文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>aidl服务与Activity的通讯

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;
        }
    };
}
相关阅读 更多 +
排行榜 更多 +
猎枪行动

猎枪行动

飞行射击 下载
导弹袭击

导弹袭击

飞行射击 下载
猫猫突围封锁要塞新手打法

猫猫突围封锁要塞新手打法

飞行射击 下载