使用bindService启动服务

http://que2010.iteye.com/blog/1339791 html

http://www.cnblogs.com/sipher/articles/2567697.html android

今天调用一个服务,一个是使用StartService,启动正常,一个是使用bindService启动不正常,很奇怪,由于在别的程序里面是正常的,百思不得其解

后来获得了答案,缘由是我使用了TabActivity,可是个人Activity是当前TabActivity里的子Activity,这是android的BUG,其实也不能算是BUG,解决方法就是使用 app

this.getApplicationContext().bindService就能够了 this

若是使用TabActivity来进行开发,而且程序须要针对TabActivity中TabHost中的每个Activity单独绑定一个Service,一般作法是在对应Tab页的Activity的onCreate()方法中进行bind service 操做,可是经过实践代表这个方法是没法达到绑定效果,Google Android Issue中有这个缺陷,缺陷详细信息在这里(Google Android Issue 2483) google

 

解决方法: spa

Using getApplicationContext().bindService instead of just bindService on your activity solves the problem as it is using the higher level application context. code

 

即在TabActivy的TabHost中的Activity若是须要bindService的话,须要先调用getApplicationContext()获取其所属的Activity的上下文环境才能正常bindService,也就是在onCreate()方法中使用this.getApplicationContext().bindService([args…])就能够了,不然bindService将永远失败返回false,remote service 返回也为null。 htm

onServiceConnected,onServiceDisconnected blog

①Service中须要建立一个实现IBinder的内部类(这个内部类不必定在Service中实现,但必须在Service中建立它)。
在OnBind()方法中需返回一个IBinder实例,否则onServiceConnected方法不会调用。 ip

②ServiceConnection 的回调方法onServiceDisconnected() 在链接正常关闭的状况下是不会被调用的, 该方法只在Service 被破坏了或者被杀死的时候调用. 例如, 系统资源不足, 要关闭一些Services, 恰好链接绑定的 Service 是被关闭者之一,  这个时候onServiceDisconnected() 就会被调用。

相关文章
相关标签/搜索