Skip to content

Instantly share code, notes, and snippets.

@andatta
Created November 21, 2020 07:05
Show Gist options
  • Save andatta/f3063fbbd74104629f8a2d07547690be to your computer and use it in GitHub Desktop.
Save andatta/f3063fbbd74104629f8a2d07547690be to your computer and use it in GitHub Desktop.
New WiFi APIs on Android 10
public void connect(String ssid, String password) {
NetworkSpecifier networkSpecifier = new WifiNetworkSpecifier.Builder()
.setSsid(ssid)
.setWpa2Passphrase(password)
.setIsHiddenSsid(true) //specify if the network does not broadcast itself and OS must perform a forced scan in order to connect
.build();
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(networkSpecifier)
.build();
mConnectivityManager.requestNetwork(networkRequest, mNetworkCallback);
}
public void disconnectFromNetwork(){
//Unregistering network callback instance supplied to requestNetwork call disconnects phone from the connected network
mConnectivityManager.unregisterNetworkCallback(mNetworkCallback);
}
private ConnectivityManager.NetworkCallback mNetworkCallback = new ConnectivityManager.NetworkCallback(){
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
//phone is connected to wifi network
}
@Override
public void onLosing(@NonNull Network network, int maxMsToLive) {
super.onLosing(network, maxMsToLive);
//phone is about to lose connection to network
}
@Override
public void onLost(@NonNull Network network) {
super.onLost(network);
//phone lost connection to network
}
@Override
public void onUnavailable() {
super.onUnavailable();
//user cancelled wifi connection
}
};
@AhmedNawaz01
Copy link

internet is not working on connected wifi using this code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment