Created
June 28, 2021 19:39
-
-
Save behroozAlborzi/35a58b41ce18375896cf05df957135f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
networkUtils class add