android bindService無法啓動或不運行的問題

今天調用一個服務,一個是使用StartService,啓動正常,一個是使用bindService啓動不正常,很奇怪,因爲在別的程序裏面是正常的,百思不得其解

後來得到了答案,原因是我使用了TabActivity,但是我的Activity是當前TabActivity裏的子Activity,這是android的BUG,其實也不能算是BUG,解決方法就是使用

this.getApplicationContext().bindService就可以了

具體看我查到的引用地址:http://hi.baidu.com/runsheng2005/blog/item/5ac6af09203f82d63ac76371.html,感謝原作者

Nothing is impossible!^oudi&orange^
 

如果使用TabActivity來進行開發,並且程序需要針對TabActivity中TabHost中的每一個Activity單獨綁定一個Service,通常做法是在對應Tab頁的Activity的onCreate()方法中進行bind service 操作,但是通過實踐表明這個方法是無法達到綁定效果,Google Android Issue中有這個缺陷,缺陷詳細信息在這裏(Google Android Issue 2483)

解決方法:

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

即在TabActivy的TabHost中的Activity如果需要bindService的話,需要先調用getApplicationContext()獲取其所屬的Activity的上下文環境才能正常bindService,也就是在onCreate()方法中使用this.getApplicationContext().bindService([args…])就可以了,否則bindService將永遠失敗返回false,remote service 返回也爲null。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章