最近工作工程中遇到一个问题。问题很简单,这里做个笔记,Android进行网络联网的一些操作时,经常会对网络是否已经连接成功进行判断。我们通常会对wifi和移动网络进行判断,我们需要判断网络设备是否开启,是否连接成功。之前我只是判断了网络设备是否已经开启,然后进行测试的时候,网络开启了(我连接的是wifi),后台报错了,说访问那个地址无法访问的错误,后来发现wifi虽然开启了,但是没有连接成功!所以就得判断网络是否连接成功!就改写了代码,直接判断网络是否连接。废话不多说,直接上代码了。
package com.example.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.Log;
/**
*
* @author XuZhiwei (xuzw13@gmail.com)
* Weibo:http://weibo.com/xzw1989
* Create at 2012-9-22 上午11:25:04
*/
public class NetUtil {
/**
* 判断Network是否开启(包括移动网络和wifi)
*
* @return
*/
public static boolean isNetworkEnabled(Context mContext) {
return ( isNetEnabled(mContext)|| isWIFIEnabled(mContext));
}
/**
* 判断Network是否连接成功(包括移动网络和wifi)
* @return
*/
public static boolean isNetworkConnected(Context mContext){
return (isWifiContected(mContext) || isNetContected(mContext));
}
/**
* 判断移动网络是否开启
*
* @return
*/
public static boolean isNetEnabled(Context context) {
boolean enable = false;
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
if (telephonyManager.getNetworkType() != TelephonyManager.NETWORK_TYPE_UNKNOWN) {
enable = true;
Log.i(Thread.currentThread().getName(), "isNetEnabled");
}
}
return enable;
}
/**
* 判断wifi是否开启
*/
public static boolean isWIFIEnabled(Context context) {
boolean enable = false;
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
enable = true;
Log.i(Thread.currentThread().getName(), "isWifiEnabled");
}
Log.i(Thread.currentThread().getName(), "isWifiDisabled");
return enable;
}
/**
* 判断移动网络是否连接成功!
* @param context
* @return
*/
public static boolean isNetContected(Context context){
ConnectivityManager connectivityManager
= (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobileNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(mobileNetworkInfo.isConnected())
{
Log.i(Thread.currentThread().getName(), "isNetContected");
return true ;
}
Log.i(Thread.currentThread().getName(), "isNetDisconnected");
return false ;
}
/**
* 判断wifi是否连接成功
* @param context
* @return
*/
public static boolean isWifiContected(Context context){
ConnectivityManager connectivityManager
= (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifiNetworkInfo.isConnected())
{
Log.i(Thread.currentThread().getName(), "isWifiContected");
return true ;
}
Log.i(Thread.currentThread().getName(), "isWifiDisconnected");
return false ;
}
}