aidl是进程间的一种通信方式.针对进程间的通信,都可以理解为客户端和服务端的通信。
1.服务端的建立
1.1 首先创建aidl文件,如下:
ITest.aidl的内容如下:
interface ITest { /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ void helloAidl(); }
注意aidl文件夹,在main目录下与java目录同级。
1.2 既然是服务端,那就需要创建一个服务。
在 AndroidManifset.xml中添加,服务申明
<service android:name=".MyAidlService" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="xxxxxxx" /> // 这个东西相当与标记你的这个服务 <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </service>
服务类中:
public class MyAidlService extends Service { public MyAidlService() {} @Override public IBinder onBind(Intent intent) { return new ITest.Stub() { @Override public void helloAidl() throws RemoteException { // 方法实现内容 } }; } }
2. 客户端的创建
2.1 将服务端的aidl目录拷贝到客户端的工程中的main目录下,或者在客户端的main目录下创建一个跟服务端aidl目录内容一样的aidl目录。(总之这两个aidl目录包括内容要一摸一样)
ITest.aidl的内容如下:
interface ITest { /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ void helloAidl(); }
注意:一模一样
2.2 绑定服务端
2.2.1 服务端的连接与绑定服务端
private ITest mITest = null; private ServiceConnection mServiceConnectionconn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mITest = ITest.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) {} };
private void attemptToBindService() { Intent intent = new Intent(); intent.setAction("xxxxxxx"); // 服务端 AndroidManifset.xml中service申明的action intent.setPackage("服务端包名"); bindService(intent, mITest, Context.BIND_AUTO_CREATE); }
调用attemptToBindService() 函数就可以绑定服务端,绑定后就通过 mITest.helloAidl() 这样来调用服务端的函数.