Created
January 30, 2015 18:01
-
-
Save greatcodeeer/3fe5b7334702ca885054 to your computer and use it in GitHub Desktop.
Android 获取网络状态
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 网络工具类 | |
*/ | |
public class NetworkUtil { | |
public static String NETWORK_TYPE_WIFI = "WIFI"; | |
public static String NETWORK_TYPE_MOBILE = "MOBILE"; | |
public static String NETWORK_TYPE_ERROR = "ERROR"; | |
/** | |
* 返回网络是否可用 | |
* @param context | |
* @return 网络可用则返回true,否则返回false | |
*/ | |
public static boolean isAvailable(Context context) { | |
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo info = cm.getActiveNetworkInfo(); | |
return info != null && info.isAvailable(); | |
} | |
/** | |
* 判断网络连接状态 | |
* @param context | |
*/ | |
public static String getNetType(Context context) { | |
try { | |
ConnectivityManager connectivity = (ConnectivityManager) context | |
.getSystemService(Context.CONNECTIVITY_SERVICE); | |
if (connectivity != null) { | |
NetworkInfo info = connectivity.getActiveNetworkInfo(); | |
if (info != null && info.isConnected()) { | |
if (info.getState() == NetworkInfo.State.CONNECTED) { | |
if (info.getType() == ConnectivityManager.TYPE_WIFI) { | |
// wifi | |
return NETWORK_TYPE_WIFI; | |
} else { | |
// 手机网络 | |
return NETWORK_TYPE_MOBILE; | |
} | |
} | |
} | |
} | |
} catch (Exception e) { | |
// 网络错误 | |
return NETWORK_TYPE_ERROR; | |
} | |
// 网络错误 | |
return NETWORK_TYPE_ERROR; | |
} | |
/** | |
* 返回Wifi是否启用 | |
* @param context | |
* @return Wifi网络可用则返回true,否则返回false | |
*/ | |
public static boolean isWIFIActivate(Context context) { | |
return ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)) | |
.isWifiEnabled(); | |
} | |
/** | |
* 修改Wifi状态 | |
* @param context | |
* @param status | |
* true为开启Wifi,false为关闭Wifi | |
*/ | |
public static void changeWIFIStatus(Context context, boolean status) { | |
((WifiManager) context.getSystemService(Context.WIFI_SERVICE)) | |
.setWifiEnabled(status); | |
} | |
/** | |
* 跳转到网络设置 | |
* @param context | |
*/ | |
public static void startNetSettingActivity(Context context){ | |
Intent intent = new Intent( | |
Settings.ACTION_WIFI_SETTINGS); | |
context.startActivity(intent); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment