禁用移动网络编程 [英] Disable mobile network programmatically

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

问题描述

我开发一个应用程序中,用户可以启用按钮点击/禁用移动网络。我用Google搜索关于这个,但我只得到飞行模式的解决方案。在飞行模式下,WI-FI和蓝牙也被禁用。我不想让他们通过使用飞行模式的概念来禁用。我想唯一的移动网络被禁用。什么是实现它的可能的方式亲语法?

I'm developing an app in which user can enable/disable mobile network on button click. I googled regarding this, but I get the solution of Airplane mode only. In airplane mode, WI-FI and Bluetooth are also disabled. I don't want them to disable by using airplane mode concept. I want only mobile network to be disabled. What are the possible way to implement it pro-grammatically?

推荐答案

低于code为禁用/启用移动网络使用。

Use below code for Disable/Enable Mobile Network..

private void setMobileConnectionEnabled(Context context, boolean enabled) {
           final ConnectivityManager mConnectivityManager = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
           final Class mClass = Class.forName(mConnectivityManager.getClass().getName());
           final Field mField = mClass.getDeclaredField("mService");
           mField.setAccessible(true);
           final Object mObject = mField.get(mConnectivityManager);
           final Class mConnectivityManagerClass =  Class.forName(mObject.getClass().getName());
           final Method setMobileDataEnabledMethod = mConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
           setMobileDataEnabledMethod.setAccessible(true);

           setMobileDataEnabledMethod.invoke(mObject, enabled);
}

您必须在 menifest.xml

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

如果你想关闭整个网络,那么你可以做的禁用/启用飞行模式

If you want Disable whole network then you can do Disable/Enable AirplaneMode

这篇关于禁用移动网络编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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