使用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() 就會被調用。

相關文章
相關標籤/搜索