android 如何使用aidl

场景:同事编了个应用,我需要调用里面的功能,他给我用aidl做了接口,我要如何使用?虽然之前学习过aidl的整个流程,但顶不住记不住啊,这次把流程记录下来,方便以后查看。

service 端:

1、在我们的项目中建立aidl文件,路径,main下。具体看图片

android 如何使用aidl_第1张图片

2、android studio为我们建立了aidl的包

android 如何使用aidl_第2张图片

android 如何使用aidl_第3张图片

3、然后,我们make project,android studio 就为我们生成了对应的java文件 

android 如何使用aidl_第4张图片

4、建立一个service,实现接口,onbinder 函数内返回对象

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

    private class DeviceInfo extends IMyAidlInterface.Stub {

        @Override
        public String getDeviceCode() throws RemoteException {
            return util.getDeviceCode();
        }
    }

5、声明这个service,


      
         
      

 client端:

1、现在生成ServiceConnection,在里面拿到对象。

android 如何使用aidl_第5张图片

相关代码:

    private ServiceConctrol serviceConctrol;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            serviceConctrol = ServiceConctrol.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            serviceConctrol = null;
        }
    };

7、在合适的地方绑定服务:

Intent intent = new Intent();
intent.setAction("com.eightmile.videotrack.ServiceConctrol");
//从 Android 5.0开始 隐式Intent绑定服务的方式已不能使用,所以这里需要设置Service所在服务端的包名
intent.setPackage("com.eightmile.videotrack");
bindService(intent, serviceConnection, BIND_AUTO_CREATE);

8、可以调用对应的方法了

try {
      serviceConctrol.call();
} catch (RemoteException e) {
      e.printStackTrace();
}

9、完

注:如果是源码编译的话,直接将aidl生成的java文件拷贝过来用,ok的。至于网上教程里说的添加aidl的路径编译的,我没有成功。

也可以参考这位兄弟的:https://blog.csdn.net/chenxiaoping1993/article/details/80651849

 

参考:

https://www.cnblogs.com/huangjialin/p/7738104.html

https://www.cnblogs.com/BeyondAnyTime/p/3204119.html

 

你可能感兴趣的:(android1)