nilA
nilA

Reputation: 11

Android: How to launch WiFi through code

i want to make an simple app which detect the wifi networks and after selecting a network it launch(connect) to the selected network.

i have written code for detection phase but how could i connect to the selected network in onItemClick(). Please suggest the code.

Upvotes: 1

Views: 8194

Answers (3)

Praveenkumar
Praveenkumar

Reputation: 24506

Maybe you can do like with existing Answer's

WifiConfigurations will help you to do this.

Hope this helps you.

Upvotes: 0

Priebe
Priebe

Reputation: 4992

You can do this by using the WifiManager. Get the Wifi Service from the system, check if the wifi is turn on or off, then turn it on/off.

private WifiManager wifiManager;
@Override
public void onCreate(Bundle bund) {
  wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
  if(wifiManager.isWifiEnabled()){
    wifiManager.setWifiEnabled(false);
  }else{
    wifiManager.setWifiEnabled(true);
  }
}

Remember do add the permissions also

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

Upvotes: 6

Nimit
Nimit

Reputation: 1712

Android comes with a complete support for the WiFi connectivity. The main component is the system-provided WiFiManager. As usual, we obtain it via getSystemServices() call to the current context.

Once we have the WiFiManager, we can ask it for the current WIFi connection in form of WiFiInfo object. We can also ask for all the currently available networks via getConfiguredNetworks(). That gives us the list of WifiConfigurations.

In this example we are also registering a broadcast receiver to perform the scan for new networks

WiFiDemo.java

package com.example;

import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class WiFiDemo extends Activity implements OnClickListener {
    private static final String TAG = "WiFiDemo";
    WifiManager wifi;
    BroadcastReceiver receiver;

    TextView textStatus;
    Button buttonScan;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Setup UI
        textStatus = (TextView) findViewById(R.id.textStatus);
        buttonScan = (Button) findViewById(R.id.buttonScan);
        buttonScan.setOnClickListener(this);

        // Setup WiFi
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

        // Get WiFi status
        WifiInfo info = wifi.getConnectionInfo();
        textStatus.append("\n\nWiFi Status: " + info.toString());

        // List available networks
        List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
        for (WifiConfiguration config : configs) {
            textStatus.append("\n\n" + config.toString());
        }

        // Register Broadcast Receiver
        if (receiver == null)
            receiver = new WiFiScanReceiver(this);

        registerReceiver(receiver, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        Log.d(TAG, "onCreate()");
    }

    @Override
    public void onStop() {
        unregisterReceiver(receiver);
    }

    public void onClick(View view) {
        Toast.makeText(this, "On Click Clicked. Toast to that!!!",
                Toast.LENGTH_LONG).show();

        if (view.getId() == R.id.buttonScan) {
            Log.d(TAG, "onClick() wifi.startScan()");
            wifi.startScan();
        }
    }

}

WiFiScanReceiver.java

package com.example;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

public class WiFiScanReceiver extends BroadcastReceiver {
  private static final String TAG = "WiFiScanReceiver";
  WiFiDemo wifiDemo;

  public WiFiScanReceiver(WiFiDemo wifiDemo) {
    super();
    this.wifiDemo = wifiDemo;
  }

  @Override
  public void onReceive(Context c, Intent intent) {
    List<ScanResult> results = wifiDemo.wifi.getScanResults();
    ScanResult bestSignal = null;
    for (ScanResult result : results) {
      if (bestSignal == null
          || WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
        bestSignal = result;
    }

    String message = String.format("%s networks found. %s is the strongest.",
        results.size(), bestSignal.SSID);
    Toast.makeText(wifiDemo, message, Toast.LENGTH_LONG).show();

    Log.d(TAG, "onReceive() message: " + message);
  }

}

The layout file for this example is fairly simple. It has one TextView wrapped in a ScrollView for scrolling purposes.

/res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <Button android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:id="@+id/buttonScan"
    android:text="Scan"></Button>
  <ScrollView android:id="@+id/ScrollView01"
    android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TextView android:layout_width="fill_parent"
      android:layout_height="wrap_content" android:id="@+id/textStatus"
      android:text="WiFiDemo" />
  </ScrollView>

</LinearLayout>

For the AndroidManifest.xml file, just remember to add the permissions to use WiFi:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

Upvotes: 3

Related Questions