android檢查網絡連接狀態 – Android移動開發技術文章_手機開發 Android移動開發教學課程

//檢查網絡連接狀態,Monitor network connections (Wi-Vi, GPRS, UMTS, etc.)
 public static boolean checkNetWorkStatus(Context context){
  boolean result;
  ConnectivityManage 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;
  }
  還要檢查 URL 是否有效   
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;
 }

 作者“AndroidPlayer”

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。