如果AsyncTask需要时间,则显示ProgressDialog

时间:2012-06-08 10:04:02

标签: android android-asynctask progressdialog

我有一个像这样的AsyncTask:

private class RetrieveDataAsyncTask extends AsyncTask<Void, Void, Boolean> {

    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
            progressDialog = ProgressDialog.show(getSherlockActivity(), "In progress", "Loading"); 
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            currentScreen.retrieveData();
            return true;
        } catch (IOException ex) {
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean result) {
            progressDialog.dismiss();
            if (result) {
                currentScreen.retrieveDataFinished();
            } else {
                showExceptionOccurred();
            }
    }

现在当AsyncTask花费不到500毫秒时,我不想显示ProgressDialog,它只会导致闪烁并且可能会让人烦恼。 我想要的是等待500ms,检查AsyncTask是否仍然忙,如果是,则显示ProgressDialog。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

尝试这样做:

final Handler handler = new Handler();


private class RetrieveDataAsyncTask extends AsyncTask<Void, Void, Boolean> {

    ProgressDialog progressDialog = null;

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected Boolean doInBackground(Void... params) {
        handler.postDelayed(pdRunnable, 500);

        try {
            currentScreen.retrieveData();
            return true;
        } catch (IOException ex) {
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean result) {
            handler.removeCallbacks(pdRunnable);
            if(progressDialog != null)
                 progressDialog.dismiss();

            if (result) {
                currentScreen.retrieveDataFinished();
            } else {
                showExceptionOccurred();
            }
    }

    final Runnable pdRunnable = new Runnable() {
            @Override
            public void run() {
                progressDialog = ProgressDialog.show(getSherlockActivity(),
                "In progress", "Loading");
            }
    };

}

答案 1 :(得分:0)

@Stan的建议似乎是正确的:

onPreExecute()中尝试以下一行:

@Override
protected void onPreExecute() {
    Timer t =new Timer();
    t.schedule(new TimerTask() {

        @Override
        public void run() {
        progressDialog = ProgressDialog.show(getSherlockActivity(), "In progress", "Loading"); 
        }
    }, 500);

}