简体   繁体   中英

Why do I need a Looper in my AsyncTask?

I want to use AsyncTask for update my db4o with a server. In the doInBackground method , I connect to the server, update the db4o, and schedule a pendingintents. Not modify UI or show any toast.

Initially, I had the following error:

Can't create handler inside thread that has not called Looper.prepare() 

After adding the Looper.prepare(), works fine, but only for five updates (AsyncTask). I've read this topic: AsyncTask threads never die (Android) , and I don't now that fails. When I throw the sixth update, the app crashes:

FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
Caused by: java.lang.RuntimeException: Only one Looper may be created per thread
at android.os.Looper.prepare(Looper.java:74)
(...)

五个AsyncTask

I've read in the documentation that I need the Looper.loop(), but whith this, the app crashes..

Example:

protected Integer doInBackground(Void... params) {
    Looper.prepare();

        update = new Update();
        update.checknewObjects();
        update.deleteOldObjects();
        update.updateObjects();
        Looper.loop();
}

Why do I need Looper? Why the app crashes after five updates? Where can I schedule Looper.loop()?

Thanks in advance!

If you want to schedule tasks you should use Timer & TimerTask, from what I understand I think they should fit better to your needs. http://developer.android.com/reference/java/util/Timer.html

If you want to use AsyncTask so use it, you shouldn't mix it with Lopper ...

protected Integer doInBackground(Void... params) {}

already working on background thread and there is no reason to call Lopper, for what?

If your application need to do some kind of long computation so AsyncTask is very good tool for it because offers methods which working on UI Thread and allow to update UI with some progress of work because every User that will use your application should know that application "doing something" (when it takes more than 2-5 seconds).

Also it's generic and that provide some benefits.

If you do not need to update UI just use for example Handler .

在异步任务中,您不能在后台函数中使用循环。

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