Last active
May 29, 2018 00:01
-
-
Save amilcar-sr/773f3f2bf087edeed714bc1ab6e4c056 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.yourpackage.example; | |
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