android determines whether the network is available and whether the connected network can access the Internet
- 2021-08-17 00:58:56
- OfStack
Network state acquisition
Upload and download need to check the network status of the current mobile phone first, and need to get ConnectionManager
/**
* Determine whether there is a current network connection , However, if the connected network is unable to access the Internet, it will also return true
* @param mContext
* @return
*/
public static boolean isNetConnection(Context mContext) {
if (mContext!=null){
ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
boolean connected = networkInfo.isConnected();
if (networkInfo!=null&&connected){
if (networkInfo.getState()== NetworkInfo.State.CONNECTED){
return true;
}else{
return false;
}
}
}
return false;
}
Can the network access the Internet normally
When there is a network connection, if you want to check whether the currently connected network can surf the Internet, you need to open the website address to make a judgment
/**
* Open this method in a sub-thread to detect whether the current network can open a web page
* true Yes, you can surf the Internet. false You can't surf the Internet
*
*/
public static boolean isOnline(){
URL url;
try {
url = new URL("https://www.baidu.com");
InputStream stream = url.openStream();
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}