一、代码实现
① 创建一个AIDL接口,并写入抽象方法
package com.example.myaidltest;
interface myAIDL {
void testMethod();
}
② 创建一个远程Service,在Service中创建一个类继承AIDL接口中的Stub类并实现Stub中的抽象方法,最后不要忘记在onBind中返回这个类的对象
public class AIDLRemoteService extends Service {
private static final String TAG = "AIDLRemoteService";
private final myAIDL.Stub mBinder=new myAIDL.Stub(){
@Override
public void testMethod() throws RemoteException {
Log.d(TAG, "testMethod: "+"this is myAIDLTest");
}
};
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
//START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。
//随后系统会尝试重新创建service,由于服务状态为开始状态,
//所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。
//如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null
return START_STICKY;
}
@Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
}
}
③ AndroidManifes配置
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myaidltest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name=".AIDLRemoteService"/>
</application>
</manifest>
这里关注下 android:process 作用
===> Android之Service设置android:process作用
④ 在要调用的地方绑定该Service,将Service返回的Binder对象转换成AIDL接口所属的类型,接着直接调用AIDL的方法。
//在成功连接之后,将Service返回的Binder对象转换成AIDL接口所属的类型
private myAIDL mMyAIDL;
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e(TAG, "onServiceConnected");
mMyAIDL = myAIDL.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e(TAG, "onServiceDisconnected");
mMyAIDL = null;
}
};
//在调用处直接使用
btnStartMethod.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mMyAIDL.testMethod();
} catch (RemoteException e) {
Toast.makeText(MainActivity.this, "服务被异常杀死,请重新开启。", Toast.LENGTH_SHORT).show();
}
}
});