Created
March 27, 2017 06:21
-
-
Save laudarch/425ea492463cfd19bb66bd7bd055c303 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 laudarch.utils; | |
import android.content.Context; | |
import android.net.ConnectivityManager; | |
import android.net.NetworkInfo; | |
import java.io.IOException; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
/** | |
* Created by laudarch on 8/24/16. | |
*/ | |
public class NetConnectedUtils { | |
/** | |
* | |
* @param context | |
* @return true ; false | |
*/ | |
public static boolean isNetConnected(Context context) { | |
boolean ret = false; | |
ConnectivityManager connectivityManager | |
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |
// connectivityManager.getActiveNetwork(); | |
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); | |
if (networkInfo == null) { | |
return ret; | |
} | |
ret = networkInfo.isAvailable() & networkInfo.isConnected(); | |
return ret; | |
} | |
/** | |
* | |
* @param context | |
* @return false ; true | |
*/ | |
public static boolean isPhoneNetConnected(Context context) { | |
int typeMobile = ConnectivityManager.TYPE_MOBILE; | |
return isNetworkConnected(context, typeMobile); | |
} | |
/** | |
* | |
* @param context | |
* @return false ; true | |
*/ | |
public static boolean isWifiNetConnected(Context context) { | |
int typeMobile = ConnectivityManager.TYPE_WIFI; | |
return isNetworkConnected(context, typeMobile); | |
} | |
/** | |
* | |
* @param context | |
* @param typeMobile | |
* @return true ; false | |
*/ | |
private static boolean isNetworkConnected(Context context, int typeMobile) { | |
boolean ret = false; | |
if (!isNetConnected(context)) { | |
return ret; | |
} | |
ConnectivityManager connectManger = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo networkInfo = connectManger.getNetworkInfo(typeMobile); | |
if (networkInfo == null) { | |
return ret; | |
} | |
ret = networkInfo.isAvailable() & networkInfo.isConnected(); | |
return ret; | |
} | |
public static boolean hasActiveInternetConnection(Context context) { | |
if (isNetConnected(context)) { | |
try { | |
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://github.com").openConnection()); | |
urlc.setRequestProperty("User-Agent", "UA-laudarch"); | |
urlc.setRequestProperty("Connection", "close"); | |
urlc.setConnectTimeout(1500); | |
urlc.connect(); | |
return (urlc.getResponseCode() == 200); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
return false; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment