Reputation: 2650
In my app i have buttons, when clicked will query the database and show result on screen. The query action will normally take 1 ~ 3 sec. These buttons will be clicked very often.
I've implemented this action on both AsyncTask and Thread but see very little different.
However in the long term, especially when the buttons are clicked many times, which will be more beneficial, in terms of resources (CPU, memory) ?
Upvotes: 5
Views: 2115
Reputation: 30611
When you use a Thread
, you have to update the result on the main thread using the runOnUiThread()
method, while an AsyncTask
has the onPostExecute()
method which automatically executes on the main thread after doInBackground()
returns.
While there is no significant difference between these two in terms of "which is more beneficial", I think that the AsyncTask
abstraction was devised so that a programmer doesn't have to synchronize the UI & worker threads. When using a Thread
, it may not always be as simple as calling runOnUiThread()
; it can get very tricky very fast. So if I were you, I'd stick to using AsyncTask
and keep Thread
for more specialized situations.
Upvotes: 6
Reputation: 1528
An AsyncTask
is used to do some background computation and publish the result to the UI thread (with optional progress updates). Since you're not concerned with UI, then a Handler
or Thread
seems more appropriate.
Reference : Handler vs AsyncTask vs Thread
Upvotes: 1