一.startActivityForResult
例子:
调起:A的Activity调B
Intent intent = new Intent(this, B.class);
intent.setPackage(getPackageName());
startActivityForResult(intent, REQUEST_CODE);
返回:B给A返回数据
Intent intent = new Intent()
intent.putExtra(Constants.DATA, data);
setResult(RESULT_OK, intent);
finish();
接收:A接收B给的数据
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE:
if (resultCode == RESULT_OK) {
String s = data.getStringExtra( Constants.DATA);
}
break;
注意:
1.resultCode != RESULT_OK的时候就无法走到取出数据的路径了,此时可能是由于B设置成了singleTask等启动模式;
2.在B返回的时候可以自己设置ResutCode;
二.BroadCastReceiver
例子:
数据接收处:
注册BroadCastReceiver并监听接收数据;
private class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (ExtraIntent.ACTION_INFO_CHANGED.equals(action)) {
String s = intent.getStringExtra("some");
}
}
}
@Override
public void onResume() {
super.onResume();
mReceiver = new Receiver();
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ExtraIntent.ACTION_INFO_CHANGED);
getActivity().registerReceiver(mReceiver, intentFilter);
}
@Override
public void onPause() {
if (mReceiver != null) {
getActivity().unregisterReceiver(mReceiver);
mReceiver = null;
}
super.onPause();
}
数据发送处:
发送数据给receiver
Intent intent = new Intent(ExtraIntent.ACTION_INFO_CHANGED);
intent.putExtra("some", "data");
sendBroadcast(intent);