android獲取及監聽手機網絡狀態

一、獲取當前手機聯網方式是WiFi還是手機4G數據

private boolean getNetworkType(){
        ConnectivityManager mConnectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        //檢查網絡鏈接
        NetworkInfo info = mConnectivity.getActiveNetworkInfo();
        int netType = mConnectivity.getActiveNetworkInfo().getType();
        if (netType == ConnectivityManager.TYPE_WIFI) {  //WIFI
            ChangYouLog.i(TAG,"當前是WIFI連接 isConnected = "+info.isConnected());
            return info.isConnected();
        } else if (netType == ConnectivityManager.TYPE_MOBILE) {   //MOBILE
            ChangYouLog.i(TAG,"當前是手機網絡連接 isConnected = "+info.isConnected());
            return info.isConnected();
        } else {
            ChangYouLog.i(TAG,"當前沒有網絡連接 isConnected = "+info.isConnected());
            return false;
        }
    }

二、監聽手機網絡變化

private class MyBroadcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {//監聽網絡連接
                //獲取聯網狀態的NetworkInfo對象
                NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                if (info != null) {
                    //如果當前的網絡連接成功並且網絡連接可用
                    if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
                        if (info.getType() == ConnectivityManager.TYPE_WIFI){
                            ChangYouLog.i(TAG,"連接上WiFi");
                        }else if (info.getType() == ConnectivityManager.TYPE_MOBILE){
                            ChangYouLog.i(TAG,"連接上移動網絡數據");
                            CYouLbyMicroClient.getInstance().gameEvent("Network_4G_reminder");
                        }
                    } else {
                        ChangYouLog.i(TAG,"網絡斷開");
                    }
                }
            }
        }
    }

註:需要添加網絡狀態權限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

總結

到此這篇關於android獲取及監聽手機網絡狀態的文章就介紹到這瞭,更多相關android網絡狀態內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: