0

in my application i have this button btn3GOn that if i tap it will enable the data connection, i have read and search for some clues but i fail but the method was the best answer. now when i tap the button it doesnt turn on the data connection, i am using jellybean API.

        btn3GOon.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            try {
                setMobileDataEnabled(null, false);
            } catch(Exception e){
                e.printStackTrace();
            }
        }                                               
    });
}       
    private void setMobileDataEnabled(Context context, boolean enabled) throws Exception {
        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);
    }

1 Answers1

0

That method of modifying the connection was deprecated in 4.3 according to this post: How to disable Mobile Data on Android

Looking at the AOSP it is definitely deprecated as of Lollipop (5.0.0) but I don't see that in the docs as it appears to still be present pre-Lollipop.

Remember you have to ask for the permission "CHANGE_NETWORK_STATE":

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
Community
  • 1
  • 1
Jim
  • 10,172
  • 1
  • 27
  • 36
  • i figured out what went wrong and it is on the null that should be getApplicationContext. anyways thank you for telling me its' deprecation. – kim caboteja Oct 13 '15 at 19:31