发送者:
private void sendBroad() {
Intent intent = new Intent(); // Itent就是我们要发送的内容
intent.putExtra(Constant.DOWN_EXTRA,"DOWN_SUCCESS"); //Extra的用法和跳Activity一样
intent.setAction(Constant.DOWN_FLAG); // 设置你这个广播的action,只有和这个action一样的接受者才能接受者才能接收广播
context.sendBroadcast(intent); // 发送广播
}
接收者:
载入Activity时先使用initBroad()初始化广播。
private ReceiveBroadCast mBroadCast;
private void initBroad() {
mBroadCast = new ReceiveBroadCast();
IntentFilter mFilter = new IntentFilter();
mFilter.addAction(Constant.DOWN_FLAG);
context.registerReceiver(mBroadCast, mFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
context.unregisterReceiver(mBroadCast);
}
public class ReceiveBroadCast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 得到广播中得到的数据,并显示出来
String message = intent.getStringExtra(Constant.DOWN_EXTRA);
tvDownInfo.setText(message);
if (message.equals("DOWN_SUCCESS")) {
tvDownInfo.setVisibility(View.GONE);
}
}
}