先看效果图,下面是广播和AIDL跨进程的方法
我们先创建AIDL文件定义接口方法
定义好接口方法如下图:
// ITokenAidlInterface.aidl
package com.example.aidldemo;
// Declare any non-default types here with import statements
interface ITokenAidlInterface {
//同步登录token到客户端的方法
void postLoginToken(in String accessToken);
}
然后将aidl整个文件夹赋值到需要跨进程的另外一个项目中如下图
然后我们将两个项目都同步或者gradle下,两个项目都会自动生成刚刚AIDL文件的Java代码
好了我们可以在需要接收数据的接收端定义服务类了
package com.example.app_server;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import androidx.annotation.Nullable;
import com.example.aidldemo.ITokenAidlInterface;
/**
* @author xiayiye5
* @date 2021/11/30 16:11
*/
public class AIDLTokenService extends Service {
private static final String TAG = "AIDLTokenService";
ITokenAidlInterface.Stub stub = new ITokenAidlInterface.Stub() {
@Override
public void postLoginToken(String accessToken) throws RemoteException {
Log.d(TAG, "获取到的登录token:" + accessToken);
Intent intent = new Intent(AIDLTokenService.this, ServerActivity.class);
intent.putExtra("accessToken", accessToken);
startActivity(intent);
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return stub;
}
}
然后需要在清单文件配置下服务,注意action这个一定要记住
<service
android:name=".AIDLTokenService"
android:exported="true">
<intent-filter>
<!--下面的action配置需要与客户端绑定服务的action保持一致-->
<action android:name="com.xiayiye5.login.token" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
然后我们可以在发送端开始绑定接收端的服务类了
/**
* 尝试与服务端建立连接
*/
private fun startBindService() {
val intent = Intent()
//下面action需要与服务端APP清单文件里面的服务配置的action字段保持一致
intent.action = "com.xiayiye5.login.token"
//要发送到服务端APP的包名
intent.setPackage("com.example.app_server")
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
}
private val mServiceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.d(TAG, "service connected")
mITokenAidlInterface = ITokenAidlInterface.Stub.asInterface(service)
//如果与服务端的连接处于未连接状态,则尝试连接
if (!mConnected) {
startBindService()
Toast.makeText(
this@ClientActivity,
"当前与服务端处于未连接状态,正在尝试重连,请稍后再试",
Toast.LENGTH_SHORT
).show()
return
}
}
override fun onServiceDisconnected(name: ComponentName) {
Log.d(TAG, "service disconnected")
mConnected = false
}
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart")
if (!mConnected) {
//建立连接
startBindService()
}
}
override fun onStop() {
super.onStop()
if (mConnected) {
//解绑服务
unbindService(mServiceConnection)
}
}
绑定完成后,我们可以开始发送数据到接收端了
//跨进程方法一 AIDL
btSend.setOnClickListener {
try {
//AIDL跨进程发送数据到服务端APP
mITokenAidlInterface!!.postLoginToken(etInput.text.toString().trim())
} catch (e: RemoteException) {
e.printStackTrace()
}
}
代码完毕。
再次感谢原博主:原博主直达
如果看着比较复杂具体可以下载源码查看:源码直达