Service的使用(三)绑定服务
2016-07-22 09:56
330 查看
创建Bound Service
关键类:Binder:活动与服务通信的接口,在Service中定义
ServiceConnection:服务生命周期的回调接口,在服务创建和销毁时回调他的方法。
定义服务
public class MyService extends Service { private DownloadBinder mBinder = new DownloadBinder(); //定义Binder接口 class DownloadBinder extends Binder { public void startDownload() { Log.d("MyService", "startDownload executed"); } public int getProgress() { Log.d("MyService", "getProgress executed"); return 0; } } @Override public IBinder onBind(Intent intent) { return mBinder; } …… }
启动服务
定义ServiceConnection
@Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name,IBinder service) { //获取Service里面的binder接口实例,进行通信 downloadBinder = (MyService.DownloadBinder) service; downloadBinder.startDownload(); downloadBinder.getProgress(); }
绑定与解绑
绑定
Intent bindIntent = new Intent(this, MyService.class); //第一个参数是Intent,第二个是ServiceConnection,第三个是标志位: //这里表示在活动和服务进行绑定后自动创建服务,即会调用onCreate但不会调用startCommand bindService(bindIntent, connection, BIND_AUTO_CREATE);
解绑
//只要一个参数就是ServiceConntion unbindService(connection)
相关文章推荐
- IIS7+MVC 基于Windows身份验证,反应很慢
- org.springframework.web.context.ContextLoaderListener
- C# new virtual和override 区别
- brew 安装
- java 字符串系列化及反系列化 (未测试)
- Copy List with Random Pointer
- spring工程中得到注入bean的集中方式
- HTML学习笔记1.15—合并单元格
- FileOutputStream,OutputStreamWriter, BufferedWriter为什么连用?
- Topological Sorting
- 搭建spring+mybatis+struts2环境的配置文件
- HTML基础笔记(推荐)
- weex&ReactNative对比
- ios基于UIScrollView实现滑动引导页
- MyBatis 批量插入数据
- Warning: bind(): React component methods may only be bound to the component instance. See ...
- Java实现——Dom4j读写XML文件
- IOS 解决UIButton 点击卡顿/延迟的问题
- Java实现——Dom4j读写XML文件
- 【Promise】Promise实现请求超时处理(加强版)