如何在android中连接服务器时显示进度条?

时间:2012-03-22 05:43:47

标签: android progress-bar

这是我连接到服务器并在MyUtilitiesActivity中获取响应的方法。

 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
 }

我在哪里显示进度条?内部onclick一个按钮或内部send()方法?如何显示?请帮我。

2 个答案:

答案 0 :(得分:7)

在Android中使用AsyncTask概念,该概念称为Painless Threading

  1. 将您的send()方法放入Async的doInBackGround()
  2. 在onPreExecute上启动进度对话框
  3. 并驳回onPostExecute()

答案 1 :(得分:0)

您可以像这样添加进度条:

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

当您的长时间操作消失时,您应该致电dialog.dismiss();