android网络监听学习笔记

网络变化android自带广播、采用广播接收器接收网络变化的监听

自定义广播接收
public class NetworkInfoBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "NetworkInfoBroadcastRec";

    @Override
    public void onReceive(Context context, Intent intent) {
        String state = intent.getAction();
        if (!TextUtils.isEmpty(state)) {
            //wifi的转态监听
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(state)) {
                int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (wifiState) {
                    case WifiManager.WIFI_STATE_DISABLED:
                        Log.e(TAG, "已禁用Wi-Fi");
                        break;
                    case WifiManager.WIFI_STATE_DISABLING:
                        Log.e(TAG, "已启用Wi-Fi");
                        break;
                }
            }
            //网络监听
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(state)) {
                Log.e(TAG, "网络连接已发生更改 ");
                //获取联网状态的NetworkInfo对象
                ConnectivityManager manager = (ConnectivityManager) MyApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
                @SuppressLint("MissingPermission") NetworkInfo info = manager.getActiveNetworkInfo();
                if (info != null && info.isAvailable()) {
                    int type = info.getType();
                    switch (type) {
                        case 0://移动网络
                            Log.e(TAG, "移动网络");
                            break;
                        case 1://wifi
                            Log.e(TAG, "wifi");
                            break;
                        default:
                            break;
                    }
                } else {
                    Log.e(TAG, "无网络");
                }
            }
        }
    }
}
为了方便全局监听在baseactivity中注册
public class BaseActivity extends AppCompatActivity {
    NetworkInfoBroadcastReceiver receiver = new NetworkInfoBroadcastReceiver();
    @Override
    protected void onResume() {
        super.onResume();
        Register();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
    }
   private void Register() {
            //这里我只添加了wifi姿态和网络变化的广播、还有一些其他的网络的广播可以自行添加
            IntentFilter filter = new IntentFilter();
            filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(receiver, filter);
        }

}

你可能感兴趣的:(android网络监听学习笔记)