以编程方式使用Android app打开或关闭移动数据。

时间:2018-04-13 17:18:38

标签: android android-studio mobile-data

我希望通过按下按钮打开或关闭移动数据或按钮关闭。我已经为setOnClickListner编写了此代码并在清单文件中给出了权限。但是我无法打开移动数据。我只是想转向没有任何配置的移动数据。我的Android Os版本是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"/>

1 个答案:

答案 0 :(得分: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);
}

检查您的清单类的此权限。并在运行时link if needed询问权限。

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