I am Trying to test network availability with callback.
I want to show toast notification when connection is not available. When I have access to the internet, onAvailable() works fine.
onAvailable() does not seem to work. Toast with message "No internet connection" does not show up.
I've read some info in the documentation about unAvailable(). Timeout value was mentioned. I am assuming onUnavailable() gets called after this timeout. However, I do not if it is related to the problem.
ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
Toast.makeText(MainActivity.this, "Request successful", Toast.LENGTH_LONG).show();
}
@Override
public void onUnavailable() {
super.onUnavailable();
Toast.makeText(MainActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
}
};
final ConnectivityManager connectivityManager
= (ConnectivityManager) MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager.registerNetworkCallback(new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build(), networkCallback);