- BroadcastReciever广播:
- 他采用了一种设计模式,熟称观察者模式。
- 意思:当我注册一个广播的时候,申明了标记Action
- 当发送广播的时候,给传送的Intent设置了相同的标记Action
- 一呼一答的模式。
- 注册广播实现方式(两种):
- 一.在manifest.xml注册广播接收器
- 二.用代码动态实现广播接收器(一边在Activity的onResumu中实现)
- 先看第一种,实现如下:
- 1.创建广播接收器(MyReceiver )
- public class MyReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- Log.i("MyReceiver", "ACTION = " + intent.getAction());
- }
- }
- 2.在Manifest.xml中注册广播接收器
- <receiver android:name=".MyReveiver">
- <intent-filter>
- <action android:name="com.zm.broad"></action>
- </intent-filter>
- </receiver>
- 3.Activity中发送广播
- final String ACTION = "com.zm.broad";
- protected void onResume() {
- //发送广播
- Intent intent = new Intent();
- intent.setAction(ACTION);
- sendBroadcast(intent);
- super.onResume();
- }
- ---------------------------------------------
- 第二种实现如下:
- public class BroadcastActivity extends Activity {
- MyReceiver myReceiver;
- final String ACTION = "com.zm.broad";
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // Button button = (Button)findViewById(R.id.broadcast);
- // button.setOnClickListener(new OnClickListener(){
- //
- // public void onClick(View v) {
- // Intent intent = new Intent();
- // intent.setAction(ACTION);
- // sendBroadcast(intent);
- // }
- //
- // });
- }
- @Override
- protected void onResume() {
- myReceiver = new MyReceiver();
- IntentFilter filter = new IntentFilter();
- filter.addAction(ACTION);
- //注册
- registerReceiver(myReceiver, filter);
- //发送广播
- Intent intent = new Intent();
- intent.setAction(ACTION);
- sendBroadcast(intent);
- super.onResume();
- }
- @Override
- protected void onPause() {
- unregisterReceiver(myReceiver);
- super.onPause();
- }
- class MyReceiver extends BroadcastReceiver{
- @Override
- public void onReceive(Context context, Intent intent) {
- Log.i("MyReceiver", "ACTION = " + intent.getAction());
- }
- }
- }