动态注册广播接收器
1、创建一个Receiver继承BroadcastReceiver,并重写onReceiver()
2、在Activity的OnCreate()中添加广播接收器想要接收的action
3、注册广播接收器,调用registerReceiver(Receiver实例,intentFilter)
4、在OnDestroy()中取消注册,unregisterReceiver(Receiver实例)
public class MainActivity extends AppCompatActivity{
private InterFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.com.CONNECTIVITY_CHANGE"); //通过intentFilter对象,添加广播接收器要监听的Action
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver,intentFilter); //注册广播接收器
}
@Override
protected void onDestory(){
super.onDestory();
unregisterReceiver(networkChangeReceiver); //取消注册
}
class NetworkChangeReceiver extends BroadcastReceiver{
@Override
public void onReceiver(Context context,Intent intent){
ConnectivityManager connectionManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
//判断当前是否有网络
if(networkInfo != null && networkInfo.isAvailable()){
//处理逻辑
}else{
//处理逻辑
}
}
}
}
访问系统网络状态需要在Androidmanifest.xml中声明权限:
<use-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
静态注册广播接收器
1、创建一个Receiver类,继承BroadcastReceiver
2、在AndroidMainfest.xml中注册
......
<use-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
......
<receiver
android:name=".BootCompleteReceiver"
android:enabled="true"
android:exported="true"
</receiver>
</application>
......
3、如果需要发送携带action的广播,还需在<receiver>中加入<intent-filter>并在其中加入<action>
<receiver
......
<intent-filter>
<action android:name="......" />
</intent-filter>
</recevier>
发送自定义广播
1、发送标准广播
(1)定义一个广播接收器接收此广播。
(2)在AndroidManifest.xml中注册,并设置action
(3)在Activity中添加控件,并设置监听器。
(4)在点击事件中,通过Intent传入action
(5)发送广播,sendBroadcast(intent)
2、发送标准广播
步骤和标准广播基本一致,在点击事件中sendOrderedBroadcast(intent,null) //二参:与权限相关的字符串
在<intent-filter>中设置优先级:<intent-filter android:priority="100">
截断广播:在广播接收器中onRecevier()里添加 abortBroadcast()
本地广播
1、创建一个LocalBroadcastManager管理广播,获取实例:LocalBroadcastManager.getInstance(this);
2、发送广播:localBroadcastManager.sendBroadcast(intent);
3、注册广播:localBroadcast.registerReceiver(localReceiver,intentFilter);
4、取消注册:localbBroadcastManager.unregisterReceiver(localReceiver);