turn Network On - Android Network

Android examples for Network:Network Operation

Description

turn Network On

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.NetworkInfo;
import android.net.wifi.WifiManager;

public class Main {
    public static void turnNetworkOn(Context c) {
        turnMobileDataOn(c);/*from   ww  w  .j  a  va  2s  . c om*/
        turnWifiOn(c);
        while (!networkConnected(c))
            ;
    }

    private static void turnMobileDataOn(Context context) {
        setMobileData(context, true);
    }

    private static void turnWifiOn(Context c) {
        getWifiManager(c).setWifiEnabled(true);
    }

    public static boolean networkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            return true;
        }
        return false;
    }

    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);
        }
    }

    private static WifiManager getWifiManager(Context c) {
        return (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
    }
}

Related Tutorials