disable Wifi NetWork - Android Network

Android examples for Network:Network Operation

Description

disable Wifi NetWork

Demo Code


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

public class Main {
    public static void disableNetWork(Context context) {
        disableWifi(context);/*w ww . j  a  v a2  s  .com*/
        disableMobileNetWork(context, false);
    }

    private static void disableWifi(Context context) {
        WifiManager wifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING
                || wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            wifiManager.setWifiEnabled(false);
        }
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private static void disableMobileNetWork(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) {
            e.printStackTrace(System.out);
        }
    }
}

Related Tutorials