2012-03-22 70 views
0

這裏是我的方法連接到服務器,並在MyUtilitiesActivity中獲取響應。如何在android中連接服務器時顯示進度條?

private static response = ""; 
public static String send(final Activity act, final String url, final String keys[], final String values[]) 
{ 
    try{ 
     HttpParams httpParameters = new BasicHttpParams(); 
     // Set the timeout in milliseconds until a connection is established. 

     HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); 
     // Set the default socket timeout (SO_TIMEOUT) 
     // in milliseconds which is the timeout for waiting for data. 

     HttpConnectionParams.setSoTimeout(httpParameters, 5000); 

     HttpClient httpclient = new DefaultHttpClient(httpParameters); 
     if(keys == null && values == null) 
     { 

      HttpGet get = new HttpGet(url); 
      // Execute HTTP Get Request 
      response = httpclient.execute(get, new BasicResponseHandler()).trim(); 

     } 
     else if(keys != null && values != null && keys.length == values.length) 
     { 
      // Add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

      for (int i = 0; i < values.length; i++) 
      { 
       nameValuePairs.add(new BasicNameValuePair(keys[i], values[i])); 
      } 

      HttpPost post = new HttpPost(url); 
      post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      response = httpclient.execute(post, new BasicResponseHandler()).trim(); 

     } 

    } 
    catch (Exception e) 
    { 
     response = e + ""; 
     e.printStackTrace(); 
    } 
    return response ; 

} 

而且我只需點擊MyTestActivity中的按鈕即可調用上述方法。

public onClick(View v) 
{ 
String response = MyUtilitiesActivity.send(MyTestActivity.this, "http://www.google.com", null, null); 

//the code to be execute after getting the response from server 
} 

我在哪裏顯示進度條?在按鈕的內部點擊或裏面的send()方法?如何顯示它?請幫幫我。

回答

7

使用AsyncTask概念在Android中被稱爲Painless Threading

  1. 把你在異步的doInBackGround()
  2. 開始進度對話框send()方法在onPreExecute
  3. onPostExecute()
  4. 和dismisss。
+0

+1也從​​我的身邊... – 2012-03-22 05:51:31

+0

把你送()方法在Async的doInBackGround()中:I'an無法做到這一點。我應該在doInBG()中調用send方法,還是應該將代碼放在doInBG()中。你能否詳細解釋一下。謝謝。 – 2012-03-22 06:40:05

+0

是的,你可以把你的發送方法的代碼放在doInBack()中也沒有問題。 – user370305 2012-03-22 06:41:32

0

您可以添加進度條是這樣的:

ProgressDialog dialog = ProgressDialog.show(YourActivity.this, "", 
            getString(R.string.Loading), true); 

,當你長時間操作已經一去不復返了,你應該叫dialog.dismiss();