android学习笔记之检查网络状态和判断URL是否是有效

//检查网络连接状态,Monitor network connections (Wi-Vi, GPRS, UMTS, etc.)
public static boolean checkNetWorkStatus(Context context){
boolean result;
ConnectivityManager cm=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if ( netinfo !=null && netinfo.isConnected() ) {
result=true;
Log.i(TAG, "The net was connected" );
}else{
result=false;
Log.i(TAG, "The net was bad!");
}
return result;
}

public static boolean checkURL(String url){
boolean value=false;
try {
HttpURLConnection conn=(HttpURLConnection)new URL(url).openConnection();
int code=conn.getResponseCode();
System.out.println(">>>>>>>>>>>>>>>> "+code+" <<<<<<<<<<<<<<<<<<");
if(code!=200){
value=false;
}else{
value=true;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}

你可能感兴趣的:(Android)