Android中bindService的使用方法
2016-06-13 10:46
435 查看
bindService用于绑定一个服务。这样当bindService(intent,conn,flags)后,就会绑定一个服务。这样做可以获得这个服务对象本身,而用startService(intent)的方法只能启动服务。
bindService方式的一般过程:
①新建Service类BindService。在BindService类里新建内部类MyBinder,继承自Binder(Binder实现IBinder接口)。MyBinder提供方法返回BindService实例。
public class MyBinder extends Binder{
public BindService getService(){
return BindService.this;
}
}
实例化MyBinder得到mybinder对象;
重写onBind()方法:
@Override
public IBinder onBind(Intent intent) {
return mybinder;
}
private MyBinder mybinder=new MyBinder();
②在Activity里,实例化ServiceConnection接口的实现类,重写onServiceConnected()和onServiceDisconnected()方法
ServiceConnection conn=new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
③在Activity的onCreate()方法里,新建Intent,并绑定服务
Intent intent=new Intent(MainActivity.this,BindService.class);
bindService(intent, conn,BIND_AUTO_CREATE);
④在Activity的onDestroy里面,添加
unbindService(conn);
如果不加这一步,就会报android.app.ServiceConnectionLeaked: ******.MainActivity has leaked ServiceConnection的异常。
bindService方式的一般过程:
①新建Service类BindService。在BindService类里新建内部类MyBinder,继承自Binder(Binder实现IBinder接口)。MyBinder提供方法返回BindService实例。
public class MyBinder extends Binder{
public BindService getService(){
return BindService.this;
}
}
实例化MyBinder得到mybinder对象;
重写onBind()方法:
@Override
public IBinder onBind(Intent intent) {
return mybinder;
}
private MyBinder mybinder=new MyBinder();
②在Activity里,实例化ServiceConnection接口的实现类,重写onServiceConnected()和onServiceDisconnected()方法
ServiceConnection conn=new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
③在Activity的onCreate()方法里,新建Intent,并绑定服务
Intent intent=new Intent(MainActivity.this,BindService.class);
bindService(intent, conn,BIND_AUTO_CREATE);
④在Activity的onDestroy里面,添加
unbindService(conn);
如果不加这一步,就会报android.app.ServiceConnectionLeaked: ******.MainActivity has leaked ServiceConnection的异常。
相关文章推荐
- 解决eclipse中查看android工程代码出现android.jar has no source attachment
- Android Tools 在线更新SDK Manager
- Android入门--返回数据到前一个Activity--startActivityForResult 方法
- Android:两个Fragment在同一个Framelayout上切换显示
- Android——Android Studio导入SlidingMenu类库的方法
- Picasso源码分析(三):快照功能实现和HandlerThread的使用
- Android源码适配器模式---Activity类结构
- Android 中ViewPager 实现banner无限轮播效果
- Android 三轴绘制实时加速度曲线
- Android之开源项目工具库篇
- Android插件化方案调研与实践
- Android报错: can't load transform_config.xml
- Android绘制折线图、柱状图等
- Android 中Timer和TimeTask完成定时任务
- android下m、mm、mmm编译命令的使用
- Android之LocalSocket和LocalServerSocket的使用
- Android开发必备技能之Android数据存储(SharedPreference存储)
- 安卓获取路径
- Mac下搭建Android studio+genymotion
- 基于tiny4412搭建Android开发环境