Skip to content

Instantly share code, notes, and snippets.

@behroozAlborzi
Created June 28, 2021 19:39
Show Gist options
  • Save behroozAlborzi/35a58b41ce18375896cf05df957135f5 to your computer and use it in GitHub Desktop.
Save behroozAlborzi/35a58b41ce18375896cf05df957135f5 to your computer and use it in GitHub Desktop.
package com.behroozalborzi.brodcastreceiver_contextregister;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetworkUtils {
private final static String TAG = NetworkUtils.class.getName();
public static boolean hasInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) new URL("http://clients3.google.com/generate_204").openConnection();
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return urlc.getResponseCode() == 204;
} catch (IOException e) {
Log.e(TAG, "Error checking internet connection", e);
}
} else {
Log.d(TAG, "No network available!");
}
return false;
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnected();
}
}
@behroozAlborzi
Copy link
Author

networkUtils class add

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