turn Mobile Data Off - Android Network

Android examples for Network:Network Status

Description

turn Mobile Data Off

Demo Code


//package com.java2s;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import android.content.Context;
import android.net.ConnectivityManager;

public class Main {
    private static void turnMobileDataOff(Context context) {
        setMobileData(context, false);/*from w  w  w  . ja  v  a  2  s  .  co  m*/
    }

    private static void setMobileData(Context context, boolean enabled) {
        try {
            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);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials