最近在照着《第一行代码》这本书来学安卓,顺便记下笔记。主要的内容是Android中服务的第二种启动方式,通过活动绑定服务来启动服务,实现活动与服务之间的通信。

一. 首先创建一个服务类

 public class MyService extends Service{

     private DownloadBinder mBinder=new DownloadBinder();

     class DownloadBinder extends Binder{
public void startDownload(){
Log.d("MyService", "start download");
} public int getProgress(){
Log.d("MyService", "getProgress executed");
return 0;
}
} public IBinder onBind(Intent intent){
return mBinder;
} public void onCreate(){
super.onCreate();
Log.d("MyService", "onCreate executed");
} public int onStartCommand(Intent intent, int flags,int startId){
Log.d("MyService", "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
} public void onDestroy(){
Log.d("MyService", "onDestroy executed");
super.onDestroy();
}
}

在MyService里重写onCreate(), onStartCommand(), onDestroy()和onBind()方法,这里重点要说下的是onBind()方法,它会在服务被绑定时执行,并且返回一个实现了IBinder接口的实例。这里在MyService中新建了DownloadBinder继承Binder并将其作为onBind()方法的返回值。

二. 在活动的布局中加入两个按钮用于绑定服务和解除绑定服务

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.servicetest.MainActivity" > <Button
android:id="@+id/bind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bind Service"/> <Button
android:id="@+id/unbind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Unbind Service"/> </LinearLayout>

之后修改MainActicity中的代码

public class MainActivity extends Activity implements OnClickListener{

    private Button bindService;
private Button unbindService;
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection=new ServiceConnection() { @Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub } @Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
downloadBinder=(MyService.DownloadBinder)service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindService=(Button)findViewById(R.id.bind_service);
unbindService=(Button)findViewById(R.id.unbind_service);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
} //启动和停止服务
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {case R.id.bind_service:
Intent bindIntent=new Intent(this,MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
break;
case R.id.unbind_service:
unbindService(connection);
break;
default:
break;
}
} }

这里的要点:1. ServiceConnection类         2. Activity中的bindService和unbindService方法

自己的总结:Activity调用自己的bindService方法去绑定服务Service,这个方法里需要3个参数。既然是Activity和Service的绑定,那么这两个类的对象是一定要的,可以将这两个用一个Intent传入。还需要一个对象来代表两者之间的连接,所以第二个参数需要一个ServiceConnection的实例,这个类有两个方法:onServiceConnected和onServiceDisconnected分别在Activity绑定Service和接触绑定时执行。onServiceConnected(ComponentName name, IBinder service)这个方法里的第二个参数应该就是Service在绑定时执行onbind方法时返回的IBinder。

最后控制台的输出:

10月9日Android学习笔记:活动与服务之间的通信的更多相关文章

  1. 2015年10月22日CSS学习笔记

    XHTML1.0对HTML4.0的改进 借鉴了XML的写法,语法更加严格. 把页面的内容和样式分离了,废弃了html4中的表示样式的标签和属性.推荐使用css来描述页面的样式. CSS样式的优先级 ! ...

  2. 2016年3月16日Android学习笔记

    1.Jdk1.7以上switch语句中才能用字符串,在Android Studio中我改正了jdk的版本为1.8,但是还是出同样的错误,原来我用的sdk版本是4.4的,改成5的就没有问题了. 2.引入 ...

  3. 2016年3月17日Android学习笔记

    1.Java.io.ByteArrayOutputStream.writeTo()方法实例 java.io.ByteArrayOutputStream.writeTo(OutputStream out ...

  4. 2016年3月12日Android学习笔记

    1. //此句不能忘,否则onFling左右滑动不起作用 mLlExamView.setLongClickable(true); mLlExamView.setOnTouchListener(new ...

  5. SPSS 2019年10月24日 今日学习总结

    2019年10月24日今日课上内容1.SPSS掌握基于键值的一对多合并2.掌握重构数据3.掌握汇总功能 内容: 1.基于键值的一对多合并 合并文件 添加变量 合并方法:基于键值的一对多合并 变量 2. ...

  6. [2018-11-03]2018年10月28日宁波dotnet社区活动回顾及下次活动预告

    离上次活动,有半年了,汗.之后尽量保证每月一次,以组织为主,多邀请嘉宾来分享. 本次活动不足之处 人手不足:由于活动组织事项受限于人手(目前就我一个,这次活动前后我又应邀给大红鹰学院应届生介绍dotn ...

  7. 2016年3月1日Android实习笔记

    1:经查资料,Android中gif动画加载共有两种 1)利用WebView,WebView 主要调用三个方法:LoadUrl.LoadData.LoadDataWithBaseURL 2)主要用的是 ...

  8. 2016年3月11日Android学习日记

    1.调试技巧:当一次调试过后,可以在App重新返回当前的状态,然后再调试,而不用再点击Android studio的Debug按钮. 参考:http://www.2cto.com/kf/201506/ ...

  9. 2016年3月4日Android实习笔记

    1.让水平LinearLayout中的两个子元素分别居左和居右 在LinearLayout中有两个子元素,LinearLayout的orientation是horizontal.需要让第一个元素居左, ...

随机推荐

  1. SQL Server错误与事务处理

    T-SQL中出现的错误,依据和事务的关系,可以分为两种情况: 有的错误会导致发生错误位置之后的代码不再执行,如果错误位置在事务中,该事务也会自动回滚(即在错误位置之后的rollback语句不会执行,但 ...

  2. SD卡读写遇到的一些函数

    SD_SPI_ReadWriteByte(0XFF): 你的数据线写0xff,就是一直保持高,clk就有了8个,可以说只是发送的数据是0xff,这又不是SD的命令,但是它必须要靠控制器提供时钟才能工作 ...

  3. 如何学习Python

    [整理]如何学习Python + 如何有效利用Python有关的网络资源 + 如何利用Python自带手册(Python Manual) http://www.crifan.com/howto_lea ...

  4. ECMAScript 6教程 (二) 对象和函数

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出 原文连接,博客地址为 http://www.cnblogs.com/jasonnode/ .该系列课程是 ...

  5. TextToSpeech之阅读文字

    创建阅读类 /** * Created by RongGuang on 2014-11-21. * 中文朗读 */ public class ChineseToSpeech { private Tex ...

  6. dataURI V.S. CSS Sprites 移动端

    英文原文:http://www.mobify.com/blog/css-sprites-vs-data-uris-which-is-faster-on-mobile/ 中文翻译:http://www. ...

  7. 注册、卸载DLL

    注册.卸载DLL,一般命令写在bat文件中,下面以注册.卸载SWFToImage.DLL为例. 1.注册文件(Install.bat)内容: REM copying files to the syst ...

  8. webApp移动开发之REM

    最近发现一偏很好的文章,关于webAPP开发REM 一个css单位: 来自腾讯ISUX; web app变革之rem

  9. 【转】Struts1.x系列教程(7):Logic标签库

    转载地址:http://www.blogjava.net/nokiaguy/archive/2009/01/archive/2009/01/archive/2009/01/archive/2009/0 ...

  10. java并发编程参考资料

    1.java编程思想 2.java并发编程实战 3.java并发编程的艺术 4.http://www.infoq.com/cn/author/%E7%A8%8B%E6%99%93%E6%98%8E#文 ...