我使用此代码关闭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 anctionbar也预览Android版本。我的一个朋友用android 2.3.6尝试了应用程序并告诉我有一个崩溃..我现在看不到任何logcat但我认为问题是上面的代码。我知道用android 2.3有另一种方法可以关闭3g,但我不知道哪个。我怎样才能检测到Android版本,并制作如下:如果android&gt; = 4使用我发布的代码,如果android&lt; = 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);
}
所以,如果版本是&gt; =姜饼这将是正确的代码?
答案 0 :(得分:2)
如何使用它的示例:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
// only for gingerbread and newer versions
}
另外,您可以按照以下方式检查版本4&gt; =或&lt; = 4 android。
if(Build.VERSION.SDK_INT >= 4.0){
//this code will be executed on devices running on DONUT (NOT ICS) or later
}
since constant 4 represents donut: public static final int DONUT = 4;
您可以找到查看Build.VERSION。
的Android版本