1

I am practicing the working of the AsyncTask and with that purpose I wanted to use the onProgressUpdate function. Currently in my program I have UI that lets the user choose an input (which would be show in a TextView after the AsyncTask is finished) and a timer (determines Thread.sleep() time in the AsyncTask)

What I want to do is ... if the user selects a time of 5. Then in every passing second I would like to send a notification to the UI (where a progress dialog is called) ... indicating progress of 1 of 5 ... 2 of 5 ... 3 of 5.

Here's the progress that I have made so far:

public class ViewFiller extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... input) {
        // TODO Auto-generated method stub
        try {
            int time;
            if (input[1].equalsIgnoreCase("")) {
                time = 0;
            } else {
                time = Integer.parseInt(input[1]) * 1000;
                for (int i = 1; i <= time / 1000; i++) {
                    publishProgress(i, time);
                }
                Thread.sleep(time);
            }

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return input[0];
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        execute.setText("Execute");
        progress.dismiss();
        tvInput.setText(result);
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        execute.setText("Running...");
        displayProgress("Updating field ... ");
        // Start the progress dialog
        progress.show();

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
        progress.setMessage("Updating field ... " + values[0] + " of "
                + values[1] / 1000);
    }

}

The current implementation only gives me 5 of 5 directly. Can anyone suggest me a solution ?

4

1 回答 1

2

因为它通过你的loop速度比你看到的要快

for (int i = 1; i <= time / 1000; i++) {
                publishProgress(i, time);

你不需要loop那里。无论sleep多长时间,然后显示您的进度sleep()publishProgress()loop. 就像是

try {
       int time = 0;
       for (int i = 1; i <= time / 1000; i++) {

        if (input[1].equalsIgnoreCase("")) {
            time = 0;
        } else {
            time = Integer.parseInt(input[1]) * 1000;
                publishProgress(time);
            }
            Thread.sleep(time);
        }

虽然,我不确定input实际包含什么,但你可能想要input[i]. 否则它看起来总是一样的。

另外,我认为CountDownTimer会对此有好处。

于 2013-11-12T02:11:32.213 回答