Service进阶与AIDL实现进程间通信

    xiaoxiao2021-03-25  105

    参考:http://blog.csdn.net/guolin_blog/article/details/9797169

    http://www.cnblogs.com/leslies2/p/5401813.html

     一,AIDL 定义

    AIDL(Android Interface Definition Language)  是Android接口定义语言,用于让某个Service与多个应用

    程序组件之间进行跨进程通信,从而实现多个应用程序共享一个Service的功能。

    二,AIDL的使用:

    1,创建AIDL文件:IRemoteService.aidl

    interface IRemoteService { /** * Request the process ID of this service, to do evil things with it. * */ int getPid(); MyProcess getProcess(in MyProcess clientProcess); /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString); }

    保存之后,会产生相应的JAVA文件 :

    2,修改RemoteService.java 实现RemoteService.Stub 接口,并且重载AIDL里面的函数:

    // 实现AIDL接口 private final Stub binder = new Stub() { @Override public int getPid() throws RemoteException { return Process.myPid(); } }

    3,在onBind()中,将RemoteService.Stub的实现返回

    @Override public IBinder onBind(Intent intent) { return binder; //暴露给客户端 }

    4,在onServiceConnected()中获得该RemoteService,并调用RemoteService的函数:

    private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { IRemote remoteService = Stub.asInterface(service); Log.i(TAG, "Client pid= " + Process.myPid()); try { Log.i(TAG, "RemoteService pid= " + remoteService.getPid()); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { } };

    5,同样的,我们可以再写一个APP,然后调用该Service中暴露出来的接口。

    AIDL类似于其他IDL。 定义client与service之间的编程接口,用于进程间通信。 android中进程之间的内存不互通。 -------------------------------------------------------------------------- 1.定义aidl文件: android studio中的目录结构: java/ aidl/ 模板: package 主包名 interface IMyAidlInterface {} //无需添加public 默认支持的数据类型(无须导包)://自定义的类型必须导包,即使同包 8中基本类型 String CharSequence List //总是用ArrayList实现。 Map //总是用HashMap实现。 方法:和普通接口一样。 --------------------------------------------------------------------- 2.在绑定Service中实现接口:编译后会在gen/目录下生产响应的.java的IBinder接口。 private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { //多了.Stub而已    //实现接口中的方法 }; ---------------------------------------------------------------------- 3.定义客户端:考虑在子线程中调用接口中的方法。 //需要导入aidl文件,生成IBinder接口。 IRemoteService mIRemoteService; private ServiceConnection mConnection = new ServiceConnection() {     public void onServiceConnected(ComponentName className, IBinder service) {         mIRemoteService = IRemoteService.Stub.asInterface(service);     }     public void onServiceDisconnected(ComponentName className) {         mIRemoteService = null;     } };

    转载请注明原文地址: https://ju.6miu.com/read-25271.html

    最新回复(0)