Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android安卓獲取網絡狀態

Android安卓獲取網絡狀態

編輯:關於Android編程

首先在AndroidManifest.xml添加權限


1,判斷是否有網絡連接

public boolean isNetworkConnected(Context context) {  
    if (context != null) {  
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
                .getSystemService(Context.CONNECTIVITY_SERVICE);  
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();  
        if (mNetworkInfo != null) {  
            return mNetworkInfo.isAvailable();  
        }  
    }  
    return false;  
}

2.判斷WIFI網絡是否可用

public boolean isWifiConnected(Context context) {  
    if (context != null) {  
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
                .getSystemService(Context.CONNECTIVITY_SERVICE);  
        NetworkInfo mWiFiNetworkInfo = mConnectivityManager  
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);  
        if (mWiFiNetworkInfo != null) {  
            return mWiFiNetworkInfo.isAvailable();  
        }  
    }  
    return false;  
}

3.判斷MOBILE網絡是否可用

public boolean isMobileConnected(Context context) {  
    if (context != null) {  
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context  
                .getSystemService(Context.CONNECTIVITY_SERVICE);  
        NetworkInfo mMobileNetworkInfo = mConnectivityManager  
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);  
        if (mMobileNetworkInfo != null) {  
            return mMobileNetworkInfo.isAvailable();  
        }  
    }  
    return false;  
}

4.判斷網絡類型

            //返回值 -1:沒有網絡  1:WIFI網絡2:wap網絡3:net網絡
	    public static int GetNetype(Context context)
	    { 
	        int netType = -1;  
	        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
	        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
	        if(networkInfo==null)
	        { 
	            return netType; 
	        } 
	        int nType = networkInfo.getType(); 
	        if(nType==ConnectivityManager.TYPE_MOBILE)
	        { 
	            if(networkInfo.getExtraInfo().toLowerCase().equals("cmnet"))
	            { 
	                netType = 3; 
	            } 
	            else
	            { 
	                netType = 2; 
	            } 
	        } 
	        else if(nType==ConnectivityManager.TYPE_WIFI)
	        { 
	            netType = 1; 
	        } 
	        return netType; 
	    }
		


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved