AIDL demo

343 阅读1分钟

1 RemoteApp和LocalApp使用相同的aidl文件(包名和文件名都一样)

package com.song.test.RemoteTimeService.aidl
interface IRemoteTimeService{

    /**
     * 获取当前时间
     */
     String requestCurrentTime();
}

2 在RemoteApp中暴露出一个service并在onBind()的时候返回IRemoteTimerService.Sub

public class RemoteTimeService extends Service {

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

    class RemoteBinder extends IRemoteTimeService.Stub {

        public String requestCurrentTime(){
            return "remote time " +System.currentTimeMillis();
        }
    }
}

3 RemoteApp中启动RemoteTimeService, 记得AndroidManifest.xml中声明一下

<service android:name="com.song.test.RemoteTimeService" android:process=":remote" android:exported="true" />

startService(new Intent(this, RemoteTimeService.class));

4 LocalApp中粘贴一份IRemoteTimeService.aidl文件然后sync project会生成aidl的实现,之后绑定远程服务就可以调用远程进程中的方法了

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.song.test","com.song.test.RemoteTimeService"));

ServiceConnection conn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        try {
            IRemoteTimeService adService = IRemoteTimeService.Stub.asInterface(iBinder);

            String s = adService.requestCurrentTime();
            Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

    }
};
bindService(intent, conn, Service.BIND_AUTO_CREATE);

注意事项:

1 bindService()的时候的intent在setComponent() 一定要设置包名和远程服务的全类名

2 RemoteApp中的service一定要指定 android:exported="true"

3 IRemoteTimeService中方法传递对象,需要把对象实现parceble

4 aidl文件只是一个接口文件,定义remote和local的通信协议