Create a simple wifi scanning application for Android phones

Tram Ho

The WiFi API provided with the SDK is really interesting. In this tutorial, we will learn and develop a simple WiFi scanning application with Android Studio!

Please note that I will not go into managing the permissions in this tutorial because I only focus on the WiFi API. You can refer to the video in this link to understand how to manage Permission:

Step 1: Add Permisson

The first step is to add the correct permissions in the application’s Android Manifest file. We will need to add permission ACCESS_WIFI_STATE. It will allow your application to access information about WiFi networks.

Step 2: Create the main interface for the application

The next step is to create the interface for our WiFi scanning application. It will be designed simply with a ListView and a Button. In particular, ListView will display WiFi networks detected by our device. When the Button is clicked, the application will allow the user to start the WiFi scanning process.

Step 3: Write code for MainActivity

Now, we will write code for MainActivity. On the Android SDK, the WiFi API is accessed through a System Service named WifiManager. We need to check if WiFi is enabled on the device. If not, we need to enable it by calling the setWifiEnables method with the parameter passed as true:

Then we can start scanning for WiFi networks around us. We need to use a dedicated BroadcastReceiver: WifiManager.SCAN_RESULTS_AVAILABLE_ACTION

Upon successful registration of BroadcastReceiver, we can start scanning for WiFi networks by calling the startScan method of WifiManager Service:

When the scan is finished, in the BroadcastReceiver’s onReceive function, we need to call the WifiManager Service’s getScanResults method to get the result. And do not forget to unsubscribe BroadcastReceiver to save battery for the device.

Our main activity will look like this:

Run the app

Click the scan button and see the results!

Chia sẻ bài viết ngay

Nguồn bài viết : Viblo