Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start Async Task within a worker thread

I have two questions:

  • Can we start/execute an Async Task within a worker thread?
  • If yes, the methods onPreExecute(), onProgressUpdate(Progress...) and onPostExecute(Result) are invoked on the UI thread?

I wanna know that because I have a TCP connection running on a worker thread and when a packet is received I wanna start a new thread to make the parse of this packet and after that refresh some data structures on the UI thread.

Thanks in advance!

like image 214
amp Avatar asked Mar 19 '12 00:03

amp


People also ask

Can an AsyncTask be executed in a worker thread?

The AsyncTasks are heavily using the ThreadPoolExecutors to do its tasks on the worker thread, and once done it passes back the result to the UI thread using Handlers.

Is it possible to start AsyncTask from background thread?

Android App Development for Beginners Android AsyncTask going to do background operation on background thread and update on main thread. In android we cant directly touch background thread to main thread in android development. asynctask help us to make communication between background thread to main thread.

Do tasks run on another thread?

Run() or similar constructs, a task runs on a separate thread (mostly a managed thread-pool one), managed by the . NET CLR. But that depends on the actual implementation of the task.

How does async task work internally?

So resuming: execute() calls executeOnExecutor() and we get a queue of tasks that wait for execution while just one Task is running in the executor, all of this applicationwise. This means that even though we call 10 AsyncTasks execute() one will be executing while the others will all be enqueued.


2 Answers

From the Android AsyncTask doc:

"The task instance must be created on the UI thread.", and

"execute(Params...) must be invoked on the UI thread."

So I think the answer to your first question is "no". As far as the second, those methods are all invoked on the UI thread, but it's a bit moot.

EDIT: I'm not sure if those are absolute restrictions, or strong suggestions, but in both cases, I'd recommend following them.

like image 171
mfsiega Avatar answered Nov 10 '22 05:11

mfsiega


Just for the Record: If you start a AsyncTask outside the UI-Thread the onPreExecute will not be executed from the UI-Thread (but from the caller Thread). This will lead to an exception. However the onPostExecute Method will always be executed on the UI-Thread. Hope to help someone :)

like image 34
Langusten Gustel Avatar answered Nov 10 '22 06:11

Langusten Gustel