广播结合消息跨进程通信
需求:
要实现一个在Framework中与上层app进行通信,不添加接口去实现。
项目描述:
项目中,我是在framework中进行获取遥控器Mac信息,但是这些数据要去上层的app中显示出来。但是不想去使用AILD的方式去实现进程之间通信。然后就想到了使用广播结合消息去实现上述功能。
直接上代码,重点代码会使用start - end 标识出来; 此代码只贴重点部分
// Android App层
public class JinJuManager implements Handler.Callback {
private final Handler mHandler = new Handler(Looper.getMainLooper(), this);
//start; framework中发送过来消息会回调到handleMessage
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case 0:
if (msg.obj instanceof Bundle) {
Bundle result = (Bundle) msg.obj;
//获取到framewrok层发送过来的Mac信息
String macAddress = result.getString("MacAddress");
mActivity.updateMacAddress(macAddress);
Log.d(TAG, "Response -> MacAddress: " + macAddress);
} else {
Log.d(TAG, "Response is null.");
}
return true;
default:
return false;
}
}
// end;
// start 首先创建一个Messenger对象出来,然后将要传递的数据通过bundle(key,vlue)形式进行保存。
// 然后使用广播把数据发送到framework端进行处理
public void requestMacAddress(Context context, int vendorId, int productId) {
Messenger messenger = new Messenger(mHandler);
Intent intent = new Intent("com.toptech.action.REQUEST_MAC_ADDRESS");
Bundle bundle = new Bundle();
//相当于将messnger对象保存在binder中,然后跨进程通信
bundle.putBinder("Messenger", messenger.getBinder());
bundle.putInt("VendorId", vendorId);
bundle.putInt("ProductId", productId);
intent.putExtras(bundle);
context.sendBroadcast(intent);
}
// end;
}
// framework层
public class UsbDeviceManager extends BroadcastReceiver {
public static final int VID = 4310;
public static final int PID = 45062;
private final Context mContext;
public UsbDeviceManager(Context context) {
mContext = context;
IntentFilter filter = new IntentFilter();
filter.addAction("com.toptech.action.REQUEST_MAC_ADDRESS");
mContext.registerReceiver(this, filter);
}
//start; 接收到携带数据的广播
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "action: " + action);
if ("com.toptech.action.REQUEST_MAC_ADDRESS".equals(action)) {
Bundle extras = intent.getExtras();
if (extras == null || extras.isEmpty()) {
return;
}
//拿到app层发送过来的VID,PID
int vendorId = extras.getInt("VendorId", 0);
int productId = extras.getInt("ProductId", 0);
if (vendorId == 0 && productId == 0) {
return;
}
Log.d(TAG, "Request mac address -> vid: " + vendorId + ", pid: " + productId);
//这个方法是在framework中获取Mac信息的方法
String macAddress = getMacAddress(vendorId, productId);
if (TextUtils.isEmpty(macAddress)) {
return;
}
//这里就是相当于获取到app层发送过来的messenger对象
IBinder binder = extras.getBinder("Messenger");
if (binder == null) {
return;
}
//将获取到的mac信息存入MacAddress中
Bundle result = new Bundle();
result.putString("MacAddress", macAddress);
Message message = Message.obtain();
message.what = 0;
message.obj = result;
//向上层发送消息
Messenger messenger = new Messenger(binder);
try {
messenger.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
return;
}
}
// end;
总结:
app层(创建广播,创建消息,发送数据) -> framewrok层(接收广播,接收消息,发送数据) -> app层(回调handleMessage,接收数据)