Android Thread difference between AsyncTask, Executor and Service - android

I'm a bit confused about multi-threading in Android. Could you tell me the difference and the use case of AsyncTask, Executor and Service ?
Thank you in advance.

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.)
Read docs
Executor is just an object that executes submitted Runnable tasks.
Read docs
Service does not relate to multi-threading at all. A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.
Read docs

Related

Solution to move way from main thread in Service?

What should be used in service to move away from UI thread?
For both Started Service and Bound Service
Loader
Asynctask
Simple thread
Robospice Library
Or something else
I want my service to keep on running even if the app is in background.
I want service to run indefinite time.
Thanks.
Use IntentService. It is a subclass of Service. It automatically runs the code in the background thread. And it clears itself up after the execution completes. You don't have to stop the IntentService.
If you have to run single long task and stop service after that, you should use IntentService - it run on separate thred and stop itself after job is done. From your descriptin it seen like you want Service running indefinite time. For that you should use RxJava library. It has many advantages for performing concurrent operations, see docs for more details, among those;
Eas two thread pools and scheduler for main thread;
Easily allow synchronizing concurret tasks - you can execute one task, wait for another, etc. without using pure java's locks.
You can run job on one thread, then process results on another thread, etc;
You can process results in reactive ways;
You can create your own scheduler from HandlerThread and use single thread for all your tasks

Using AsyncTask in Service

Is that a normal practice of using AsyncTask in Service (not IntentService). Or is it better to create background thread in another way?
Is that a normal practice of using AsyncTask in Service
No. The point of AsyncTask is to be able to do some work on the main application thread after the background work is completed. Services rarely, if ever, need to do work on the main application thread.
Or is it better to create background thread in another way?
Yes: new Thread() would be a strong candidate as a straight-up replacement for AsyncTask. In other cases, some form of thread pool might make sense.
No, an AsyncTask is designed to run some short lived work in a background thread away from the UI thread. It has callbacks that allows it to modify the UI thread once it is completed.
If you need a separate thread in a service, create a thread using new Thread()

Confusion: Handler and IntentService

So I have gone through the developer site:
https://developer.android.com/training/articles/perf-anr.html
So I came to a conclusion :avoid intensive tasks via worker thread. So should use Asyctask, Intent Service and Handlers.
Also these three tasks have some limitations:
Asynctask:
It could not be used for long running operations
Cannot be used when using multiple asynchronous operations and and the need for UI change, will become more complicated
IntentService
Works requests run sequentially.
Operation running cannot be interrupted
Now keeping this in mind, as Handler and IntentServices could be used for long running operation.
can anybody help me with the difference between Handler and IntentService ?
Like when should I use Handler and when IntentService and which is better to use?
Also what is the best approach to run request asynchronously?

send data from the UI thread to another thread which is not created in by the Main Activity "Android"

I checked in several websites but i didn't find an answer to this question.
I have a UI thread that calls a service with an alarmManager at a specific frequency.
and the service by itself calls another IntentService, that starts a Server/client thread. I want to know if it is possible to make the Server/Client Threads communicate with the UI thread?
Thanks a lot for your help.
The IntentService.onCreate() method is always executed on the UI thread. You can create a new Handler instance inside that method and store it in an instance or a class data member of your IntentService implementation. You can use this Handler to post(Runnable) to be executed on the UI thread, or sendMessage(Message) which will be processed on the UI thread by your handleMessage(Message) implementation. I would suggest to stick with post(Runnable) for simplicity.
Update based on your comment:
Assuming your background thread does continuous processing on its own and does not have a looper, the easiest way would be to create a queue (ArrayList<MyLocation> would work for example), and add each new location to the tail of it from the UI thread. Meanwhile the background thread picks the next location from the head and processes it as expected. This is a very simple asynchronous way of communicating between the two threads (and is essentially a simplified version of how Looper and Message work).
However, the main drawback of this approach is that your background thread is always busy thus waisting CPU resources if there are no incoming location updates. The better alternative would be to change your background thread to be a Looper thread and send Message to it. Here's an example of how to Create Looper thread and send a Message to it.

Asynctask vs Thread in android

In UI, to perform some background work, I used a separate Thread. But as suggested by others, I am now using AsyncTask.
What is the main difference between a Thread and an AsyncTask?
In which scenario, should I use a Thread or an AsyncTask?
For long-running or CPU-intensive tasks, there are basically two ways to do this: Java threads, and Android's native AsyncTask.
Neither one is necessarily better than the other, but knowing when to use each call is essential to leveraging the system's performance to your benefit.
Use AsyncTask for:
Simple network operations which do not require downloading a lot of data
Disk-bound tasks that might take more than a few milliseconds
Use Java threads for:
Network operations which involve moderate to large amounts of data (either uploading or downloading)
High-CPU tasks which need to be run in the background
Any task where you want to control the CPU usage relative to the GUI thread
And there are lot of good resources over internet which may help you:
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html
If you use Java threads you have to handle the following requirements in your own code:
Synchronization with the main thread if you post back results to the
user interface
No default for canceling the thread
No default thread pooling
No default for handling configuration changes in Android
Thread
Long task in general
Invoke by thread.start() method
Triggered from any thread
Runs on its own thread
Manual thread management/code may become difficult to read
AsyncTask
Small task having to communicate with main thread
Invoke by excute() method
Triggered from main thread
Runs on worker thread
Must be executed and created from the main thread
Thread
A thread is a concurrent unit of execution. It has its own call stack.
There are two methods to implement threads in applications.
One is providing a new class that extends Thread and overriding its
run() method. The other is providing a new Thread instance with a
Runnable object during its creation. A thread can be executed by
calling its "start" method. You can set the "Priority" of a thread by
calling its "setPriority(int)" method.
A thread can be used if you have no affect in the UI part. For
example, you are calling some web service or download some data, and
after download, you are displaying it to your screen. Then you need to
use a Handler with a Thread and this will make your application
complicated to handle all the responses from Threads.
A Handler allows you to send and process Message and Runnable objects
associated with a thread's MessageQueue. Each thread has each message
queue. (Like a To do List), and the thread will take each message and
process it until the message queue is empty. So, when the Handler
communicates, it just gives a message to the caller thread and it will
wait to process.
If you use Java threads then you need to handle the following
requirements in your own code:
Synchronization with the main thread if you post back results to the
user interface No default for canceling the thread No default thread
pooling No default for handling configuration changes in Android
AsyncTask
AsyncTask enables proper and easy use of the UI thread. This class
allows performing background operations and publishing results on the
UI thread without having to manipulate threads and/or handlers. An
asynchronous task is defined by a computation that runs on a
background thread and whose result is published on the UI thread.
AsyncTask will go through the following 4 stages:
onPreExecute()
Invoked on the UI thread before the task is executed
doInbackground(Params..)
Invoked on the background thread immediately after onPreExecute()
finishes executing.
onProgressUpdate(Progress..)
Invoked on the UI thread after a call to publishProgress(Progress...).
onPostExecute(Result)
Invoked on the UI thread after the background computation finishes.
Why should you use AsyncTask?
Easy to use for a UI Thread. (So, use it when the caller thread is a
UI thread).
No need to manipulate Handlers.
For further information visit Here
Thread:
Thread should be used to separate long running operations from main thread so that performance is improved. But it can't be cancelled elegantly and it can't handle configuration changes of Android. You can't update UI from Thread.
AsyncTask can be used to handle work items shorter than 5ms in duration. With AsyncTask, you can update UI unlike java Thread. But many long running tasks will choke the performance.
You have few more alternatives to both of them.
HandlerThread/ Handler and ThreadPoolExecutor
Refer to below post for more details:
Handler vs AsyncTask vs Thread
If you have longer tasks which should work concurrently to leverage the CPU cores and shorten time latency, you should absolutely use Multithreading or a Thread:
You can initialize the thread form the Background Thread or (initialization can be possible as Inner Thread) unlike AsyncTask.
You don't need to inherit parent class and override methods (More Clean and Precise).
You can manage Concurrency yourself with multithreading, just read about Volatile and Atomicity.
For publishing on UI, you can use synchronized thread and notify UiThread using UIhandler.

Categories

Resources