标签(空格分隔): Android
概要
Broadcast Receiver,广播接收器,是 android四大组件之一,用于监听应用发出的广播,并做出适当响应
观察者模式
全局广播:
动态注册:
简单应用:
e.g.监听网络变化
- 先建一个内部类,继承自BroadcastReceiver,重写父类的onReceive
class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectionManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
Toast.makeText(context, "network is available",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "network is unavailable",
Toast.LENGTH_SHORT).show();
}
- 创建一个IntentFiler实例,添加相应的action
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
- 创建一个自定义的Receiver实例,调用registerReceiver,将IntentFiler实例和Receiver实例传入注册,这样该Receiver就能收到所有值为所添加的action的广播
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);
注意:动态注册的广播必须在onDestroy中注销
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);
localBroadcastManager.unregisterReceiver(localReceiver);
}
小技巧
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectionManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
Toast.makeText(context, "network is available",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "network is unavailable",Toast.LENGTH_SHORT).show();
- 通过getSystemService()方法得到ConnectivityManager的实例,调用它的getActiveNetwork-Info()得到NetWorkInfo的实例,接着调用NetworkInfo的isAvailable(),网络权限要注册。
静态注册
利用AS的设置,可以快速(不用在AndroidManifest中注册),补充对应的action及权限
<intent-filer>
<action android:name="android.intent.action.BOOT_COMLETED"/>
<intent-filer>
注意:在 onReceive()方法中不允许开启子线程,如果onRecceive方法执行较长时间没有结束会报错
使用本地广播
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;
onCreate(){
……
localBroadcastManager = LocalBroadcastManager.getInstance(this); // 获取实例
Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent); // 发送本地广播
intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
localReceiver = new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver, intentFilter); // 注册本地广播监听器
}
/*
记得在onDestory()里注销
*/
localBroadcastManager.unregisterReceiver(localReceiver);
class LocalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT).show();
}