更新时间:2022-11-13 08:00:23
以下code会告诉你,如果移动数据已启用与否,不管是否有一个移动数据连接活跃在那一刻,或无论是否wifi的启用/激活。这code只能在Android 2.3(姜饼),后来。 其实这code也适用于早期版本的Android,以及; - )
The following code will tell you if "mobile data" is enabled or not, regardless of whether or not there is a mobile data connection active at the moment or whether or not wifi is enabled/active or not. This code only works on Android 2.3 (Gingerbread) and later. Actually this code also works on earlier versions of Android as well ;-)
boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean)method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API
// TODO do whatever error handling you want here
}
请注意:您需要有权限 android.permission.ACCESS_NETWORK_STATE
才能够使用这个code
Note: you will need to have permission android.permission.ACCESS_NETWORK_STATE
to be able to use this code.