ConnectivityManager.getNetworkInfo()
is a deprecated method.
The right thing to do is to make a ConnectivityManager.NetworkCallback
To answer your question, checking whether you are connected to the internet via WiFi or Mobile Data:
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest request = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build();
connMgr.requestNetwork(request, new ConnectivityManager.NetworkCallback() {
// This callback is invoked when there is a valid Mobile Data or WiFi network
// but is later lost during the course of using the application.
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
}
// This callback is invoked when there is a valid Mobile Data or WiFi network
// that is ready for use
@Override
public void onLost(@NonNull Network network) {
super.onLost(network);
}
// This callback is invoked when there is no valid Mobile Data or WiFi network
// after a specific timeout has timed out.
@Override
public void onUnavailable() {
super.onUnavailable();
}
});
There are various other callbacks, but I believe for your use case these are the primary ones you would need.
Finally, the to add a specific timeout, that was mentioned in the onUnavailable
callback, you can use this Constructor for your ConnectivityManager.NetworkCallback
:
ConnectivityManager.NetworkCallback(int timeoutMs)
I really do hope this helps. See more information on the API here