Android allows applications to access to view the access the state of the wireless connections at very low level. Application can access almost all the information of a wifi connection.
The information that an application can access includes connected network’s link speed, IP address, negotiation state, other networks information. Applications can also scan, add, save, terminate and initiate Wi-Fi connections.
Android provides WifiManager API to manage all aspects of WIFI connectivity. We can instantiate this class by calling getSystemService method. Its syntax is given below −
1 2 |
WifiManager wifiManager; wifiManager= (WifiManager) getSystemService(Context.WIFI_SERVICE); |
In order to scan a list of wireless networks, you also need to register your BroadcastReceiver. It can be registered using registerReceiver method with argument of your receiver class object. Its syntax is given below −
1 2 3 4 5 6 |
class WifiScanReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { } } WifiScanReceiver wifiReciever = new WifiScanReceiver(); registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); |
The wifi scan can be start by calling the startScan method of the WifiManager class. This method returns a list of ScanResult objects. You can access any object by calling the get() of list. Its syntax is given below −
1 2 |
List<ScanResult> wifiScanList = wifiManager.getScanResults(); String scanResult= wifiScanList.get(0).toString(); |
Apart from just Scanning, you can have more control over your WIFI by using the methods defined in WifiManager class. They are listed as follows −
Method | Description |
---|---|
addNetwork(WifiConfiguration config) | This method add a new network description to the set of configured networks. |
createWifiLock(String tag) | This method creates a new WifiLock. |
disconnect() | This method disassociate from the currently active access point. |
enableNetwork(int netId, boolean disableOthers) | This method allow a previously configured network to be associated with. |
getWifiState() | This method gets the Wi-Fi enabled state. |
isWifiEnabled() | This method return whether Wi-Fi is enabled or disabled. |
setWifiEnabled(boolean enabled) | This method enable or disable Wi-Fi. |
updateNetwork(WifiConfiguration config) | This method update the network description of an existing configured network. |
In this tutorial, we are going to learn how to use WIFI by enabling and disabling it and listing scanned wifi’s in ListView.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Open res ⇒ values ⇒ strings.xml and add below string values. This are some strings that i am going to use in this tutorial.
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Wifi Demo</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="enable">Enable</string> <string name="disable">Disable</string> <string name="scan">Scan Wifi</string> </resources> |
3. To work on WiFi we need to set certain permission in Manifest file so open manifest file and add this lines to it.
1 2 3 |
<!-- Permissions required to work over wifi --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.wifi_demo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <!-- Permissions required to work over wifi --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
4. Now, create a xml layout naming activity_main.xml for basic layout. This layout contains some buttons and one listview for displaying Wifi’s.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="5dp" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/enable" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/enable" /> <Button android:id="@+id/disable" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/disable" /> <Button android:id="@+id/scan_wifi" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/scan" /> </LinearLayout> <ListView android:id="@+id/show_scaned_wifi" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp" > </ListView> </LinearLayout> |
5. Now, come to your MainActivity.java and add the following code. In this code we used above discussed method to enable, disable wifi and list scanned wifi over ListView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
package com.wifi_demo; import java.util.List; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements OnClickListener { private static Button enable, disable, scan; private static ListView scannedWifi; private static WifiManager wifiManager;// Wifi Manager to manage wifi private static WifiReceiver receiverWifi; // Wifi broadcase receiver private static List<ScanResult> wifiList;// List to store scanned wifi's @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); setListeners(); } // Initialize all views private void init() { enable = (Button) findViewById(R.id.enable); disable = (Button) findViewById(R.id.disable); scan = (Button) findViewById(R.id.scan_wifi); scannedWifi = (ListView) findViewById(R.id.show_scaned_wifi); wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); // Get // wifi // service // to // use // Wifi receiverWifi = new WifiReceiver();// Broadcast receiver for wifi } // Setting click listener over buttons private void setListeners() { enable.setOnClickListener(this); disable.setOnClickListener(this); scan.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.enable: // Check if wifi is enabled or disabled and do according to it if (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true);// enable wifi Toast.makeText(MainActivity.this, "WIFI enabled.", Toast.LENGTH_SHORT).show(); } else Toast.makeText(MainActivity.this, "WIFI already enabled.", Toast.LENGTH_SHORT).show(); break; case R.id.disable: // If wifi is enabled then disable it if (wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(false);// disable wifi Toast.makeText(MainActivity.this, "WIFI disabled.", Toast.LENGTH_SHORT).show(); } else Toast.makeText(MainActivity.this, "WIFI is not enabled.", Toast.LENGTH_SHORT).show(); break; case R.id.scan_wifi: // If wifi is enabled then scan wifi's if (wifiManager.isWifiEnabled()) { // Register broadcast receiver // Broacast receiver will automatically call when number of wifi // connections changed registerReceiver(receiverWifi, new IntentFilter( WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); wifiManager.startScan();// Start wifi scan } else Toast.makeText(MainActivity.this, "WIFI is not enabled.", Toast.LENGTH_SHORT).show(); break; } } @Override protected void onDestroy() { super.onDestroy(); // On destroy we have to unregister receiver try { unregisterReceiver(receiverWifi); } catch (Exception e) { e.printStackTrace(); } } // Broadcast receiver to scan new wifi class WifiReceiver extends BroadcastReceiver { // This method call when number of wifi connections changed and // disaplayed wifi connections over listview public void onReceive(Context c, Intent intent) { String action = intent.getAction();// Get sent action // If sent action is equal to scan results if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { wifiList = wifiManager.getScanResults();// get scanned results // in list if (wifiList.size() > 0) {// if size is greater then 0 then show // wifi connection over listview Toast.makeText( MainActivity.this, "Number of Wifi connections found : " + wifiList.size(), Toast.LENGTH_SHORT) .show(); // Toast to display no. of connections ArrayAdapter<ScanResult> adapter = new ArrayAdapter<ScanResult>( MainActivity.this, android.R.layout.simple_list_item_1, wifiList); scannedWifi.setAdapter(adapter);// Setting adapter over // listview adapter.notifyDataSetChanged();// Notify adapter } else { // If list size is 0 then show toast Toast.makeText(MainActivity.this, "No Wifi found.", Toast.LENGTH_SHORT).show(); } } } } } |
6. Finally, you are all done, run your app and you will get the output as shown in video.
Thanks.
Subscribe to us and get the latest news.