1

我有一个这样的 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,它只会导致闪烁并且可能会令人讨厌。我想要的是等待 500 毫秒,检查 AsyncTask 是否仍然忙,如果是,则显示 ProgressDialog。

我怎样才能做到这一点?

4

2 回答 2

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");
            }
    };

}
于 2012-06-08T10:22:49.317 回答
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);

}
于 2012-06-08T10:31:58.540 回答