如何在所有版本中启用/禁用移动数据,包括棒棒糖5

时间:2015-05-28 11:00:55

标签: android gprs

我使用了这些代码,这些代码在Lollipop之前工作正常但在Lollipop上没有用。 我想做的就是启用/禁用移动数据。



 private void setMobileDataEnabled(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final Class conmanClass = Class.forName(conman.getClass().getName());
        final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
        connectivityManagerField.setAccessible(true);
        final Object connectivityManager = connectivityManagerField.get(conman);
        final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
        final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
        setMobileDataEnabledMethod.setAccessible(true);

        setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
    }




请帮我告诉我在棒棒糖中是怎么做到的?

1 个答案:

答案 0 :(得分:1)

用于启用Wifi

    WifiManager wifiManager = (WifiManager) mContext
    .getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);

对于数据启用:

   ConnectivityManager dataManager;
dataManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = null;
try {
    dataMtd = ConnectivityManager.class
            .getDeclaredMethod(
                    "setMobileDataEnabled",
                    boolean.class);
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}
dataMtd.setAccessible(true);
try {
    dataMtd.invoke(dataManager, true);
} catch (IllegalAccessException
        | IllegalArgumentException
        | InvocationTargetException e) {
    e.printStackTrace();
}