Disable mobile network programmatically

后端 未结 3 987
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 17:16

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 m

3条回答
  •  伪装坚强ぢ
    2020-12-29 17:54

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

    you must add below permission in menifest.xml

    
    

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

提交回复
热议问题