http://linconz.net/archives/229.html
http://linconz.net/archives/314.html
首先建立一个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