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

Rah*_*dia 0 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 ;  

}
Run Code Online (Sandbox Code Playgroud)

我在点击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
 }
Run Code Online (Sandbox Code Playgroud)

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

use*_*305 7

使用AsyncTask概念,在Android中称为无痛线程.

  1. 把你的send()方法放在Async中 doInBackGround()
  2. 在onPreExecute上启动进度对话框
  3. 并且对此不以为然onPostExecute().