Wifi模式下判断数据开关是否开启(Android)
以下采用反射的方式获取当前GPRS数据开关是否打开,在Wi-Fi开启时也同样有效。
注意⚠️:此处判断的是系统的数据【开关】是否打开,而非当前是否正在使用流量数据。
代码如下
/**
* 判断GPRS开关是否打开(注意是【开关】并非指当前是否使用数据)
* @param context
* @return
*/
private static Method mMethodGetMobileDataEnabled;
public static boolean getMobileDateMode(Context context) {
if (mMethodGetMobileDataEnabled == null) {
try {
mMethodGetMobileDataEnabled = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled",
(Class[]) null);
mMethodGetMobileDataEnabled.setAccessible(true);
} catch (NoSuchMethodException e) {
if (DEBUG) {
Log.e(TAG, "get mobile data method err", e);
}
}
}
if (mMethodGetMobileDataEnabled != null) {
ConnectivityManager cm = (ConnectivityManager) ContextHelper.getSystemService(context,
Context.CONNECTIVITY_SERVICE);
try {
boolean ret = (Boolean) mMethodGetMobileDataEnabled.invoke(cm, (Object[]) null);
return ret;
} catch (Exception e) {
if (DEBUG) {
Log.e(TAG, "GetMobileDataEnabled err", e);
}
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
int type = info.getType();
if (type == ConnectivityManager.TYPE_MOBILE || type == ConnectivityManager.TYPE_MOBILE_DUN
|| type == ConnectivityManager.TYPE_MOBILE_HIPRI
|| type == ConnectivityManager.TYPE_MOBILE_MMS
|| type == ConnectivityManager.TYPE_MOBILE_SUPL) {
if (DEBUG) {
Log.d(TAG, "active is mobile");
}
return true;
}
}
}
}
/**
* 当上述方法无效的情况再执行以下方法
* 在某些机型下面这种方法有误
*/
try {
int ret = 1;
if (Build.VERSION.SDK_INT >= 17) {
try {
ret = Settings.Global.getInt(context.getContentResolver(), "mobile_data");
} catch (NoClassDefFoundError e) {
try {
ret = Settings.Secure.getInt(context.getContentResolver(), "mobile_data");
} catch (Settings.SettingNotFoundException ee) {
if (DEBUG) {
Log.e(TAG, "err", ee);
}
}
}
} else {
ret = Settings.Secure.getInt(context.getContentResolver(), "mobile_data");
}
return ret == 1;
} catch (Exception ex) {
if (DEBUG) {
Log.e(TAG, "another method ex =", ex);
}
}
return false;
}
.
.
.
.
.
.
.
.
.
.
.
下面附带,判断当前是否正在使用GPRS数据(即GPRS实际是否处于连接状态【非开关】):
代码如下
public static boolean isNetWorkIsUsing(Context context) {
if (context != null) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager != null) {
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
return info.isAvailable();
}
}
}
return false;
}