How to turn off 3G data connection programmatically in android?

♀尐吖头ヾ 提交于 2019-12-06 13:16:47

问题


I want to Enable/Disable 3G and other Data connections separately.Is it possible to access 3G individually?That means if the user selects the option 3G, then Enable/Disable 3G data connection only.And if the user selects the option Data Services, enable/disable data connections except 3G.Is it possible? I tried the following methods

enableDataConnectivity();
and
disableDataConnectivity();
of
TelephonyManager

But i think these methods turn off/on all data services in whole.I want to access 3G separately.

How to do this?


回答1:


This code sample should work for android phones running gingerbread and higher:

private void setMobileDataEnabled(Context context, boolean enabled) 
{
   final ConnectivityManager conman = (ConnectivityManager)    
   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);
}

This also requires the following permission.

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


来源:https://stackoverflow.com/questions/14116948/how-to-turn-off-3g-data-connection-programmatically-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!