Android中bindService的使用方法
来源:互联网 发布:拍卖系统源码 编辑:程序博客网 时间:2024/05/21 17:07
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的异常。
- Android中bindService的使用方法
- Android中bindService的使用方法
- Android中bindService的使用方法
- Android中bindService的使用方法
- Android中bindService的使用方法
- Android开发:bindService的使用方法
- Android中bindService基本使用方法概述
- android中bindService的使用
- bindService的使用方法
- bindService的使用方法
- bindService的使用方法
- Android中BindService方式使用的理解
- Android中BindService方式使用的理解
- Android中BindService方式使用的理解
- android项目中bindService失败的原因
- Android中BindService方式使用的理解
- Android中BindService方式使用的理解
- Android中BindService方式使用的理解
- java中hashCode方法与equals方法的用法总结
- 使用UNIVOCITY-PARSERS创建和读取CSV文件
- 第三方APP微信支付Java服务端构建步骤
- 第7章 证据的效力如何
- 写给嵌入式程序员的循环冗余校验(CRC)算法入门引导
- Android中bindService的使用方法
- *leetcode #90 in cpp
- how to use cmake
- CodeForces - 676A Nicholas and Permutation (模拟) 水
- c++ stl容器set成员函数介绍及set集合插入,遍历等用法举例
- AngularJS数据绑定
- ViewPage和Fragment上 实现BadgeView消息提醒(仿旧微信)
- 解决eclipse中查看android工程代码出现android.jar has no source attachment
- JAVA MD5加密