Search code examples
javaandroidmultithreadingandroid-asynctask

AsyncTask vs Worker thread for getting information from a MySQL DB


I understand that I cannot access a MySQL DB from the main thread (UI thread). So I know now that I have options for doing so. I can use a worker thread ( Thread t = new Thread() ) to access MySQL db and get what I need or I can do AsyncTask to access MySQL db and get what I need.

But my question here is, what would be the right way of going about this or the most efficient approach here? I really want to understand and follow good programming procedures when I come across this.

So retrieving data from a MySQL db: AsyncTask, a worker thread or would there be no difference time, power etc?


Solution

  • AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask. (Straight from the doc).

    http://developer.android.com/reference/android/os/AsyncTask.html.

    An alternative to asynctask for long running operations is robospice.

    https://github.com/octo-online/robospice

    Update:

    Asynctask is deprecated using coroutines or any other threading mechanism. Consider suing work manager for defferable jobs.