我有2个活动在运行。首先启动活动A,然后启动活动B.(即堆叠中的A,焦点中的B)。我有两个活动BroadcastReceiver
。问题是只有活动A能够捕获我的广播消息(使用sendBroadcast
)
为什么会这样?如何启用两个活动以接收广播而不终止(在活动A上调用finish
)
另外,有什么办法可以在Activity A中重用Broadcast接收器方法吗?
广播活动
Intent intent = new Intent(MESSAGE_UPDATE);
intent.putExtra("message", message);
sendBroadcast(intent);
活动A
@Override
public void onResume() {
super.onResume();
if(resumeHasRun==false){
IntentFilter movementFilter;
movementFilter = new IntentFilter();
movementFilter.addAction(NewService.MESSAGE_UPDATE);
registerReceiver(mIntentReceiver, movementFilter);
resumeHasRun=true;
return;
}
}
public BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
updateTable(message);
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mIntentReceiver);
}
public void startNewActivity(){
Intent newIntent = new Intent(getApplicationContext(),ActivityB.class);
startActivity(newIntent);
//never call finish
}
活动B
@Override
public void onResume() {
super.onResume();
if(resumeHasRun==false){
IntentFilter movementFilter;
movementFilter = new IntentFilter();
movementFilter.addAction(NewService.MESSAGE_UPDATE);
registerReceiver(mIntentReceiver, movementFilter);
resumeHasRun=true;
return;
}
}
public BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
updateAnotherTable(message);
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mIntentReceiver);
}
答案 0 :(得分:2)
移动:
registerReceiver(mIntentReceiver, movementFilter); to onStart()
unregisterReceiver(mIntentReceiver); to onStop()
制作(在自己的文件中):
public class TableUpdateReceiver extends BroadcastReceiver {
public interface Listener {
public void tableUpdate(String message);
};
Listener mListener;
public TableUpdateReceiver(Listener list) {
mListener = list;
}
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
if(mListener != null) {
mListener.tableUpdate(message);
}
}
};
让您的活动实现TableUpdateReceiver.Listener和:
public BroadcastReceiver mIntentReceiver;
onCreate(Bundle savedState) {
...
mIntentReceiver = new TableUpdateReceiver(this);
...
}
public void tableUpdate(String message) {
//do something
}
答案 1 :(得分:1)
请参阅this example它可以帮助您解决问题。在两个活动中注册并进行抽象类活动。