1

我想通过按下按钮 On 或按钮 Off 来打开或关闭移动数据。我已经在清单文件中为 setOnClickListner 和 Given Permission 编写了这段代码。但我无法打开移动数据。我只想打开移动数据没有任何配置。我的 android 操作系统版本是 Marshmellow。

  btnDataOn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                final ConnectivityManager conman = (ConnectivityManager)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, true); } catch (NoSuchMethodException e1) {
                e1.printStackTrace();

            } catch (InvocationTargetException e1) {
                e1.printStackTrace();
            } catch (NoSuchFieldException e1) {
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            }

        }
    });

以下是清单文件:-

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
4

1 回答 1

0
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);
}

检查您的清单类的此权限。如果需要,请在运行时链接请求许可。

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
于 2018-04-13T17:51:57.700 回答