开发者

Show ProgressDialog while uithread sleeps?

I want to show ProgressDialog while uithread sleeps so that until the data from the server is retrive开发者_运维技巧d my activity will not be shown. How can I do this?


You can use Thread, AsyncTask, or Service to load your data in the background, and with a Handler implementation control your ProgressDialog.

The example in this post shows how to use a thread for a login request, and in the meantime show the progress dialog.

Using AsyncTask is a lot easier and clearer:

private static final int WAIT = 11;
private final class MyTask extends AsyncTask<Void, Void, Void>
{
    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        // Show up the dialog with id=WAIT [11]
        showDialog(WAIT);
        // other actions that must be performed in the UI thread
        // before the background works starts
    }

    @Override
    protected Void doInBackground(Void... params)
    {
        // perform the background work
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {
        super.onPostExecute(result);
        // Remove the dialog with id=WAIT [11]
        removeDialog(WAIT);
        // other actions that must be performed in the UI thread
        // after the background works finished
    }
}

[...]

final MyTask task = new MyTask();
task.execute(null);

Since AsyncTask is a generic type, you can specify the parameter types for your preference, so it is very handy for transferring data from the ui thread to a background thread and back.

Your dialog part is just a few lines inside your activity:

private ProgressDialog dialog;

@Override
protected Dialog onCreateDialog(int id)
{
    switch (id)
    {
        case WAIT:
        {
            dialog = new ProgressDialog(this);
            dialog.setMessage("Loading...");
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            return dialog;
        }
    }
    return null;
}


This task is commonly solved with AsyncTask bounded with progress dialog. See this article.


Move your Network Process code into a Thread and get a ProgressDialog. Start your network process by calling .start(); and then ProgressDialog.show(); when you have done in network process, stop the ProgressDialog through a Handler from Thread.run().


you can try this code for progress dialoge in ur thread

ProgressDialoge pd = ProgressDialog.show(this, "Please wait...", "Retrieving data.", true,false);

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜