set Mobile Data Enabled - Android android.net

Android examples for android.net:ConnectivityManager

Description

set Mobile Data Enabled

Demo Code

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main{

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void setMobileDataEnabled(Context context)
            throws ClassNotFoundException, NoSuchFieldException,
            IllegalAccessException, NoSuchMethodException,
            InvocationTargetException {
        final ConnectivityManager conman = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final Class conmanClass = Class
                .forName(conman.getClass().getName());
        final Field connectivityManagerField = conmanClass
                .getDeclaredField("mService");
        connectivityManagerField.setAccessible(true);
        final Object connectivityManager = connectivityManagerField
                .get(conman);/*from   w  ww.  j a v a  2  s. co m*/
        final Class connectivityManagerClass = Class
                .forName(connectivityManager.getClass().getName());
        final Method setMobileDataEnabledMethod = connectivityManagerClass
                .getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
        setMobileDataEnabledMethod.setAccessible(true);

        setMobileDataEnabledMethod.invoke(connectivityManager, true);
    }

}

Related Tutorials