我使用此代码关闭 wifi 连接和数据连接
public static class LowBatteryReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent){
wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
wifi = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
try {
ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Class<?> conmanClass = Class.forName(conman.getClass().getName());
Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
Object iConnectivityManager = iConnectivityManagerField.get(conman);
Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
该类将在一个工作方法中被调用,但这并不重要。我有一个带有 android 4.3 的 nexus 4 并且代码有效。同样在 android 4.0.3/4、4.1、4.1.2、4.2.1 和 .4.2.2 中。我使用 ActionbarSherlock 库,所以我也可以使用 holo.light 操作栏和预览 android 版本。我的一个使用 android 2.3.6 的朋友尝试了该应用程序并告诉我崩溃了。我现在看不到任何 logcat,但我认为问题出在上面的代码上。我知道使用 android 2.3 有另一种关闭 3g 的方法,但我不知道是哪一种。我如何检测 android 版本并制作类似:如果 android >= 4 使用我发布的代码,如果 android <=4 使用另一个代码(如果有人能告诉我哪个更好,谢谢)。
编辑:我找到了一个带有 android 2.3 的数据代码。我有没有做类似的事情
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
Method dataConnSwitchmethod;
Class telephonyManagerClass;
Object ITelephonyStub;
Class ITelephonyClass;
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED){
isEnabled = true;
}else{
isEnabled = false;
}
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());
if (isEnabled) {
dataConnSwitchmethod = ITelephonyClass
.getDeclaredMethod("disableDataConnectivity");
} else {
dataConnSwitchmethod = ITelephonyClass
.getDeclaredMethod("enableDataConnectivity");
}
dataConnSwitchmethod.setAccessible(true);
dataConnSwitchmethod.invoke(ITelephonyStub);
}
所以如果版本是>=姜饼,这将是代码对吗?