10月9日Android学习笔记:活动与服务之间的通信
最近在照着《第一行代码》这本书来学安卓,顺便记下笔记。主要的内容是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学习笔记:活动与服务之间的通信的更多相关文章
- 2015年10月22日CSS学习笔记
XHTML1.0对HTML4.0的改进 借鉴了XML的写法,语法更加严格. 把页面的内容和样式分离了,废弃了html4中的表示样式的标签和属性.推荐使用css来描述页面的样式. CSS样式的优先级 ! ...
- 2016年3月16日Android学习笔记
1.Jdk1.7以上switch语句中才能用字符串,在Android Studio中我改正了jdk的版本为1.8,但是还是出同样的错误,原来我用的sdk版本是4.4的,改成5的就没有问题了. 2.引入 ...
- 2016年3月17日Android学习笔记
1.Java.io.ByteArrayOutputStream.writeTo()方法实例 java.io.ByteArrayOutputStream.writeTo(OutputStream out ...
- 2016年3月12日Android学习笔记
1. //此句不能忘,否则onFling左右滑动不起作用 mLlExamView.setLongClickable(true); mLlExamView.setOnTouchListener(new ...
- SPSS 2019年10月24日 今日学习总结
2019年10月24日今日课上内容1.SPSS掌握基于键值的一对多合并2.掌握重构数据3.掌握汇总功能 内容: 1.基于键值的一对多合并 合并文件 添加变量 合并方法:基于键值的一对多合并 变量 2. ...
- [2018-11-03]2018年10月28日宁波dotnet社区活动回顾及下次活动预告
离上次活动,有半年了,汗.之后尽量保证每月一次,以组织为主,多邀请嘉宾来分享. 本次活动不足之处 人手不足:由于活动组织事项受限于人手(目前就我一个,这次活动前后我又应邀给大红鹰学院应届生介绍dotn ...
- 2016年3月1日Android实习笔记
1:经查资料,Android中gif动画加载共有两种 1)利用WebView,WebView 主要调用三个方法:LoadUrl.LoadData.LoadDataWithBaseURL 2)主要用的是 ...
- 2016年3月11日Android学习日记
1.调试技巧:当一次调试过后,可以在App重新返回当前的状态,然后再调试,而不用再点击Android studio的Debug按钮. 参考:http://www.2cto.com/kf/201506/ ...
- 2016年3月4日Android实习笔记
1.让水平LinearLayout中的两个子元素分别居左和居右 在LinearLayout中有两个子元素,LinearLayout的orientation是horizontal.需要让第一个元素居左, ...
随机推荐
- c++ type_info and typeid
c++ type_info and typeid typeid 关键字typeid提供了对一个对象查询类型的功能. 该关键字和dynami_cast一起提供了c++的RTTI(rumtime type ...
- Maven打包pom里面配置exclude 排除掉环境相关的配置文件
Maven打包pom里面配置exclude 排除掉环境相关的配置文件 有几种方式:1. 打包时,指定环境参数把环境的配置文件复制过去2. 不打包所有的环境相关的配置文件,直接由运维的人维护 可以在上传 ...
- Create and Use Custom Attributes
http://www.codeproject.com/Articles/1811/Creating-and-Using-Attributes-in-your-NET-applicat Create a ...
- html5 Web Storage(localStorage(),sessionStorage())
Web Storage包括了两种存储方式:sessionStorage和localStorage sessionStorage 是会话级别的存储,这些数据只有在同一个会话中的页面才能访问并且当会话结束 ...
- asp.net服务控件的生命周期
1. 初始化 - Init事件 (OnInit 方法) 2. 加载视图状态 - LoadViewState方法 3. 处理回发数据 - LoadPostData方法 对实现 ...
- ASP。net treeview xml
this.TreeView2.ShowLines = false; //显示连接子节点与父节点之间的线条 TreeNodeBinding area = new TreeNodeBinding(); a ...
- php程序员的水平 看看自己属于那个级别的
文章链接:http://www.oschina.net/question/570781_60150?sort=time&p=4#answers
- 从零开始学iPhone开发(5)——使用MapKit
(转)Leonbao:MapKit学习笔记 1.概述插入MapView,设置Delegate(一般为Controller),Annotations记录兴趣位置点(AnnotationView用来显示兴 ...
- [渣译文] 使用 MVC 5 的 EF6 Code First 入门 系列:排序、筛选和分页
这是微软官方教程Getting Started with Entity Framework 6 Code First using MVC 5 系列的翻译,这里是第三篇:排序.筛选和分页 原文:Sort ...
- jquery总结04-DOM节点操作
一般js操作节点 ①创建节点(元素文本)document.createElement innerHTML ②添加属性 setAttribute ③加入文档 appendChild 操作繁琐还有兼容性 ...