简体   繁体   中英

AsyncTask - update progress while ONE long operation completes

I'm working on an android app that has a lengthy process that I'd like to report the progress on.

I don't have the source to the process, so I can't get the process itself to report on it's percent complete. I have to wrap it somehow. I also need the process to run in the background.

To me, this seemed like a good case for an AsyncTask, but since I have one lengthy process, I can only report progress at the start, and end of the task.

What's the best way in Android to write this, so I can report progress back to the UI while the lengthy process (for which I have no source) is running?

I tried using an AsyncTask with a Handler in it, but that didn't seem to work (failed with: "java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()")

EDIT: Note, I'm calling "publishProgress" at the start and end of my long process. I need to figure out how to call it while my one huge process is running.

EDIT 2: The UI kills my process if I don't report back, so I have to report back while it's running...

This is a solution as hackish as it gets.

public class LongAction {
    public AtomicBoolean finished = new AtomicBoolean();
    private final Handler h;      

    /* attributes you need */

    public LongAction(Handler h /* parameters you need to initialice attibutes */) {
        this.h = h;
        // Initialization
    }

    public void doLongTask() {
        finished.set(false);
        new Runnable() {
            @Override
            public void run() {
                // your long task
                finished.set(true);
            }
        }.run();
        new Runnable() {
            @Override
            public void run() {
                while (!finished.get()) {
                }
                Message m = Message.obtain();
                m.what = 0;
                m.arg1 = 50;
                h.sendMessage(m);
            }
        }.run();
    }
}

I'm not sure you can do anything else since you don't have control over the long running task. The basic AsyncTask looks enough for what you want.

You can display text that tells the user the operation is on-going (or start some animation) in AsyncTask.doInBackground(). And you then display the completion message (or stop the animation) in AsyncTask.onPostExecute().

I don't quite see what else you can do. I don't think AsyncTask.onProgress() is useful for your case.

Not directly related: You might also want to disable some functionality in the Activity when the operation is on-going. You also must be careful on what you want to do about the lifecycle (if the Activity is killed while the process is on-going).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM