AIDL

#AIDL是什么
AIDL (Android Interface Definition Language), Android接口定义语言,Android提供的IPC (Inter Process Communication,进程间通信)的一种独特实现。


#什么时候要使用AIDL
使用AIDL只有在你允许来自不同应用的客户端跨进程通信访问你的service,并且想要在你的service种处理多线程的时候才是必要的。 如果你不需要执行不同应用之间的IPC并发,你应该通过实现Binder建立你的接口,或者如果你想执行IPC,但是不需要处理多线程。那么使用Messenger实现你的接口。


#使用AIDL步骤

  1. 建立.aidl文件。这个文件使用方法签名定义了语言接口。
  2. 实现接口。Android SDk工具基于你的.aidl文件使用java语言生成一个接口。这个接口有一个内部抽象类,叫做Stub,它是继承Binder并且实现你AIDL接口的。你必须继承这个Stub类并且实现这些方法。
  3. 暴露接口给客户端。实现一个服务并且重载onBind()方法,在onBind()中返回Stub类的实现。

你的.aidl文件必须被复制到其他应用程序中来让他们访问你service的接口,你必须维护原始接口的支持(向后兼容)。


#实例讲解
这个例子做的事情很简单,只有两个按钮,一个显示一段内容,这个内容通过AIDL从服务中获取,另外一个按钮用来退出服务和应用。
项目目录大概如图:
项目目录

1.在项目中建立.aidl文件
IMyAidlInterface.aidl

interface IMyAidlInterface {
    void setName(String name);
    void setAge(int age);
    String display();
}

这里只有三个简单的方法,分别是设置名字、年龄和展示内容。
然后当你编译你的应用时,Android SDK工具生成一个.java接口文件用你的.aidl文件命名生成的接口包含一个名字为Stub的子类,这是一个它父类的抽象实现,并且声明了.aidl中所有的方法。

2. 创建IMyAidlInterfaceImpl类实现扩展IMyAidlInterface.java里的方法,暴露其接口

public class IMyAidlInterfaceImpl extends IMyAidlInterface.Stub {
    private String name;
    private int age;

    @Override
    public void setName(String name) throws RemoteException {
        this.name = name;
    }

    @Override
    public void setAge(int age) throws RemoteException {
        this.age = age;
    }

    @Override
    public String display() throws RemoteException {
        return "Name:" + name + "\nAge:" + age;
    }

3.创建一个service来返回AIDL接口供客户端使用

public class RemoteService extends Service {
    private IMyAidlInterface.Stub iMyAidlInterface = new IMyAidlInterfaceImpl();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return iMyAidlInterface;
    }
}

重载onBind,返回AIDL接口。

4.修改mail.xml,添加两个Button

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_aidl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="AIDL"
        android:textSize="30sp" />

    <Button
        android:id="@+id/btn_exit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_aidl"
        android:text="EXIT"
        android:textSize="30sp" />
</RelativeLayout>

5.修改AndroidManifest.xml,添加服务

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.uidq0161.aidltest">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".RemoteService">
            <intent-filter>
                <action android:name="com.android.aidl.action.MY_REMOTE_SERVICE" />
            </intent-filter>
        </service>
    </application>
</manifest>

6.在主Activity中实现service的绑定和AIDL接口的调用

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private IMyAidlInterface iMyAidlInterface;//接口
    private Button btn_aidl, btn_exit;

    // 实例化ServiceConnection
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);// 获得接口
            if (iMyAidlInterface != null)
                try {
                    // RPC 方法调用
                    iMyAidlInterface.setName("lyh.");
                    iMyAidlInterface.setAge(18);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("TAG", "Unbind service.");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_aidl = (Button) findViewById(R.id.btn_aidl);
        btn_exit = (Button) findViewById(R.id.btn_exit);
        btn_aidl.setOnClickListener(this);
        btn_exit.setOnClickListener(this);

        Intent intent = new Intent(); // 实例化Intent
        intent.setAction("com.android.aidl.action.MY_REMOTE_SERVICE");// 设置Intent Action 属性
        intent.setPackage(getPackageName());
        bindService(intent, conn, Service.BIND_AUTO_CREATE);// 绑定服务
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_aidl:
                String msg = "";
                try {
                    msg = iMyAidlInterface.display();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_exit:
                unbindService(conn);//断开服务
                conn = null;
                finish();
                break;
            default:
                break;
        }
    }
}

在 binderService调用后,onServiceConnected会自动调用,其中参数service 就是RemoteService中onBind返回的值。

运行结果图:
运行结果

源码下载

参考
参考
好文

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值