control NetWork - Android Network

Android examples for Network:Network Operation

Description

control 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 controlNetWork(Context context, boolean enabled) {
        controlWifi(context, enabled);/*from   w  w  w . j a va 2s.co  m*/
        controlMobileNetWork(context, enabled);
    }

    public static void controlWifi(Context context, boolean enabled) {
        WifiManager wifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING
                || wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            wifiManager.setWifiEnabled(enabled);
        } else {
            wifiManager.setWifiEnabled(enabled);
        }
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void controlMobileNetWork(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