如何启用/移动数据从编程 [英] How to enable mobile data on/off programmatically

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

问题描述

在机器人如何启用安卓4.4及以上版本和关闭移动数据。 我已经使用这个code,但它不工作在Android的Andr​​oid 4.4系统和版本

 私人无效setMobileDataEnabled(上下文的背景下,布尔启用){
    最后ConnectivityManager赌侠=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    最后类conmanClass =的Class.forName(conman.getClass()的getName());
    最后一个字段iConnectivityManagerField = conmanClass.getDeclaredField(MSERVICE);
    iConnectivityManagerField.setAccessible(真正的);
    最终目标iConnectivityManager = iConnectivityManagerField.get(赌侠);
    最后类iConnectivityManagerClass =的Class.forName(iConnectivityManager.getClass()的getName());
    最后一个方法setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod(setMobileDataEnabled,Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(真正的);

    setMobileDataEnabledMethod.invoke(iConnectivityManager,启用);
}
 

解决方案

您无法访问移动数据的开/关programmaticaly上面的Andr​​oid 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 android 4.4 and 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);
}

解决方案

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天全站免登陆