Example usage for android.net.wifi WifiManager setWifiEnabled

List of usage examples for android.net.wifi WifiManager setWifiEnabled

Introduction

In this page you can find the example usage for android.net.wifi WifiManager setWifiEnabled.

Prototype

public boolean setWifiEnabled(boolean enabled) 

Source Link

Document

Enable or disable Wi-Fi.

Usage

From source file:nl.nikhef.eduroam.WiFiEduroam.java

private void saveWifiConfig() {
    WifiManager wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
    wifiManager.setWifiEnabled(true);

    WifiConfiguration currentConfig = new WifiConfiguration();

    List<WifiConfiguration> configs = null;
    for (int i = 0; i < 10 && configs == null; i++) {
        configs = wifiManager.getConfiguredNetworks();
        try {// w  ww .j a v  a 2  s.  c om
            Thread.sleep(1);
        } catch (InterruptedException e) {
            continue;
        }
    }

    // Use the existing eduroam profile if it exists.
    boolean ssidExists = false;
    if (configs != null) {
        for (WifiConfiguration config : configs) {
            if (config.SSID.equals(surroundWithQuotes(ssid))) {
                currentConfig = config;
                ssidExists = true;
                break;
            }
        }
    }

    currentConfig.SSID = surroundWithQuotes(ssid);
    currentConfig.hiddenSSID = false;
    currentConfig.priority = 40;
    currentConfig.status = WifiConfiguration.Status.DISABLED;

    currentConfig.allowedKeyManagement.clear();
    currentConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);

    // GroupCiphers (Allow most ciphers)
    currentConfig.allowedGroupCiphers.clear();
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    currentConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);

    // PairwiseCiphers (CCMP = WPA2 only)
    currentConfig.allowedPairwiseCiphers.clear();
    currentConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

    // Authentication Algorithms (OPEN)
    currentConfig.allowedAuthAlgorithms.clear();
    currentConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

    // Protocols (RSN/WPA2 only)
    currentConfig.allowedProtocols.clear();
    currentConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);

    // Enterprise Settings
    HashMap<String, String> configMap = new HashMap<String, String>();
    configMap.put(INT_SUBJECT_MATCH, subject_match);
    configMap.put(INT_ANONYMOUS_IDENTITY, "anonymous" + realm);
    configMap.put(INT_EAP, "TLS");
    configMap.put(INT_ENGINE, "1");
    configMap.put(INT_ENGINE_ID, "keystore");
    configMap.put(INT_CA_CERT, INT_CA_PREFIX + ca_name);
    configMap.put(INT_PRIVATE_KEY, INT_PRIVATE_KEY_PREFIX + client_cert_name);
    configMap.put(INT_PRIVATE_KEY_ID, INT_PRIVATE_KEY_ID_PREFIX + client_cert_name);
    configMap.put(INT_CLIENT_CERT, INT_CLIENT_CERT_PREFIX + client_cert_name);

    if (android.os.Build.VERSION.SDK_INT >= 11 && android.os.Build.VERSION.SDK_INT <= 17) {
        applyAndroid4_42EnterpriseSettings(currentConfig, configMap);
    } else if (android.os.Build.VERSION.SDK_INT >= 18) {
        applyAndroid43EnterpriseSettings(currentConfig, configMap);
    } else {
        throw new RuntimeException("API version mismatch!");
    }

    if (!ssidExists) {
        int networkId = wifiManager.addNetwork(currentConfig);
        wifiManager.enableNetwork(networkId, false);
    } else {
        wifiManager.updateNetwork(currentConfig);
        wifiManager.enableNetwork(currentConfig.networkId, false);
    }
    wifiManager.saveConfiguration();

}

From source file:org.droidmate.uiautomator2daemon.UiAutomator2DaemonDriver.java

/**
 * Based on: http://stackoverflow.com/a/12420590/986533
 *///from  w  w w  .  j a  v a2s.c  o m
private void turnWifiOn() {
    Log.d(uiaDaemon_logcatTag, "Ensuring WiFi is turned on.");
    WifiManager wfm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

    boolean wifiEnabled = wfm.setWifiEnabled(true);

    if (!wifiEnabled)
        Log.w(uiaDaemon_logcatTag, "Failed to ensure WiFi is enabled!");
}

From source file:cordova.plugins.Diagnostic.java

public void setWifiState(boolean enable) {
    WifiManager wifiManager = (WifiManager) this.cordova.getActivity().getSystemService(Context.WIFI_SERVICE);
    if (enable && !wifiManager.isWifiEnabled()) {
        wifiManager.setWifiEnabled(true);
    } else if (!enable && wifiManager.isWifiEnabled()) {
        wifiManager.setWifiEnabled(false);
    }// ww  w.j  a v a2 s  . co m
}

From source file:com.trigger_context.Main_Service.java

private void takeAction(String mac, InetAddress ip) {
    noti("comes to ", mac);

    SharedPreferences conditions = getSharedPreferences(mac, MODE_PRIVATE);
    Map<String, ?> cond_map = conditions.getAll();
    Set<String> key_set = cond_map.keySet();
    Main_Service.main_Service.noti(cond_map.toString(), "");
    if (key_set.contains("SmsAction")) {
        String number = conditions.getString("SmsActionNumber", null);
        String message = conditions.getString("SmsActionMessage", null);

        try {/*from w  w w .j a  va  2  s.  co m*/
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(number, null, message, null, null);
            noti("Sms Sent To : ", "" + number);
        } catch (Exception e) {
            noti("Sms Sending To ", number + "Failed");
        }
    }
    if (key_set.contains("OpenWebsiteAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Open_Url.class);
        dialogIntent.putExtra("urlAction", (String) cond_map.get("urlAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);

    }
    if (key_set.contains("ToggleAction")) {
        if (key_set.contains("bluetoothAction") && conditions.getBoolean("bluetoothAction", false)) {
            final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            bluetoothAdapter.enable();
        } else if (key_set.contains("bluetoothAction")) {
            final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            bluetoothAdapter.disable();
        }
        if (key_set.contains("wifiAction") && conditions.getBoolean("wifiAction", false)) {
            final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wm.setWifiEnabled(true);
        } else if (key_set.contains("wifiAction")) {
            final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wm.setWifiEnabled(false);
        }
    }
    if (key_set.contains("TweetAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Post_Tweet.class);
        dialogIntent.putExtra("tweetTextAction", (String) cond_map.get("tweetTextAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);
    }

    if (key_set.contains("EmailAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Email_Client.class);
        dialogIntent.putExtra("toAction", (String) cond_map.get("toAction"));
        dialogIntent.putExtra("subjectAction", (String) cond_map.get("subjectAction"));
        dialogIntent.putExtra("emailMessageAction", (String) cond_map.get("emailMessageAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);
    }
    if (key_set.contains("RemoteServerCmd")) {

        String text = conditions.getString("cmd", null);
        new Thread(new SendData("224.0.0.1", 9876, text)).start();
    }
    // network activities from here.
    // in all network actions send username first
    if (key_set.contains("FileTransferAction"))

    {
        String path = conditions.getString("filePath", null);
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 1
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataOutputStream out = null;
            out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(1);
            sendFile(out, path);

            noti("Sent " + path + " file to :",
                    getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    if (key_set.contains("ccfMsgAction"))

    {
        String msg = conditions.getString("ccfMsg", null);
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 2 is msg
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataOutputStream out = null;
            out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(2);
            out.writeUTF(msg);

            noti("Sent msg : '" + msg + "'", "to : "
                    + getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (key_set.contains("sync")) {
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 3 is sync
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(3);
            senderSync(in, out, Environment.getExternalStorageDirectory().getPath() + "/TriggerSync/");

            noti("Synced with:",
                    getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:com.sdsoft.motoactv_export.WebActivity.java

public boolean promptforWifi() {
    if (!isOnline(false)) {
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.getWifiState() != 3) {
            new AlertDialog.Builder(this).setTitle("Enable WiFi.")
                    .setMessage("Internet connection needed, would you like to enable WiFi?")
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                            wifiManager.setWifiEnabled(true);
                            //UpdateUtil.EnableWifi(getBaseContext());
                        }//ww  w .j  a va 2s . c  om
                    }).setNegativeButton(android.R.string.no, null).show();
        }
    }
    return true;
}

From source file:com.jesjimher.bicipalma.MesProperesActivity.java

/** Called when the activity is first created. */
@Override/*ww w .j  av  a2  s. co  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mesproperes);
    this.prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Si s'ha d'activar el wifi en inici, fer-ho
    WifiManager wm = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    // Guardar el estado actual para restaurarlo al salir
    this.estatWifi = wm.isWifiEnabled();
    if (prefs.getBoolean("activarWifiPref", false))
        wm.setWifiEnabled(true);

    // Cargamos la versin cacheada de las estaciones
    leerCacheEstaciones();

    actualizarListado();

    // Iniciamos la descarga de las estaciones y su estado desde la web (en un thread aparte)
    descargaEstaciones = new RecuperarEstacionesTask(this);
    descargaEstaciones.execute();

    // Inicialmente se busca por red (ms rpido)
    //       dBuscaUbic=ProgressDialog.show(c, "",getString(R.string.buscandoubica),true,true);
    //        Toast.makeText(getApplicationContext(), "Activando", Toast.LENGTH_SHORT).show();
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    providerCoarse = locationManager.getBestProvider(criteria, true);

    if (providerCoarse == null) {
        Toast.makeText(getApplicationContext(), "No hay forma de posicionarse", Toast.LENGTH_SHORT).show();
        return;
    }
    locationManager.requestLocationUpdates(providerCoarse, 10, 0, (LocationListener) this);

    // Usar ltima ubicacin conocida de red para empezar y recibir futuras actualizaciones
    lBest = locationManager.getLastKnownLocation(providerCoarse);

    // Guardar el inicio de bsqueda de ubicacin para no pasarse de tiempo
    //tIni=new Date().getTime();
    tIni = System.currentTimeMillis();

    // Crear listeners para mostrar estacin en mapa, o abrir men con clic largo
    ListView lv = (ListView) findViewById(R.id.listado);
    lv.setOnItemClickListener((OnItemClickListener) this);
    lv.setOnItemLongClickListener((OnItemLongClickListener) this);
}

From source file:org.openbmap.activities.StartscreenActivity.java

/**
 * Toggles wifi enabled (to trigger reconnect)
 *///from w w  w.j a  va  2  s .  c o  m
private void repairWifiConnection() {
    Log.i(TAG, "Reparing wifi connection");
    final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(false);
    wifiManager.setWifiEnabled(true);
}

From source file:com.yoval.community.chatapp.DistanceActivity.java

private void showWifiRequest() {

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    final WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    // set title//from ww w .  j  av a  2  s .co m
    alertDialogBuilder.setTitle("Wifi Settings");

    // set dialog message
    alertDialogBuilder.setMessage("Do you want to enable WIFI ?").setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //enable wifi
                    wifiMan.setWifiEnabled(true);
                }
            }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //disable wifi
                    //wifiMan.setWifiEnabled(false);
                    finish();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}

From source file:edu.cmu.mpcs.dashboard.TagViewer.java

private String wifiSetting(String settingString) {
    /*//from  w  w  w  . j  a  va2  s  .co m
     * Enable/Disable wifi
     */
    if (settingString.contains("wifi")) {
        WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        if (settingString.contains("wifi:On")) {
            wifiManager.setWifiEnabled(true);
            return ("Wifi turned On\n");
        } else {
            wifiManager.setWifiEnabled(false);
            return ("Wifi turned Off\n");
        }
    }
    return ("");

}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Enable/Disable the Wifi adapter", example = "")
@APIParam(params = { "boolean" })
public void enableWifi(boolean enabled) {
    WifiManager wifiManager = (WifiManager) a.get().getSystemService(Context.WIFI_SERVICE);
    wifiManager.setWifiEnabled(enabled);
}