Switch On Wifi network - Android Network

Android examples for Network:Network Operation

Description

Switch On Wifi network

Demo Code


//package com.java2s;

import android.content.Context;

import android.net.wifi.WifiManager;
import android.provider.Settings;

public class Main {
    /**/*  ww w  .ja  v a 2s  . c  o  m*/
     * Switch On Wifi network
     * 
     * @param context
     *            - Context
     * @return true if Wifi successfully switched on
     * @throws SettingNotFoundException
     *             if Wifi settings were not found
     */
    public static boolean setWifiOn(Context context) {
        WifiManager wifiMng = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        if (wifiMng == null) {
            return false;
        }
        if (wifiMng.isWifiEnabled()) {
            return true;
        }
        Settings.System.putInt(context.getContentResolver(),
                Settings.Secure.WIFI_ON, 1);
        try {
            wifiMng.reassociate();
            wifiMng.reconnect();
            wifiMng.setWifiEnabled(true);
            Settings.System.putInt(context.getContentResolver(),
                    Settings.Secure.WIFI_ON, 1);
            Thread.sleep(5000);
            return wifiMng.isWifiEnabled();
        } catch (Exception e) {
            return false;
        }
    }
}

Related Tutorials