1、定义AIDL接口:在src/main/aidl
目录下创建AIDL文件,例如IExampleService.aidl
如下:
package com.example.aidl; interface IExampleService { String getStringFromService(); void sendStringToService(String input); }
2、实现AIDL接口:在服务端实现这个接口,在一个Service类中,重写接口的方法。
package com.example.aidl; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class ExampleService extends Service { private final IExampleService.Stub mBinder = new IExampleService.Stub() { @Override public String getStringFromService() { return "Hello from Service!"; } @Override public void sendStringToService(String input) { Log.d("ExampleService", "Received: " + input); } }; @Override public IBinder onBind(Intent intent) { return mBinder; } }
3、创建服务:在AndroidManifest.xml
中注册服务。
<service android:name=".ExampleService" />
4、在客户端绑定服务:在客户端Activity中,绑定到这个服务,获取AIDL接口的实例。
package com.example.aidl; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private IExampleService mService; private boolean mBound = false; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { mService = IExampleService.Stub.asInterface(service); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mService = null; mBound = false; } }; @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, ExampleService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); if (mBound) { unbindService(mConnection); mBound = false; } } // 其他代码,例如调用服务方法 }
5、调用服务方法:在需要调用服务的方法时,通过AIDL接口进行调用。
if (mBound) { String response = mService.getStringFromService(); Log.d("MainActivity", "Response from service: " + response); mService.sendStringToService("Hello from client!"); }
1、什么是AIDL?
答:AIDL(Android Interface Definition Language)是Android提供的一种机制,允许开发者定义接口,以便不同进程的组件能够相互通信,使用AIDL,你可以轻松传递复杂的数据类型,如对象、数组等。
2、AIDL支持哪些数据类型?
答:AIDL支持的数据类型包括八种基本数据类型(byte、char、short、int、long、float、double、boolean)、String、CharSequence、List和Map,List和Map承载的数据必须是AIDL支持的类型,或者是其它声明的AIDL对象。