1、定义广播
private final BroadcastReceiver mSystemReceiver = new SystemBroadcastReceiver();
2、注册广播
/*本地广播*/
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mSystemReceiver, intentFilter);
3、接收广播
private class SystemBroadcastReceiver extends BroadcastReceiver {
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action == null) {
return;
}
switch (action) {
case ConnectivityManager.CONNECTIVITY_ACTION:
//处理网络变化的业务
break;
}
}
}
4、注销
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mSystemReceiver);
}