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

淺唱寂寞╮ 提交于 2019-12-04 20:34:35
Neal

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