Android AIDL远程服务使用示例

来源:互联网 发布:mac卸载软件后图标还在 编辑:程序博客网 时间:2024/06/04 20:11

Android AIDL远程服务使用示例

了解Android上比较强大的远程服务设计。

  一、为什么要使用AIDL,他的优势有哪些呢?

  AIDL服务更像是 一个Server,可以为多个应用提供服务。由于使用了IDL这样类似COM组件或者说中间语言的设计,可以让后续的开发者无需了解内部,根据暴漏的接口实现相关的操作,AIDL可以工作在独立的进程中。

二、学习AIDL服务需要有哪些前置知识?

  作为Android上服务的扩展,首先你要了解Android Service模型,Android Serivice我们可以分为两种模式,三个类型,1.最简单的Service就是无需处理onBind方法,一般使用广播通讯,效率比较低。2. 使用Binder模式处理Service和其他组件比如Activity通讯,Android开发网提示对于了解了Binder模式的服务后,开发AIDL远程服务就轻松容易的多。

三、具体实例,我们以com.android123.cwj.demo为工程名,首先在工程目录的com.android123.cwj目录下创建一个ICWJ.aidl文件,内容为

  package com.android123.cwj;

  interface ICWJ {

  String getName();

}

  如果格式AIDL格式没有问题,在Eclipse中ADT插件会在工程的gen目录下会自动生成一个Java实现文件。

在Service中代码如下:

public class CWJService extends Service {

public static final String BIND = "com.android123.cwj.CWJService.BIND"; 

public String mName="android123";

private final ICWJ.Stub mBinder = new ICWJ.Stub()
  {

     @Override
     public String getName() throws RemoteException
     {    //重写在AIDL接口中定义的getName方法,返回一个值为我们的成员变量mName的内容。
        try
        {
          return CWJService.this.mName;
        }
        catch(Exception e)
        {
           return null;
        }
    }

};

  @Override
  public void onCreate() {
   Log.i("svc", "created.");
  }

  @Override
  public IBinder onBind(Intent intent) {
     return mBinder;    //这里我们要返回mBinder而不是一般Service中的null
  }

}

接着在AndroidManifest.xml文件中定义

<service android:name=".CWJService">
   <intent-filter>
    <action android:name="com.android123.cwj.CWJService.BIND" />
    <category android:name="android.intent.category.DEFAULT"/>
   </intent-filter>
  </service>

接下来在Activity中的调用,我们可以

   private ICWJ objCWJ = null;

   private ServiceConnection serviceConn = new ServiceConnection() {

  @Override
  public void onServiceDisconnected(ComponentName name) {
   }

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
   objCWJ = ICWJ.Stub.asInterface(service);
  }
};

在Activity的onCreate中加入绑定服务的代码

  Intent intent = new Intent();
  intent.setClass(this, CWJService.class);
  bindService (intent, serviceConn, Context.BIND_AUTO_CREATE);

  同时重写Activity的onDestory方法

    @Override
    public void onDestroy() {
         unbindService(serviceConn);  // 取消绑定
     super.onDestroy();
    }

执行AIDL的getName可以通过下面的方法

   if (objCWJ == null)
   {
       try {
            String strName = obj.getName();
       }
       catch (RemoteException e)
       {}
   }

原创粉丝点击