Android中的广播机制
有的时候,在一个Activity之外要对这个Activity的UI进行更新,例如,当外界的参数变化引起这个Activity相应的变化,这种情况下,我们可以采用广播机制:在变量发生变化的地方,向需要接收的Activity或其他Android应用组件发送一个广播消息。下面有个Demo,展示了这种消息机制:
首先启动的是Activity中注册一个广播:
//广播监听类class MyReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {int color = intent.getExtras().getInt("color");Log.v("tag", "receive color: " + color);drawColor(color);}}/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);receiver = new MyReceiver();IntentFilter filter = new IntentFilter();filter.addAction("ChangeColor");registerReceiver(receiver, filter);btnStartB = (Button) findViewById(R.id.btnStartB);textView = (TextView) findViewById(R.id.textView);btnStartB.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent(FirstActivity.this,SecondActivity.class);startActivity(intent);}});}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(receiver); //取消注册}public void drawColor(int c) {int color = c;Log.v("tag", "receive: " + color);switch (color) {case 0:textView.setBackgroundColor(Color.RED);break;case 1:textView.setBackgroundColor(Color.YELLOW);break;case 2:textView.setBackgroundColor(Color.BLUE);break;}textView.invalidate(); //更新UI}
在第二个Activity中,有三个按钮,代表三种不同的颜色值,每次点击一个按钮,则发出广播,通知ActivityA进行更新UI。
发送广播的代码如下:
Intent intent = new Intent("ChangeColor");intent.putExtra("color", c);sendBroadcast(intent);
Demo的效果如下:
(1)
(2)
(3)




浙公网安备 33010602011771号