简体   繁体   English

如何在应用内禁用/启用移动数据(Android)

[英]How to disable/enable mobile data from within app (Android)

I'm still relatively new to Android app development but im trying to create an app which toggles internet connectivity upon the click of a button within the app. 我仍然相对较新的Android应用程序开发,但我试图创建一个应用程序,点击应用程序内的按钮切换互联网连接。 is there any way to actually do this, as i havent found any resources online on how to do this. 有没有办法真正做到这一点,因为我没有在网上找到任何有关如何做到这一点的资源。 ive included all user permissions that might be of help in the app's manifest but cant seem to make it work. 我已经包含了可能在应用程序清单中提供帮助的所有用户权限,但似乎无法使其正常工作。 Thanks. 谢谢。

This code sample should work for android phones. 此代码示例应适用于Android手机。 For Android 2.3 and above: 对于Android 2.3及更高版本:

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

also requires the following permission 还需要以下许可

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

Please follow below URL for more clarification. 请按照以下网址获取更多说明。

EDIT: 编辑:

1: Enable/disable data connection in android programmatically 1: 以编程方式在android中启用/禁用数据连接

2: How can i turn off 3G/Data programmatically on Android? 2: 如何在Android上以编程方式关闭3G /数据?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM