"项目接入篇"已经帮助大家将宿主程序、插件程序接入到项目中,接下来就是宿主与插件之间数据通信了。
1、Intent 传递数据
和平时使用的跳转 Intent 传递数据一样,也可以使用 startActivityForResult 传递数据并返回响应。
//宿主跳转到插件 并传递数据
String input = inputEt.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("host_param",input);
//第一个参数是插件的包名,第二个参数是插件的Activity
Intent intent = RePlugin.createIntent(pluginName, className);
intent.putExtras(bundle);
RePlugin.startActivityForResult(this,intent,REQUEST_CODE);
//插件中接收数据
Bundle extras = intent.getExtras();
if (extras != null){
String param = extras.getString("host_param");
hostParamTv.setText("接收宿主参数:" + param);
}
//插件回应宿主
Bundle bundle = new Bundle();
bundle.putString("plugin_param","来自插件的回复");
intent.putExtras(bundle);
setResult(RESULT_OK,intent);
//宿主接收插件回应
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null){
return;
}
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK){
Bundle extras = data.getExtras();
String param = extras.getString("plugin_param");
Utils.showToast(context,"收到插件的回复:" + param);
}
}
2、BroadcastReceiver 广播
新建广播接收类 PluginReceiver
public class PluginReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null){
return;
}
Bundle extras = intent.getExtras();
String param = extras.getString("plugin_param");
Utils.showToast(context,"收到插件的回复:" + param);
}
}
宿主中注册广播
//声明
private PluginReceiver pluginReceiver;
//注册
pluginReceiver = new PluginReceiver();
IntentFilter filter = new IntentFilter("com.plugin.receiver");
registerReceiver(pluginReceiver,filter);
//onDestroy中注销
unregisterReceiver(pluginReceiver);
插件中发送广播
Intent broadIntent = new Intent("com.plugin.receiver");
Bundle bundle1 = new Bundle();
bundle1.putString("plugin_param","来自插件发送的广播");
broadIntent.putExtras(bundle1);
sendBroadcast(broadIntent);
3、使用EventBus
宿主项目app下build.gradle中添加依赖
implementation 'org.greenrobot:eventbus:3.2.0'
新建EventBus事件类 HostEvent
public class HostEvent {
private String params;
public HostEvent(String params){
this.params = params;
}
public String getParams() {
return params;
}
//供插件调用的方法
public void sendHostEvent(){
EventBus.getDefault().post(this);
}
}
宿主中注册、执行事件、注销
//注册
EventBus.getDefault().register(this);
//执行事件的方法,HostEvent为自定义事件类
@Subscribe(threadMode = ThreadMode.MAIN)
public void getHostEvent(HostEvent event){
if (event != null){
String params = event.getParams();
Utils.showToast(context,"收到插件的event:" + params);
}
}
//注销
if (EventBus.getDefault().isRegistered(this)){
EventBus.getDefault().unregister(this);
}
插件中调用宿主提供的方法
try {
//获取宿主类加载器
ClassLoader hostClassLoader = RePlugin.getHostClassLoader();
//获取HostEvent类
Class> hostEvent = hostClassLoader.loadClass("com.zsf.zplugin_host.event.HostEvent");
//得到有参构造方法
Constructor> constructor = hostEvent.getConstructor(String.class);
//调用有参构造,传递参数
Object eventBusInfo = constructor.newInstance("你好 宿主");
//反射宿主中方法
Method method = hostEvent.getDeclaredMethod("sendHostEvent");
method.invoke(eventBusInfo);
finish();
}catch (Exception e){
e.printStackTrace();
}
4、Messenger 通信
把宿主当作服务端,新建MessengerService
/**
* 宿主中注册 MessengerService
*/
public class MessengerService extends Service {
private String TAG = "MessengerService";
private Messenger messenger = new Messenger(new MessengerHandler());
@Nullable
@Override
public IBinder onBind(Intent intent) {
return messenger.getBinder();
}
@SuppressLint("HandlerLeak")
private class MessengerHandler extends Handler{
@Override
public void handleMessage(Message msg) {
if (msg.what == 1){
Log.e(TAG, "handleMessage: 宿主得到消息");
Bundle data = msg.getData();
String param = data.getString("plugin_param");
//回复插件
Messenger plugin= msg.replyTo;
Bundle bundle = new Bundle();
bundle.putString("host_param","插件消息已收到");
Message pluginMsg = Message.obtain();
pluginMsg.what = 0;
pluginMsg.setData(bundle);
try {
plugin.send(pluginMsg);
} catch (RemoteException e) {
e.printStackTrace();
}
EventBus.getDefault().post(new ServiceEvent(param));
}else{
super.handleMessage(msg);
}
}
}
}
宿主清单文件注册
在插件中绑定服务,发送信息,并获取宿主响应结果
// 创建 ServiceConnection
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Messenger mService = new Messenger(iBinder);
//向服务器发送数据
try {
Message msg = Message.obtain();
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("plugin_param",messengerEt.getText().toString());
msg.setData(bundle);
//设置服务端回复的Messenger
msg.replyTo = mMessenger;
mService.send(msg);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
// 宿主的Messenger
private Messenger mMessenger = new Messenger(new MessengerHandler());
@SuppressLint("HandlerLeak")
private class MessengerHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0){
Bundle data = msg.getData();
String host_param = data.getString("host_param");
Toast.makeText(MainActivity.this, "得到宿主回复:" + host_param, Toast.LENGTH_SHORT).show();
}
}
}
//绑定宿主服务
Intent messengerIntent = new Intent("com.zsf.zplugin_host.utils.MessengerService");
ComponentName componentName = new ComponentName("com.zsf.zplugin_host", "com.zsf.zplugin_host.utils.MessengerService");
Intent messengerIntent.setComponent(componentName);
RePlugin.getHostContext().bindService(messengerIntent,mConnection, Service.BIND_AUTO_CREATE);
//onDestroy中断开连接
RePlugin.getHostContext().unbindService(mConnection);
5、AIDL 通信
该方法还在测试中,后续完成后会再加上。