1.创建 BroadcastReceiver
/** * 广播监听 */ private class ScrosReceive extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.e("BroadcastReceiver" ,"第一个页面,监听到广播,做相应的数据处理"); scros = intent.getIntExtra("scros", 0); textView.setText("这学期的综合成绩:scros = " + scros); } }
2.在MainActivity中实例化广播与注册广播
private ScrosReceive scrosReceive;
scrosReceive = new ScrosReceive();
//注册广播
//ruidee.mainActivity 是广播的Action,可自定义
IntentFilter intentFilter = new IntentFilter("ruidee.mainActivity");
registerReceiver(scrosReceive, intentFilter);
3.在另一个Activity中发送BroadcastReceiver
//发送广播的点击事件
btnSendBrocast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent_brocast = new Intent();
intent_brocast.setAction("ruidee.mainActivity");
intent_brocast.putExtra("scros" ,120);
//发送广播调用 sendBroadcast(Intent intent)方法
sendBroadcast(intent_brocast);
Log.e("BroadcastReceiver" ,"第二个页面,发送广播");
}
});