ResultReceiver可以简单实现不同组件之间的消息分发。
使用场景:用于service接收activity的回调
比如activity需要返回结果给启动它的service,可以这么实现:
service.java
public ResultReceiver resultReceiver = new ResultReceiver(handler) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
Log.i(TAG, "onReceiveResult, resultCode:" + resultCode + ", resultData:" + resultData.toString());
}
};
// 启动activity,传入resultReceiver
Intent intent1 = new Intent(getBaseContext(), MyActivity1.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1.putExtra("result_callback", resultReceiver);
startActivity(intent1);
activity.java
public void onClick(View view) {
ResultReceiver resultReceiver = getIntent().getParcelableExtra("result_callback");
Bundle resultData = new Bundle();
resultData.putString("msg", "这是来之activity的调用");
resultReceiver.send(0, resultData);
}
触发onClick,会看到打印:
2023-09-11 16:58:40.449 5303-5303 MyService1 com.ericcode.codetest I onReceiveResult, resultCode:0, resultData:Bundle[{msg=这是来之activity的调用}]
证明service收到了来自activity的消息。
使用场景:用于组件互发消息
service.java
public ResultReceiver resultReceiver = new ResultReceiver(new Handler()) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
Log.i(TAG, "onReceiveResult, resultCode:" + resultCode + ", resultData:" + resultData.toString());
ResultReceiver activityResultReceiver = resultData.getParcelable("result_callback");
if (activityResultReceiver != null) {
Bundle reply = new Bundle();
reply.putString("msg", "这是来着service的消息");
activityResultReceiver.send(0, reply);
}
}
};
// 启动activity,传入resultReceiver
Intent intent1 = new Intent(getBaseContext(), MyActivity1.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1.putExtra("result_callback", resultReceiver);
startActivity(intent1);
activity.java
public ResultReceiver resultReceiver = new ResultReceiver(new Handler()) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
Log.i(TAG, "onReceiveResult, resultCode:" + resultCode + ", resultData:" + resultData.toString());
}
};
public void onClick(View view) {
ResultReceiver serviceResultReceiver = getIntent().getParcelableExtra("result_callback");
Bundle resultData = new Bundle();
resultData.putString("msg", "这是来之activity的调用");
resultData.putParcelable("result_callback", resultReceiver);
serviceResultReceiver.send(0, resultData);
}
触发onClick,会看到打印:
2023-09-11 17:51:12.316 14795-14795 MyService1 com.ericcode.codetest I onReceiveResult, resultCode:0, resultData:Bundle[{msg=这是来之activity的调用, result_callback=com.ericcode.codetest.resultreceiver.MyActivity1$1@7b303fe}]
2023-09-11 17:51:12.319 14795-14795 MyActivity1 com.ericcode.codetest I onReceiveResult, resultCode:0, resultData:Bundle[{msg=这是来着service的消息}]
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!