`
staroflife
  • 浏览: 20611 次
社区版块
存档分类
最新评论

android 绑定 service

 
阅读更多
(1)
一个Activity和一个Service绑定在一起,一起运行,共同消亡。
如果要想进行绑定的话,需要一个ServiceConnection接口,接口定义了2个方法,
onServiceConnected(ComponentName,IBinder) 当与一个Service建立连接的时候调用.
onServiceDisConnected(ComponentName) 当与一个Service取消连接的时候调用.
注意在连接的时候有个叫做IBinder接口的对象.
ServiceConnection接口主要的功能是当一个Activity程序与Service建立连接之后,可以通过ServiceConnection接口执行Service连接(或取消)连接的处理操作,在Activity连接到Service程序上之后,会触发Service类中的onBind()方法,在此方法中要返回一个android.os.IBinder接口的对象。

ServiceConnection con=new ServiceConnection(){
public void onServiceConnected(ComponentName,IBinder){}
public void onServiceDisConnected(ComponentName)()
};
context.bindService(new Intent(context,MyService.class),con,Context.BIND_AUTO_CREATE);
context.unbindService(con);
此时Activity程序编写完成.

第一步:启动startService后,会onCreate,再onStartCommand
第二步:调用bindService后,会onBind,onServiceConnected.

如果不启动而直接进行bindService,会onCreate,onBind,onServiceConnected.再退出程序(或调用unbindService),会onUnbind,onDestroy.

以上会有一个bug,因为如果没有服务bindService,而调用了unbindService就会出现问题。所以在解除绑定之前必须加一个判断,判断一个Activity是否和一个Service绑定在了一起,如果绑定在了一起才可以使用unbindService()方法解除绑定.做法如下:
(2)Activity中定义一个
private IBinder binder;当onServiceConnected的时候,用其参数IBinder对象去实例化它。然后判断其if(binder!=null){unbindService(con);binder=null}
class MyService extend Service(){
private IBinder bind=new Binder();
public IBinder onBind(Intent intent){
   return bind;//传给ServiceConnection的onServiceConnected的方法,变成其参数了。然后赋给Activity的属性IBinder做为一个判断是否调用过bindService去启动了服务。
}
}




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics