1. 程式人生 > >監聽網路變化的廣播

監聽網路變化的廣播

BroadcastReceiverNetWork mReceiverNetWork = new BroadcastReceiverNetWork();
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        context.registerReceiver(mReceiverNetWork, mFilter);
 public static class BroadcastReceiverNetWork extends BroadcastReceiver {
        public BroadcastReceiverNetWork() {
        }

        public void onReceive(Context context, Intent intent) {
            getNetWorkType(context);
        }
    }
    public static int getNetWorkType(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService("connectivity");
        NetworkInfo ni = cm.getActiveNetworkInfo();
        byte netType;
        if(ni != null && ni.isConnectedOrConnecting()) {
            switch(ni.getType()) {
                case 0:
                    switch(ni.getSubtype()) {
                        case 1:
                        case 2:
                        case 4:
                        case 7:
                        case 11:
                        case 16:
                            netType = 2;
                            RxToast.info("切換到2G環境下");
                            return netType;
                        case 3:
                        case 5:
                        case 6:
                        case 8:
                        case 9:
                        case 10:
                        case 12:
                        case 14:
                        case 15:
                        case 17:
                            netType = 3;
                            RxToast.info("切換到3G環境下");
                            return netType;
                        case 13:
                        case 18:
                            netType = 4;
                            RxToast.info("切換到4G環境下");
                            return netType;
                        default:
                            String subtypeName = ni.getSubtypeName();
                            if(!subtypeName.equalsIgnoreCase("TD-SCDMA") && !subtypeName.equalsIgnoreCase("WCDMA") && !subtypeName.equalsIgnoreCase("CDMA2000")) {
                                netType = 5;
                            } else {
                                netType = 3;
                            }

                            RxToast.normal("未知網路");
                            return netType;
                    }
                case 1:
                    netType = 1;
                    RxToast.success("切換到wifi環境下");
                    break;
                default:
                    netType = 5;
                    RxToast.normal("未知網路");
            }
        } else {
            netType = -1;
            RxToast.error(context, "當前無網路連線").show();
        }

        return netType;
    }

記得反註冊