Broadcast是Android四大组件之一,中文翻译是广播.顾名思义,使用它需要广播发出者和监听者.
发出广播很简单,只要在Activity中使用sendBroadcast方法即可.和startActivity方法一样,需要传入Intent方法:
Intent intent = new Intent("com.example.broadcastbestpractice.FORCE_OFFLINE");
sendBroadcast(intent);
监听者需要继承至BroadcastReceiver,重写onReceiver方法可以处理接收到广播后的响应.
class OffLineReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Waring");
alertDialog.setMessage("You are forced to be offline. Please try to login again!");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("OK",nil);
alertDialog.show();
}
}
顺利实现监听,需要注册监听名称,分为静态注册和动态注册两种方法.其中静态注册在AndroidMainfest.xml文件中实现:
<receiver android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.zhudong.broadcasttest.MY_BROADCAST"/>
</intent-filter>
</receiver>
动态注册用代码实现:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcastbestpractice.FORCE_OFFLINE");
receiver = new OffLineReceiver();
registerReceiver(receiver, intentFilter);
注意:Activity动态注册后,在Activity的销毁方法onDestroy中移除监听:
unregisterReceiver(receiver);
receiver = null;
上述发送和接收广播的方式,能够被其他App干扰,使App变的不安全.使用本地广播LocalBroadcastManager可以发送安全广播,解决上述问题.
接收本地广播:
localBroadcastManager = LocalBroadcastManager.getInstance(this);
localReceiver = new LocalReceiver();
intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcasttext.LOCAL_BROADCAST");
localReceiver = new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver, intentFilter);
发送本地广播:
Intent intent = new Intent("com.example.broadcasttext.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);
最后,通过设置IntentFilter的优先级来控制广播接收者的先后顺序:
<intent-filter android:priority="100">
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
总结:使用Broadcast组件需要发送者和接受者,根据发送方式分为本地广播和全局广播;根据接受者注册方式有静态和动态两种;通过设置接受者IntentFilter的priority来控制接收的顺序.
喜欢和关注都是对我的支持和鼓励~