安卓系统为7时,系统去掉了网络监测的广播,测试系统任然可以接收广播,为了适配低版本,可结合版本的不同写不同的逻辑
- 清单中配置权限
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
2,appcation中注册回调或注册广播
public static final String RECIVER_SELF_NET_CHANGE = “android.self.conn.CONNECTIVITY_CHANGE”;
public static final String RECIVER_ANDROID_NET_CHANGE = “android.net.conn.CONNECTIVITY_CHANGE”;`
@Override
public void onCreate() {
super.onCreate();
registNetworkStatus();
}
private void registNetworkStatus(){
if (Build.VERSION.SDK_INT >= 21){
//注册自己的广播
registerReciver(RECIVER_SELF_NET_CHANGE);
try {
registerCallback();
} catch (Exception e) {
Log.e(TAG, "error", e);
}
}else{
//注册系统的广播
registerReciver(RECIVER_ANDROID_NET_CHANGE);
}
}
@TargetApi(Build.VERSION_CODES.M)
//注册回调
private void registerCallback() {
ConnectivityManager connectivitymanager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
connectivitymanager.requestNetwork(new NetworkRequest.Builder().build(), new ConnectivityManager.NetworkCallback(){
@Override
public void onAvailable(Network network) {
// TODO Auto-generated method stub
super.onAvailable(network);
Log.d(TAG, "onAvailable broadcast");
Toast.makeText(BtrunCApp.this, "app onAvailable broadcast", 0).show();
//发送广播
Intent intent=new Intent();
intent.setAction(RECIVER_SELF_NET_CHANGE);
BtrunCApp.this.sendBroadcast(intent);
Log.d(TAG, "send broadcast");
}
});
}
// 注册广播
private void registerReciver(String action) {
Log.d(TAG, "registerReciver");
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(action);
registerReceiver(new CommonBroadcastReceiver(), intentFilter);
}
`
3,广播中实现自己的逻辑
public class CommonBroadcastReceiver extends BroadcastReceiver {
public static final String TAG = CommonBroadcastReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(TAG, "action = " + action);
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)||intent.getAction().equals(BtrunCApp.RECIVER_SELF_NET_CHANGE)) {
//自己的逻辑,监听网络变化需要执行的逻辑
}
}
}
“`