一、服务端
1、新建AIDL文件,定义相关接口
2、新建Service,注册到manifest文件中,并添加属性标签:
- "enabled=true"是否可以被实例化;
- "exported=true"是否能被隐式调用;
- "process=remote_server"应用程序在使用该服务的时候会自动创建一个名为"remote_server"的进程;
- 添加action唯一标识
<service
android:name=".ILoginResultService"
android:enabled="true"
android:exported="true"
android:process=":remote">
<intent-filter>
<action android:name="Action_A"></action>
</intent-filter>
</service>
3、在Service的onBind方法中返回服务的IBinder对象
public class ILoginService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.e("TAG", "<=======Service-onBind===>");
//重写登录的AIDL服务
return new ILoginInterface.Stub() {
@Override
public void login() throws RemoteException {
Log.e("TAG", "Login===>开始登录服务");
startActivity();
}
@Override
public void loginCallback(boolean isSuccess, String userName) throws RemoteException {
}
};
}
private void startActivity() {
//调起登录的主界面
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
二、客户端
1、导入AIDL文件,文件路径必须与服务端相同
2、新建Intent对象,并设置其"action"属性值为服务应用Service配置的Action属性,设置其"package"属性为服务应用的包名
3、通过bindService(intent,ServiceConnection,BIND_AUTO_CREATE)绑定服务
private void initBindService() {
//新建意图,并绑定服务B
Intent intent = new Intent();
intent.setAction("Action_B");
intent.setPackage("com.wkr.aidl_b");
bindService(intent, conn, BIND_AUTO_CREATE);
isBindService = true;
}
4、新建ServiceConnection对象,并在绑定成功的回调方法中初始化调用的服务
//新建连接
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//绑定成功,获取服务端提供的服务对象
iLogin = ILoginInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(MainActivity.this, "服务绑定失败", Toast.LENGTH_SHORT).show();
}
};
5、在需要使用的地方使用服务对象调用对应的方法
//判断是否连接成功
if (iLogin != null) {
try {
iLogin.login();
} catch (RemoteException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, "请安装服务应用B", Toast.LENGTH_SHORT).show();
}
6、在Activity的onDestroy()方法中进行解绑
@Override
protected void onDestroy() {
super.onDestroy();
if (isBindService) {
unbindService(conn);
}
}
三、AIDL相关文件
interface ILoginInterface {
void login();
void loginCallback(boolean isSuccess,String userName);
}
四、遇到相关问题
1、应用A在绑定服务的时候,不会运行ServiceConnection 的onServiceConnected()回调方法
问题原因:应用B后台没运行,无法进行绑定