馬上加入Android 台灣中文網,立即免費下載應用遊戲。
您需要 登錄 才可以下載或查看,沒有帳號?註冊
x
在 android中Activity負責前台界面展示,service負責後台的需要長期執行的任務。Activity和Service之間的通信主要由 IBinder負責。在需要和Service通信的Activity中實現ServiceConnection接口,並且實現其中的 onServiceConnected和onServiceDisconnected方法。然後在這個Activity中還要通過如下代碼綁定服務:- Intent intent = new Intent().setClass( this , IHRService.class );
- bindService( intent , this , Context.BIND_AUTO_CREATE );
複製代碼 當調用bindService方法後就會回調Activity的onServiceConnected,在這個方法中會向Activity中傳遞一個IBinder的實例,Acitity需要保存這個實例。代碼如下:- public void onServiceConnected( ComponentName inName , IBinder serviceBinder) {
- if ( inName.getShortClassName().endsWith( "IHRService" ) ) {
- try {
- this.serviceBinder= serviceBinder;
- mService = ( (IHRService.MyBinder) serviceBinder).getService();
- //mTracker = mService.mConfiguration.mTracker;
- } catch (Exception e) {}
-
- }
- }
複製代碼 在Service中需要創建一個實現IBinder的內部類(這個內部類不一定在Service中實現,但必須在Service中創建它)。- public class MyBinder extends Binder {
- //此方法是為了可以在Acitity中獲得服務的實例
- public IHRService getService() {
- return IHRService.this;
- }
- //這個方法主要是接收Activity發向服務的訊息,data為發送訊息時向服務傳入的對象,replay是由服務返回的對象
- public boolean onTransact( int code , Parcel data , Parcel reply , int flags ) {
- //called when client calls transact on returned Binder
- return handleTransactions( code , data , reply , flags );
- }
-
- }
複製代碼 然後在Service中創建這個類的實例:- public IBinder onBind( Intent intent ) {
- IBinder result = null;
- if ( null == result ) result = new MyBinder() ;
- return result;
- }
複製代碼 這時候如果Activity向服務發送訊息,就可以調用如下代碼向服務端發送訊息:- inSend = Parcel.obtain();
- serviceBinder.transact( inCode , inSend , null , IBinder.FLAG_ONEWAY );
複製代碼 這種方式是只向服務端發送訊息,沒有返回值的。如果需要從服務端返回某些值則可用如下代碼:- result = Parcel.obtain();
- serviceBinder.transact( inCode , inSend , result , 0 );
- return result;
複製代碼 發送訊息後IBinder接口中的onTransact將會被調用。在服務中如果有結果返回(比如下載數據)則將結果寫入到result參數中。在Activity中從result中讀取服務執行的結果。
上面只是描述了如何由Acitity向Service發送訊息,如果Service向Activity發送訊息則可借助於BroadcastReceiver實現,BroadcastReceiver比較簡單。 |
評分
-
查看全部評分
|