Android 判断是否网络连接, 判断是否为WIFI,移动网络以及跳转网络设置界面
生活随笔
收集整理的這篇文章主要介紹了
Android 判断是否网络连接, 判断是否为WIFI,移动网络以及跳转网络设置界面
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這個自己在項目中總結了一個工具類 如下
public class NetWorkUtils {private NetWorkUtils() {/* cannot be instantiated */throw new UnsupportedOperationException("cannot be instantiated");}/*** 判斷網絡是否連接* @param context* @return*/public static boolean isConnected(Context context) {if (context == null) {Log.e("111111", "傳進來的context實例為空!");return false;}ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);if (null != connectivity) {NetworkInfo info = connectivity.getActiveNetworkInfo();if (null != info && info.isConnected()) {if (info.getState() == NetworkInfo.State.CONNECTED) {return true;}}}return false;}/*** 判斷是否是wifi連接*/public static boolean isWifi(Context context) {ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);if (cm == null)return false;return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;}/*** 判斷是否為移動網絡*/public static boolean isMobile(Context context) {ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);if (cm == null)return false;return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_MOBILE;}/*** 打開網絡設置界面*/public static void openSetting(Activity activity) {Intent intent = new Intent("/");ComponentName cm = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");intent.setComponent(cm);intent.setAction("android.intent.action.VIEW");activity.startActivityForResult(intent, 0);}}
?
使用的時候判斷下即可
if (!NetWorkUtils.isConnected(this)) {ToastUtils.showLong("網絡無連接");
}
或者自己封裝網絡請求的時候把這個判斷寫進去也行。。。。
總結
以上是生活随笔為你收集整理的Android 判断是否网络连接, 判断是否为WIFI,移动网络以及跳转网络设置界面的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 花生十里出山泉是谁画的啊?
- 下一篇: Android 获取联网的IP地址