AsyncQueryHandler's call to onQueryComplete on ui thread? ( Android )
-
20-06-2021 - |
Question
I am using AsyncQueryHandler
and it calls onQueryComplete
once the query is complete.
My question: is onQueryComplete
called on the UI thread?
I know it does the query in the background.
Does it matter where AsyncQueryHandler
is instantiated? (If instantiated in UI thread will mean onQueryComplete
will be called on UI thread).
La solution
Is
onQueryComplete
called on UI thread?
It's called on the calling thread... so the thread on which you launched the AsyncQueryHandler
.
Does it matter where
AsyncQueryHandler
is instantiated?
AsyncQueryHandler
is a subclass of Handler
that performs an asynchronous query (or insert, update, delete) to the ContentResolver
and returns the result to the calling thread. Handler
s are allowed to be associated with threads other than the main UI thread, and so are queries/transactions to the ContentResolver
. Therefore, you should be allowed to call AsyncQueryHandler
from a separate thread too.
That being said, doing so is probably not what you want for a couple reasons:
When you instantiate the
AsyncQueryHandler
on a separate thread, all subsequent callbacks will be returned to that calling thread. This is usually not what you want because it doesn't provide an easy means of syncing with the main UI thread, the thread that is responsible for creating your layouts and receiving your touch events.You are already on a separate thread, so calls to the
ContentResolver
will already be asynchronous with respect to the UI thread.
And by the way, the documentation on AsyncQueryHandler
doesn't mention anything about these points, but you can figure most of it out by reading the source code. The documentation for Handler
(its immediate base class) explains the theory behind it too.