码迷,mamicode.com
首页 > 移动开发 > 详细

Android安卓获取网络状态

时间:2014-12-09 01:56:25      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:android   blog   io   java   on   2014   log   cti   as   

首先在AndroidManifest.xml添加权限

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

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; 
	    }
		


Android安卓获取网络状态

标签:android   blog   io   java   on   2014   log   cti   as   

原文地址:http://blog.csdn.net/sysprogram/article/details/41814029

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!