Connecting to Wi-Fi Using WifiNetworkSpecifier in Android
In Android applications, connecting to Wi-Fi is a common requirement. Android 8.0 introduced the WifiNetworkSpecifier class, making it easier and more flexible to connect to a specific Wi-Fi network via code. This article explains how to use the WifiNetworkSpecifier class to connect to a Wi-Fi network and provides relevant code examples.
Overview of WifiNetworkSpecifier
The WifiNetworkSpecifier class was introduced in Android 8.0 (API level 26) to specify the conditions required to connect to a particular Wi-Fi network. With WifiNetworkSpecifier, you can define details such as the Wi-Fi SSID, BSSID, and security settings to achieve connection to a specific Wi-Fi network.
Using WifiNetworkSpecifier
To use WifiNetworkSpecifier for connecting to a Wi-Fi network, create a WifiNetworkSpecifier object and pass it to a WifiNetworkSuggestion object. Finally, add the network suggestion using the addNetworkSuggestions() method of the WifiManager.
Here is a simple example demonstrating how to connect to a Wi-Fi network named "MyWifiNetwork":
WifiNetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
.setSsid("MyWifiNetwork")
.build();
WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
.setPriority(1)
.setNetworkSpecifier(specifier)
.build();
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetworkSuggestions(Collections.singletonList(suggestion), null);
After adding the network suggestion, you must request user authorization for the app to automatically connect to the specified Wi-Fi network. You can request this authorization by calling startActivityForResult():
Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivityForResult(intent, REQUEST_CODE);
Relationship Diagram
Below is an example relationship diagram for using WifiNetworkSpecifier to connect to Wi-Fi:
erDiagram
WIFI_NETWORK_SPECIFIER ||--o WIFI_NETWORK_SUGGESTION : 1
WIFI_NETWORK_SUGGESTION ||--o WIFI_MANAGER : 1
Sequnece Diagram
Here is an example sequence diagram for using WifiNetworkSpecifier to connect to Wi-Fi: