只要不被取消,广播接收器是可以跨Activity接受广播的。而Handler只能在本Activity中接收Message。
public class MainActivity extends Activity {
private BroadcastReceiver myBR;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerBroadcast();
initialWidget();
}
public void registerBroadcast() {
myBR = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("broadcastSent")) {
Toast.makeText(context, "SendButtonClick", Toast.LENGTH_SHORT).show();
}
if(action.equals("broadcastCancelled")) {
Toast.makeText(context, "CancelButtonClick", Toast.LENGTH_SHORT).show();
}
}
};
// IntentFilter通过action来过滤intent
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction("broadcastSent");
myIntentFilter.addAction("broadcastCancelled");
// 注册BroadcastReceiver
this.registerReceiver(myBR, myIntentFilter);
}
public void initialWidget() {
Button send = (Button) findViewById(R.id.send);
Button cancel = (Button) findViewById(R.id.cancel);
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
BrocastMessage("broadcastSent");
}
});
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
BrocastMessage("broadcastCancelled");
}
});
}
/* 创建带有action的Intent并发送广播 */
public void BrocastMessage(String s) {
Intent in = new Intent(s);
this.sendBroadcast(in);
}
/* 进入活动生存期的时候重新注册广播器 */
@Override
public void onResume() {
super.onResume();
this.registerReceiver(myBR);
}
/* 跳转activity的时候取消广播器 */
@Override
public void onPause() {
this.unregisterReceiver(myBR);
super.onPause();
}
/* activity销毁时时取消广播 */
@Override
public void onDestroy() {
this.unregisterReceiver(myBR);
super.onDestroy();
}
}