2011年3月19日 星期六

判斷網路是否有通2(採用)

判斷網路是否有通,第1篇判斷功能,無用. 原因是我家公司上網要另外輸入帳號,所以通了沒輸也是不能用. 所以直接判斷能否連到某網頁是我找到比較好的方法..

/* 測試手機是否具有連線能力 */
checkInternetConnection cic = new checkInternetConnection();
if(!cic.check("http://google.com%22,%22utf-8/"))
{
  Toast.makeText(this, "無法上網,請先開通..",Toast.LENGTH_LONG).show();
}

public class checkInternetConnection {
 public boolean check(String strURL, String strEncoding){  
  try{
    HttpURLConnection urlConnection= null;
       URL url = new URL(strURL);
       urlConnection=(HttpURLConnection)url.openConnection();
       urlConnection.setRequestMethod("GET");
       urlConnection.setDoOutput(true);
       urlConnection.setDoInput(true);
       urlConnection.setRequestProperty
       (
         "User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)"
       );
       
       urlConnection.setRequestProperty
       ("Content-type","text/html; charset="+strEncoding);     
       //預設五秒內要回應
       urlConnection.setConnectTimeout(5000);
       urlConnection.connect();
       if (urlConnection.getResponseCode() == 200)
       {
         return true;
       }
       else
       {
         return false;
       }
     }
     catch (Exception e)
     {
       e.printStackTrace();
       return false;
     }
 }
}

參考自Google Android SDK 開發範例大全2 (9-3)

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁