APP开发实战64-Activity数据传递机制
16.4.2数据传递机制
(1)使用Activity系统函数传递数据
(2)使用自定义接口函数传递数据
(3)使用广播消息传递数据
示例代码如下:
publicstatic void registerApiListener(Context context, BroadcastReceiver receiver,String actionId) {
LocalBroadcastManager.getInstance(context).registerReceiver(receiver,new IntentFilter(actionId));
}
privatevoid sendResponseData(Response response) {
Intent intent = new Intent(API_ACTION_RAW_RESPONSE);
intent.putExtra(API_RESPONSE_OBJECT,response);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
@Override
public void onReceive(Context context,Intent intent) {
Serializable dataObject =
intent.getExtras().getSerializable(ApiService.API_RESPONSE_OBJECT);
Object responseObject =
((Response)dataObject).getResponseObject();
processResponseObject(context,responseObject);
LocalBroadcastManager.getInstance(context).unregisterReceiver(this);
}
用这种方式可以解决类似A->B->C->A这样多级Activity/Fragment间使用
startActivityForResult/onActivityResult这种机制无法传递数的问题。