zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Android AIDL 一探究竟详解编程语言

Android编程语言 详解 究竟 一探 AIDL
2023-06-13 09:20:39 时间

AIDL (Android Interface Definition Language)Android接口定义语言

简述:

1、什么时候使用?


2、如何实现 AIDL 通信?

下面是项目目录结构图:客户端与服务端代码要保证 aidl 文件夹下内容的一致

Android AIDL 一探究竟详解编程语言

步骤①:创建一个AIDL文件. (在服务端)

 1 // IMyAidlInterface.aidl 

 2 package com.anglus.aidl; 

 4 // Declare any non-default types here with import statements 

 6 interface IMyAidlInterface { 

 7 /** 

 8 * Demonstrates some basic types that you can use as parameters 

 9 * and return values in AIDL. 

10 */ 

11 // 计算两个数的和 

12 int add(int num1, int num2); 

13 }

步骤②:实现自定义的AIDL 接口文件(在服务端)

 public class IRemoteService extends Service { 

 @Override 

 public IBinder onBind(Intent intent) { 

 return mIBinder; 

 private IBinder mIBinder = new IMyAidlInterface.Stub() { 

 @Override 

 public int add(int num1, int num2) throws RemoteException { 

 Log.i("IRemoteService", "收到远程的请求,传入的参数是:" + num1 + "和" + num2); 

 return num1 + num2; 

}

  一定不要忘了在 AndroidManifest.xml 文件中注册服务:

 service 

 android:name=".IRemoteService" 

 android:enabled="true" 

 android:exported="true"/ 

  步骤③: 绑定服务,得到远程服务对象,即可在客户端进行使用。

 1 private void bindService() { 

 2 // 绑定到服务 

 3 Intent intent = new Intent(); 

 4 intent.setComponent(new ComponentName("com.anglus.aidl", 

 5 "com.anglus.aidl.IRemoteService")); 

 6 bindService(intent, conn, Context.BIND_AUTO_CREATE); 

 7 } 

 9 private ServiceConnection conn = new ServiceConnection() { 

10 @Override 

11 public void onServiceConnected(ComponentName name, IBinder service) { 

12 // 拿到远程服务 

13 iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service); 

14 } 

16 @Override 

17 public void onServiceDisconnected(ComponentName name) { 

18 // 回收资源 

19 iMyAidlInterface = null; 

20 } 

21 };

  注意:在 new ComponetName() 中,第一个参数是:服务端的 项目包名;第二个参数是:要绑定的服务 包名 + 类名。

 

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/13423.html

cgojavaxml