第 5 章 全局大喇叭,详解广播机制
一:接收系统广播
-
动态注册监听网络变化
- 自定义广播类并重写onreceive类
- 在需要启动广播时注册广播
- 需要结束时取消注册
private IntentFilter intentFilter; private NetworkChangeReceiver networkChangeReceiver; /////////////////////////////////注册广播 intentFilter = new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//监听网络变化 networkChangeReceiver = new NetworkChangeReceiver(); registerReceiver(networkChangeReceiver, intentFilter); /////////////////////////////////取消注册 protected void onDestroy() { super.onDestroy(); unregisterReceiver(networkChangeReceiver); }
注://如何获取网络状态
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>//清单文件中添加权限 //////////////////////////////////////////////////////////////////////////// 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(); }
-
静态注册实现开机启动
- 添加权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
- 自定义广播类并重写onreceive类接收开机广播
- 由于Android系统启动完成后会发出一条值为android.intent.action.BOOT_COMPLETED的广播,因此我们在清单文件中添加相应的 action
<receiver android:name=".BootCompleteReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>
二:发送自定义广播
- 发送标准广播
- 新建一个 MyBroadcastReceiver继承自 BroadcastReceiver,重写onreceive方法
- 在 AndroidManifest.xml 中对这个广播接收器进行注册
<receiver android:name=".MyBroadcastReceiver"> <intent-filter> <action android:name="com.example.broadcasttest. MY_BROADCAST"/> </intent-filter> </receiver>
- 发送广播
Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST"); sendBroadcast(intent);
- 发送有序广播
- 使用sendOrderedBroadcast(intent, null);发送有序广播
- 在清单文中设置优先级
<intent-filter android:priority="100" > //设置优先级 <action android:name="com.example.broadcasttest.MY_BROADCAST"/> </intent-filter>
- 如果需要终止广播,可以在onreceive方法中调用abortBroadcast();方法
标准广播和有序广播可以被其他的应用程序接收到,有序广播可以被终止,本地广播只能本应用接收
- 使用本地广播(本地广播是无法通过静态注册的方式来接收的)
//注册
1. 通过 LocalBroadcastManager的getInstance()方法得到了它的一个实例,
2. 然后在注册广播接收器的时候调用的是LocalBroadcastManager的registerReceiver()方法,
//发送
3. 在发送广播的时候调用的是LocalBroadcastManager的sendBroadcast()方法。
4. 这里我们在按钮的点击事件里面发出了一条com.example.broadcasttest.LOCAL_BROADCAST广播,
//接收
5. 然后在LocalReceiver 里去接收这条广播。
public class MainActivity extends Activity {
private IntentFilter intentFilter;
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;
/* 主要就是使用了一个 LocalBroadcastManager 来对广播进行管理,并提供了发送广播和注册广播接收器的方法 */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localBroadcastManager = LocalBroadcastManager.getInstance(this); // 获取实例 /* 比标准广播多了这行 */
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
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);
}
//取消注册
@Override
protected void onDestroy() {
super.onDestroy();
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();
}
}
}
-
广播的最佳实践——实现强制下线功能
- 新建登录对话框
- 新建广播接收类 ForceOfflineReceiver
public class ForceOfflineReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context); dialogBuilder.setTitle("Warning"); dialogBuilder.setMessage("You are forced to be offline. Please try to login again."); dialogBuilder.setCancelable(false); //setCancelable()方法将对话框设为不可取消 dialogBuilder.setPositiveButton("OK",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCollector.finishAll(); // 销毁所有活动 Intent intent = new Intent(context, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); // 重新启动LoginActivity } }); AlertDialog alertDialog = dialogBuilder.create(); // 需要设置AlertDialog的类型,保证在广播接收器中可以正常弹出 alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); alertDialog.show(); } }
- 声明权限
首先由于我们在 ForceOfflineReceiver 里弹出了一个系统级别的对话框,因此必须要声明 android.permission.SYSTEM_ALERT_WINDOW 权限 - 发送广播或本地广播
Intent intent = new Intent("com.example.broadcastbestpractice.FORCE_OFFLINE "); sendBroadcast(intent);
网友评论