Android進行網絡聯網的一些操作時,經常會對網絡是否已經連接配接成功進行判斷。我們通常會對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 ([email protected])
* 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)
public static boolean isNetworkConnected(Context mContext){
return (isWifiContected(mContext) || isNetContected(mContext));
* 判斷移動網絡是否開啟
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) {
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");
* 判斷移動網絡是否連接配接成功!
* @param context
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是否連接配接成功
public static boolean isWifiContected(Context context){
NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifiNetworkInfo.isConnected())
Log.i(Thread.currentThread().getName(), "isWifiContected");
Log.i(Thread.currentThread().getName(), "isWifiDisconnected");
}
本文轉自xuzw13 51CTO部落格,原文連結:http://blog.51cto.com/xuzhiwei/1003059,如需轉載請自行聯系原作者