migrate hasInternetConnection() to new api

Thank you to @ailicic for figuring out the new API.

Closes #4050
This commit is contained in:
Daniel Gultsch 2021-03-29 10:58:11 +02:00
parent 30c9e7399e
commit 0fc191d004

View file

@ -20,6 +20,8 @@ import android.database.ContentObserver;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.media.AudioManager; import android.media.AudioManager;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.net.Uri; import android.net.Uri;
import android.os.Binder; import android.os.Binder;
@ -1075,11 +1077,20 @@ public class XmppConnectionService extends Service {
} }
public boolean hasInternetConnection() { public boolean hasInternetConnection() {
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); final ConnectivityManager cm = ContextCompat.getSystemService(this, ConnectivityManager.class);
if (cm == null) {
return false;
}
try { try {
final NetworkInfo activeNetwork = cm == null ? null : cm.getActiveNetworkInfo(); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
return activeNetwork != null && (activeNetwork.isConnected() || activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET); final Network activeNetwork = cm.getActiveNetwork();
} catch (RuntimeException e) { final NetworkCapabilities capabilities = activeNetwork == null ? null : cm.getNetworkCapabilities(activeNetwork);
return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
} else {
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && (networkInfo.isConnected() || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET);
}
} catch (final RuntimeException e) {
Log.d(Config.LOGTAG, "unable to check for internet connection", e); Log.d(Config.LOGTAG, "unable to check for internet connection", e);
return true; //if internet connection can not be checked it is probably best to just try return true; //if internet connection can not be checked it is probably best to just try
} }