aidl服务与Activity的通讯
时间:2010-12-26 来源:蚂蚁搬家
MyServiceBinder.aidl
interface MyServiceBinder { boolean startCaculate(); boolean stopCaculate();
//下面两个函数用来注册,注销回调函数
boolean registerObserver(MyServiceObserver observer);
boolean unregisterObserver(); }
定义Observer的aidl文件
MyServiceObserver.aidl
interface MyServiceObserver { notifyComplete(int result); }
接口定义完后需要在Service中实现相应的接口:
public class MyService extends Service { //skip other function, just show the implements of interfaces defined in aidl file.
private MyServiceObserver mObserver = null; private final MyServiceBinder.Stub mBinder = new MyServiceBinder.Stub()
{
public void startCaculate()
{
int result;
//Method should be implement
if(mObserver != null)
mObserver.notifyComplete(result);
}
public void stopCaculate()
{
}
public void registerObserver(MyServiceObserver observer)
{
mObserver = observer;
}
public void unregisterObserver()
{
mObserver = null;
}
}; }
对于MyServiceObserver的定义和ServiceConnection可以在Activity中实现:
public class MyActivity extends Activity { private MyServiceBinder mServiceBinder; private MyServiceObserver mObserver = new MyServiceObserver.Stub() { public void notifyCompleted(int result) { Log.i("NOTICE", "Service returned result:"+result); } }; private ServiceConnection mServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { mServiceBinder = MyServiceBinder.Stub.asInterface(service); mServiceBinder.registerObserver(mObserver); } public void onServiceDisconnected(ComponentName className) { mServiceBinder.unregisterObserver(); mServiceBinder = null; } }; }
相关阅读 更多 +