在上一篇博文中简单介绍了一下BroadcastReceiver的相关知识点,本篇举一个在代码中动态的注册、注销BroadcastReceiver的栗子。

1、首先创建一个MyReceiver并继承BroadcastReceiver,既然要动态注册该receiver的话,就无需在AndroidManifest.xml中配置它了:

public class MyReceiver extends BroadcastReceiver {
public static final String ACTION = "com.codingblock.receive.intent.action.MyReceiver";
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("接收到的消息为:" + intent.getStringExtra("data"));
}
}

代码分析:上面代码中定义了一个静态变量ACTION,以方便程序指定该receiver。另外,从onReceive()方法的第二个参数intent可以获取到传递过来的数据。

2、布局文件如下,很简单,只有三个按钮:发送消息按钮、注册receiver按钮和注销receiver按钮。

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
android:id="@+id/btn_send_receiver"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送消息" />
android:id="@+id/btn_register_receiver"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="注册receiver" />
android:id="@+id/btn_unregister_receiver"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="注销receiver" />

3、最后在MainActivity中测试一下

public class MainActivity extends Activity implements OnClickListener {
private MyReceiver receiver = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_send_receiver).setOnClickListener(this);
findViewById(R.id.btn_register_receiver).setOnClickListener(this);
findViewById(R.id.btn_unregister_receiver).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send_receiver:
Intent i = new Intent(MyReceiver.ACTION);
i.putExtra("data", "来自MainActivity的消息");
sendBroadcast(i);
break;
case R.id.btn_register_receiver:
if (receiver == null) {
System.out.println("注册receiver");
receiver = new MyReceiver();
registerReceiver(receiver, new IntentFilter(MyReceiver.ACTION));
}
break;
case R.id.btn_unregister_receiver:
if (receiver != null) {
System.out.println("注销receiver");
unregisterReceiver(receiver);
receiver = null;
}
break;
default:
break;
}
}
}

代码分析:本段代码在23行,通过registerReceiver()方法动态的注册了MyReceiver,并且使用过后最好不要忘了用unregisterReceiver()方法再将其注销,注销后应将receiver设为null。

4、运行结果如下


测试就会发现在点击发送消息按钮之前,如果没有注册receiver的话是不能成功发送消息的,只有注册了receiver,点击发送消息log中才有输出:


从日志输出就能看出,当注册好了receiver后,按下发送消息按钮,在MyReceiver中就能收到来自MainActivity的消息。

Android学习笔记--Broadcast, BroadcastReceiver(广播)

参考资料: 在 Android 中使用 Activity, Service, ...