开发者

How do I show a ProgressDialog while an HttpRequest executes on Android?

I have the following code, which I got by looking at the sample on the Android developer documentation. However, it doesn't actually show the dialog. If I take the dismiss() cal开发者_运维百科l out, it displays the dialog AFTER the call to doLogin() finishes, and then never goes away. I don't need it to be fancy, I just want to display something while the request executes.

    ProgressDialog dialog = ProgressDialog.show(GameList.this, "", 
            "Connecting. Please wait...", true);

    int r = app.doLogin();

    dialog.dismiss();

doLogin() is a method that makes an HTTP request against the server and it returns a status code to indicate if the request was successful.


It's never a good idea to run HTTP requests on a main thread. Spin a worker thread, use a Handler to dismiss the dialog back in the UI thread. Something like this:

ProgressDialog dialog = ProgressDialog.show(GameList.this, "",              "Connecting. Please wait...", true); 

final Handler h = new Handler(); //will execute on the main thread

new Thread(new Runnable(){
public void run()
{
    app.doLogin();
    h.post(new Runnable()
    {
        public void run()
        {
              dialog.dismiss();
        }
    }
}
}).start();

The three-level nesting is not necessary, of course. Just trying to illustrate the technique here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜