Daily#11. Establishing Wi-Fi Connection using WifiNetworkSpecifier and WifiNetworkSuggestion
Welcome back to our daily tech series! Today, we're diving into how to connect to a Wi-Fi network programmatically in Android using WifiNetworkSpecifier and WifiNetworkSuggestion APIs.
WifiNetworkSpecifier
WifiNetworkSpecifier is a part of the Android 10 (API level 29) addition to the Wi-Fi API. It allows applications to force Wi-Fi connections with specific networks programmatically. However, please note that the system will limit the number of outstanding requests to 100 per app. If this limit is exceeded, an exception will be thrown.
Here's a simple example of how to use it:
WifiNetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
.setSsidPattern(new PatternMatcher("test", PatternMatcher.PATTERN_PREFIX))
.setWpa2Passphrase("test1234")
.build();
NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(specifier)
.build();
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCallback networkCallback = new NetworkCallback() {
// override necessary methods here
};
connectivityManager.requestNetwork(request, networkCallback);
Remember to unregister the callback when you're done:
connectivityManager.unregisterNetworkCallback(networkCallback);
WifiNetworkSuggestion
WifiNetworkSuggestion API, introduced in Android 10 (API level 29), allows an app to suggest networks for the device to connect to. However, the final decision on whether to switch to the suggested network is made by the system UI.
Here's how to use WifiNetworkSuggestion:
WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
.setSsid("test")
.setWpa2Passphrase("test1234")
.build();
WifiManager wifiManager = (WifiManager)
context.getSystemService(Context.WIFI_SERVICE);
int status = wifiManager.addNetworkSuggestions(Collections.singletonList(suggestion));
if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
// handle failure, e.g., log the error or inform the user
}
The system remembers network suggestions across reboots. When your app is uninstalled, all its suggestions are removed.
This is a brief introduction to these two APIs, but there's more to explore. Check out the official Android documentation for more details and keep experimenting!
https://developer.android.com/reference/android/net/wifi/WifiNetworkSpecifier
https://developer.android.com/reference/android/net/wifi/WifiNetworkSuggestion
Comments
Post a Comment