Is there a way to elevate the priority of an AsyncTask?
I'm doing some image manipulation in an AsyncTask. On a very slow device, it takes up to 60 seconds to process an image. Now I'd like to increase the performance by elevating the priority of the task. Can it be done somehow?
Directly from the Android docs, an AsyncTask runs in four sequential steps: doInBackground (Params...) — invoked on the background thread immediately after onPreExecute () finishes executing
AsyncTask Tutorial With Example Android Studio [Step By Step] In Android, AsyncTask (Asynchronous Task) allows us to run the instruction in the background and then synchronize again with our main thread. This class will override at least one method i.e doInBackground (Params) and most often will override second method onPostExecute (Result).
In this example, a URL is passed into the AsyncTask, the progress units are Integer, and the result of the background task is a Long. (You can see the complete code for this class later in this tutorial.) Directly from the Android docs, an AsyncTask runs in four sequential steps:
AsyncTask uses three types of parameter i.e Params, Progress, Result. Params parameters are passed to perform background computation. Progress parameters are used to update UI thread.
Try to use following (increase of priority AsyncTask
threads):
protected final MyResult doInBackground(MyInput... myInput) {
Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND + THREAD_PRIORITY_MORE_FAVORABLE);
// blah-blah
}
If you do not have a heavy UI which would interleave with the AsyncTask flow of execution, then your problem is in the algorithm used.
If you can divide your algorithm in parallel tasks, then you can use a pool of executors. If not, your Async Task is just doing serial work.
Be aware that according to AsyncTask:
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR
You can use code like this on most devices
if (Build.VERSION.SDK_INT >= 11) {
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
asyncTask.execute();
}
or even create a custom ThreadPoolExecutor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With