使用android中的AIDL让Service与Activity通信(service回调activity)

这几天搞了搞AIDL,终于弄明白了在AIDL中让Service调用Activity的方法
代码:

首先建立一个ICallback.aidl文件,作为Activity中的回调方法

package com.zhang.test.service;

     interface ICallback {
     void showResult(int result);
     }

然后再建立一个IService.aidl用来在Activity中接收Service回调,以及在Service中onBind时返回的Binder
注意:aidl中import不能写com.xxx.*,要写全类的路径

package com.zhang.test.service;
 
     import com.zhang.test.service.ICallback;
 
     interface IService {
             void registerCallback(ICallback cb);
             void unregisterCallback(ICallback cb);
     }
接下来是service:
MainService.java

package com.zhang.test.service;
 
      import android.app.Service;
      import android.content.Intent;
      import android.os.Handler;
      import android.os.IBinder;
      import android.os.Message;
      import android.os.RemoteCallbackList;
      import android.os.RemoteException;
     import android.util.Log;
 
     public class MainService extends Service {
 
         private static final String TAG = "MainService";
 
         private RemoteCallbackList<icallback> mCallbacks = new RemoteCallbackList<icallback>();
 
         private IService.Stub mBinder = new IService.Stub() {
 
             @Override
             public void unregisterCallback(ICallback cb){
                 if(cb != null) {
                     mCallbacks.unregister(cb);
                }
             }
 
             @Override
             public void registerCallback(ICallback cb){
                 if(cb != null) {
                     mCallbacks.register(cb);
                 }
             }
         };
 
         @Override
         public IBinder onBind(Intent intent) {
            Log.d(TAG, "onBind");
            return mBinder;
       }
 
         @Override
         public void onCreate() {
             Log.d(TAG, "onCreate");
             //这里不知道为什么,直接使用callback方法回调showResult
             //mCallbacks.beginBroadcast()是0,需要用handler延迟1000毫秒
             //也许是在activity中binService太耗时的原因?
              mHandler.sendEmptyMessageDelayed(0, 1000);
             super.onCreate();
         }
 
         @Override
         public void onDestroy() {
             mHandler.removeMessages(0);
             mCallbacks.kill();
             super.onDestroy();
         }
 
         private void callBack() {
             int N = mCallbacks.beginBroadcast();
             try {
                 for (int i = 0; i < N; i++) {
                     mCallbacks.getBroadcastItem(i).showResult(i);
                 }
             } catch (RemoteException e) {
                 Log.e(TAG, "", e);
             }
             mCallbacks.finishBroadcast();
         }
 
         private Handler mHandler = new Handler() {
 
             @Override
             public void handleMessage(Message msg) {
                 callBack();
                 super.handleMessage(msg);
            }
         };
     }
     </icallback></icallback>
然后是activity:


package com.zhang.test;
 
     import android.app.Activity;
     import android.content.ComponentName;
     import android.content.Context;
     import android.content.Intent;
     import android.content.ServiceConnection;
     import android.os.Bundle;
     import android.os.IBinder;
     import android.os.RemoteException;
     import android.util.Log;
 
     import com.zhang.test.service.ICallback;
     import com.zhang.test.service.IService;
     import com.zhang.test.service.MainService;

     public class MainActivity extends Activity {
 
         private static final String TAG = "MainActivity";
 
         private IService mService;
 
         /** Called when the activity is first created. */
         @Override
         public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
             Intent i = new Intent(this, MainService.class);
             bindService(i, mConnection, Context.BIND_AUTO_CREATE);
         }
 
         @Override
         protected void onDestroy() {
             if(mService!=null){
                try {
                    mService.unregisterCallback(mCallback);
                 } catch (RemoteException e) {
                     Log.e(TAG, "", e);
                 }
             }
             //destroy的时候不要忘记unbindService
              unbindService(mConnection);
             super.onDestroy();
         }
 
         /**
          * service的回调方法
          */
         private ICallback.Stub mCallback = new ICallback.Stub() {
 
             @Override
             public void showResult(int result) {
                 Log.d(TAG, " result : " + result);
             }
         };

         /**
          * 注册connection
          */
         private ServiceConnection mConnection = new ServiceConnection() {
 
             @Override
             public void onServiceDisconnected(ComponentName name) {
                 Log.d(TAG, "onServiceDisconnected");
                 mService = null;
             }
 
             @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                 Log.d(TAG, "onServiceConnected");
                 mService = IService.Stub.asInterface(service);
                 try {
                     mService.registerCallback(mCallback);
                 } catch (RemoteException e) {
                     Log.e(TAG, "", e);
                 }
             }
         };
     }
最后不要忘记在manifest中加上service标记:


<service android:name=".service.MainService">
</service>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值