如何以编程方式启用/关闭移动数据 [英] How to enable mobile data on/off programmatically

查看:53
本文介绍了如何以编程方式启用/关闭移动数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在android中如何在android 4.4及以上版本中开启和关闭移动数据.我已经使用过这段代码,但它在 android 4.4 及以上版本中不起作用:

In android how to enable mobile data on and off in android 4.4 and above versions. I have used this code but it is not working in android 4.4 and above versions:

private void setMobileDataEnabled(Context context, boolean enabled){
    final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final Class conmanClass = Class.forName(conman.getClass().getName());
    final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
    iConnectivityManagerField.setAccessible(true);
    final Object iConnectivityManager = iConnectivityManagerField.get(conman);
    final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);

    setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}

推荐答案

您无法在 android 4.4 以上以编程方式打开/关闭移动数据.出于安全原因,它已被停止,您可以使用对话框要求用户启用移动数据,然后如果他启用您就可以完成您的任务.

You cannot access mobile data on / off programmaticaly above android 4.4 .It have been made stopped for security reasons ,instead you can ask the user using a dialog to enable the mobile data and then if he enable you can do your task.

这篇关于如何以编程方式启用/关闭移动数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆