Skip to content

Instantly share code, notes, and snippets.

@saeedsh92
Last active August 17, 2023 11:33
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saeedsh92/a205f2a4c5af4d0e4a1e708825a7db19 to your computer and use it in GitHub Desktop.
Save saeedsh92/a205f2a4c5af4d0e4a1e708825a7db19 to your computer and use it in GitHub Desktop.
Check internet connectivity
package com.sevenlearn.broadcastreceivertutorial;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.os.Build;
public class NetworkUtil {
public static boolean checkNetworkState(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null)
return false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network nw = connectivityManager.getActiveNetwork();
NetworkCapabilities activeNetworkInfo = connectivityManager.getNetworkCapabilities(nw);
if (activeNetworkInfo!=null && activeNetworkInfo.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && activeNetworkInfo.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else
return false;
} else {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null)
return networkInfo.isConnected();
else
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment