歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 的Activity和Service之間的通信

Android 的Activity和Service之間的通信

日期:2017/3/1 9:57:16   编辑:Linux編程

在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 = 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;

上面只是描述了如何由Acitity向Service發送消息,如果Service向Activity發送消息則可借助於BroadcastReceiver實現,BroadcastReceiver比較簡單,前面在將Service中已有提及。

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved