[英]Two different AsyncTasks not getting started from a foregroundService
I have written a foreground service which in the onCreate method does this: 我已经编写了一个前台服务,该服务在onCreate方法中可以做到这一点:
public void onCreate(){
//........
startForeground(id,notification);
Task1=new Task(this);
task1.execute();
Task2=new Task(this);
Log.d("T2","Created");
task2.execute();
Log.d("T2","Executed");
}
Now what is happening is that above code is causing task1 to execute(which has a while(true) with sleep of 60 sec after each loop), but never lets task2 start its doInBackground(). 现在发生的是,上面的代码使task1执行(每个循环后有一个while(true),睡眠60秒的时间),但是决不允许task2启动其doInBackground()。
I am not sure whats wrong.As per the logcat, its clearly showing that the task2.execute() does get invoked.But why is the doInBackground() of second task is not getting started? 我不确定是怎么回事,根据logcat,它清楚地表明task2.execute()确实被调用了,但是为什么第二个任务的doInBackground()没有启动? I was initially planning to have two foreground services, but after reading a few SO posts, decided to have only one Service in foreground and let it have two different Asynctasks to do some continuous processing in background.
我最初计划有两个前台服务,但是在阅读了几篇SO文章之后,决定仅在前台有一个服务,并让它有两个不同的Asynctasks在后台进行一些连续处理。 Please help me in making this work!
请帮助我完成这项工作!
The default executor for AsyncTask
, starting from Honeycomb, is AsyncTask.SERIAL_EXECUTOR
, which means that only one task is executing at a given time. 从Honeycomb开始的
AsyncTask
的默认执行程序是AsyncTask.SERIAL_EXECUTOR
,这意味着在给定时间仅执行一个任务。
If you need parallelism, just use AsyncTask.THREAD_POOL_EXECUTOR
, ie 如果需要并行性,则只需使用
AsyncTask.THREAD_POOL_EXECUTOR
,即
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
instead of just 而不只是
task.execute(params);
See the Order of Execution section in the documentation for AsyncTask . 请参阅AsyncTask文档中 的“执行顺序”部分。
It`s simply because since from Android 3.0 AsyncTask-s work in a single background thread: 这仅仅是因为从Android 3.0开始,AsyncTask在单个后台线程中工作:
Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
从HONEYCOMB开始,任务在单个线程上执行,以避免并行执行引起的常见应用程序错误。
http://developer.android.com/reference/android/os/AsyncTask.html http://developer.android.com/reference/android/os/AsyncTask.html
So Task2 never run because you run it before a completion of Task1. 因此Task2永远不会运行,因为您是在Task1完成之前运行它的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.