Confusion: Handler and IntentService - android

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?

Related

Android Thread difference between AsyncTask, Executor and Service

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

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

IntentService vs Service [duplicate]

I am seeking an example of something that can be done with an IntentService that cannot be done with a Service (and vice-versa)?
I also believe that an IntentService runs in a different thread and a Service does not. So, as far as I can see, starting a service within its own thread is like starting an IntentService. Is that correct?
Tejas Lagvankar wrote a nice post about this subject.
Below are some key differences between Service and IntentService.
When to use?
The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.
The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).
How to trigger?
The Service is triggered by calling method startService().
The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.
Triggered From
The Service and IntentService may be triggered from any thread, activity or other application component.
Runs On
The Service runs in background but it runs on the Main Thread of the application.
The IntentService runs on a separate worker thread.
Limitations / Drawbacks
The Service may block the Main Thread of the application.
The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.
When to stop?
If you implement a Service, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method).
The IntentService stops the service after all start requests have been handled, so you never have to call stopSelf().
If someone can show me an example of something that can be done with an IntentService and can not be done with a Service and the other way around.
By definition, that is impossible. IntentService is a subclass of Service, written in Java. Hence, anything an IntentService does, a Service could do, by including the relevant bits of code that IntentService uses.
Starting a service with its own thread is like starting an IntentService. Is it not?
The three primary features of an IntentService are:
the background thread
the automatic queuing of Intents delivered to onStartCommand(), so if one Intent is being processed by onHandleIntent() on the background thread, other commands queue up waiting their turn
the automatic shutdown of the IntentService, via a call to stopSelf(), once the queue is empty
Any and all of that could be implemented by a Service without extending IntentService.
Service
Invoke by startService()
Triggered from any Thread
Runs on Main Thread
May block main (UI) thread. Always use thread within service for long task
Once task has done, it is our responsibility to stop service by calling stopSelf() or stopService()
IntentService
It performs long task usually no communication with main thread if communication is needed then it is done by Handler or BroadcastReceiver
Invoke via Intent
Triggered from Main Thread
Runs on the separate thread
Can't run the task in parallel and multiple intents are Queued on the same worker thread.
Don't reinvent the wheel
IntentService extends Service class which clearly means that IntentService is intentionally made for same purpose.
So what is the purpose ?
`IntentService's purpose is to make our job easier to run background tasks without even worrying about
Creation of worker thread
Queuing the processing multiple-request one by one (Threading)
Destroying the Service
So NO, Service can do any task which an IntentService would do. If your requirements fall under the above-mentioned criteria, then you don't have to write those logics in the Service class.
So don't reinvent the wheel because IntentService is the invented wheel.
The "Main" difference
The Service runs on the UI thread while an IntentService runs on a
separate thread
When do you use IntentService?
When you want to perform multiple background tasks one by one which exists beyond the scope of an Activity then the IntentService is perfect.
How IntentService is made from Service
A normal service runs on the UI Thread(Any Android Component type runs on UI thread by default eg Activity, BroadcastReceiver, ContentProvider and Service). If you have to do some work that may take a while to complete then you have to create a thread. In the case of multiple requests, you will have to deal with synchronization.
IntentService is given some default implementation which does those tasks for you.
According to developer page
IntentService creates a Worker Thread
IntentService creates a Work Queue which sends request to onHandleIntent() method one by one
When there is no work then IntentService calls stopSelf() method
Provides default implementation for onBind() method which is null
Default implementation for onStartCommand() which sends Intent request to WorkQueue and eventually to onHandleIntent()
Adding points to the accepted answer:
See the usage of IntentService within Android API.
eg:
public class SimpleWakefulService extends IntentService {
public SimpleWakefulService() {
super("SimpleWakefulService");
}
#Override
protected void onHandleIntent(Intent intent) { ...}
To create an IntentService component for your app, define a class that extends IntentService, and within it, define a method that overrides onHandleIntent().
Also, see the source code of the IntentService, it's constructor and life cycle methods like onStartCommand...
#Override
public int More ...onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
Service together an AsyncTask is one of best approaches for many
use cases where the payload is not huge. or just create a class
extending IntentSerivce. From Android version 4.0 all network
operations should be in background process otherwise the application compile/build fails.
separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. For more discussion of this topic, see the blog post
from Android developers guide:
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent, in turn, using a worker thread, and stops itself when it runs out of work.
Design pattern used in IntentService
:
This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness. Also, an IntentService isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask.
An IntentService has a few limitations:
It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity.
Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished.
An operation running on an IntentService can't be interrupted.
However, in most cases
IntentService is the preferred way to simple background operations
**
Volley Library
There is the library called volley-library for developing android networking applications
The source code is available for the public in GitHub.
The android official documentation for Best practices for Background jobs:
helps better understand on intent service, thread, handler, service. and also Performing Network Operations
I'm sure you can find an extensive list of differences by simply googling something such as 'Android IntentService vs Service'
One of the more important differences per example is that IntentService ends itself once it's done.
Some examples (quickly made up) could be;
IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.
Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication.
IntentService
IntentService runs on its own thread.
It will stop itself when it's done. More like fire and forget.
Subsequent calls will be queued. Good for queuing calls.
You can also spin multiple threads within IntentServiceif you need to- You can achieve this using ThreadPoolExecutor.
I say this because many people asked me "why use IntentService since it doesn't support parallel execution".
IntentService is just a thread. You can do whatever you need inside it- Even spinning multiple threads. The only caveat is that IntentService finishes as soon as you spin those multiple threads. It doesn't wait for those threads to come back. You need to take care of this. So I recommend using ThreadPoolExecutor in those scenarios.
Good for Syncing, uploading etc …
Service
By Default Service runs on the main thread. You need to spin a worker thread to do your job.
You need to stop service explicitly.
I used it for a situation when you need to run stuff in the background even when you move away from your app and come back more for a Headless service.
Again you can run multiple threads if you need to.
Can be used for apps like music players.
You can always communicate back to your activity using BroadcastReceivers if you need to.
An IntentService is an extension of a Service that is made to ease the execution of a task that needs to be executed in background and in a seperated thread.
IntentService starts, create a thread and runs its task in the thread. once done, it cleans everything. Only one instance of a IntentService can run at the same time, several calls are enqueued.
It is very simple to use and very convenient for a lot of uses, for instance downloading stuff. But it has limitations that can make you want to use instead the more basic (not simple) Service.
For example, a service connected to a xmpp server and bound by activities cannot be simply done using an IntentService. You'll end up ignoring or overriding IntentService stuffs.
Android IntentService vs Service
1.Service
A Service is invoked using startService().
A Service can be invoked from any thread.
A Service runs background operations on the Main Thread of the
Application by default. Hence it can block your Application’s UI.
A Service invoked multiple times would create multiple instances.
A service needs to be stopped using stopSelf() or stopService().
Android service can run parallel operations.
2. IntentService
An IntentService is invoked using Intent.
An IntentService can in invoked from the Main thread only.
An IntentService creates a separate worker thread to run background
operations.
An IntentService invoked multiple times won’t create multiple
instances.
An IntentService automatically stops after the queue is completed. No
need to trigger stopService() or stopSelf().
In an IntentService, multiple intent calls are automatically Queued
and they would be executed sequentially.
An IntentService cannot run parallel operation like a Service.
Refer from Here
If someone can show me an example of something that you can be done with an IntentService and can not be done with a service and the other way around.
IntentService can not be used for Long Time Listening, Like for XMPP Listeners, its a single time operator, do the job and wave goodbye.
Also it has just one threadworker, but with a trick, you can use it as unlimited.
The Major Difference between a Service and an IntentService is described as follows:
Service :
1.A Service by default, runs on the application's main thread.(here no default worker thread is available).So the user needs to create a separate thread and do the required work in that thread.
2.Allows Multiple requests at a time.(Multi Threading)
IntentService :
1.Now, coming to IntentService, here a default worker thread is available to perform any operation. Note that - You need to implement onHandleIntent() method ,which receives the intent for each start request, where you can do the background work.
2.But it allows only one request at a time.

Service vs IntentService in the Android platform

I am seeking an example of something that can be done with an IntentService that cannot be done with a Service (and vice-versa)?
I also believe that an IntentService runs in a different thread and a Service does not. So, as far as I can see, starting a service within its own thread is like starting an IntentService. Is that correct?
Tejas Lagvankar wrote a nice post about this subject.
Below are some key differences between Service and IntentService.
When to use?
The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.
The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).
How to trigger?
The Service is triggered by calling method startService().
The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.
Triggered From
The Service and IntentService may be triggered from any thread, activity or other application component.
Runs On
The Service runs in background but it runs on the Main Thread of the application.
The IntentService runs on a separate worker thread.
Limitations / Drawbacks
The Service may block the Main Thread of the application.
The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.
When to stop?
If you implement a Service, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method).
The IntentService stops the service after all start requests have been handled, so you never have to call stopSelf().
If someone can show me an example of something that can be done with an IntentService and can not be done with a Service and the other way around.
By definition, that is impossible. IntentService is a subclass of Service, written in Java. Hence, anything an IntentService does, a Service could do, by including the relevant bits of code that IntentService uses.
Starting a service with its own thread is like starting an IntentService. Is it not?
The three primary features of an IntentService are:
the background thread
the automatic queuing of Intents delivered to onStartCommand(), so if one Intent is being processed by onHandleIntent() on the background thread, other commands queue up waiting their turn
the automatic shutdown of the IntentService, via a call to stopSelf(), once the queue is empty
Any and all of that could be implemented by a Service without extending IntentService.
Service
Invoke by startService()
Triggered from any Thread
Runs on Main Thread
May block main (UI) thread. Always use thread within service for long task
Once task has done, it is our responsibility to stop service by calling stopSelf() or stopService()
IntentService
It performs long task usually no communication with main thread if communication is needed then it is done by Handler or BroadcastReceiver
Invoke via Intent
Triggered from Main Thread
Runs on the separate thread
Can't run the task in parallel and multiple intents are Queued on the same worker thread.
Don't reinvent the wheel
IntentService extends Service class which clearly means that IntentService is intentionally made for same purpose.
So what is the purpose ?
`IntentService's purpose is to make our job easier to run background tasks without even worrying about
Creation of worker thread
Queuing the processing multiple-request one by one (Threading)
Destroying the Service
So NO, Service can do any task which an IntentService would do. If your requirements fall under the above-mentioned criteria, then you don't have to write those logics in the Service class.
So don't reinvent the wheel because IntentService is the invented wheel.
The "Main" difference
The Service runs on the UI thread while an IntentService runs on a
separate thread
When do you use IntentService?
When you want to perform multiple background tasks one by one which exists beyond the scope of an Activity then the IntentService is perfect.
How IntentService is made from Service
A normal service runs on the UI Thread(Any Android Component type runs on UI thread by default eg Activity, BroadcastReceiver, ContentProvider and Service). If you have to do some work that may take a while to complete then you have to create a thread. In the case of multiple requests, you will have to deal with synchronization.
IntentService is given some default implementation which does those tasks for you.
According to developer page
IntentService creates a Worker Thread
IntentService creates a Work Queue which sends request to onHandleIntent() method one by one
When there is no work then IntentService calls stopSelf() method
Provides default implementation for onBind() method which is null
Default implementation for onStartCommand() which sends Intent request to WorkQueue and eventually to onHandleIntent()
Adding points to the accepted answer:
See the usage of IntentService within Android API.
eg:
public class SimpleWakefulService extends IntentService {
public SimpleWakefulService() {
super("SimpleWakefulService");
}
#Override
protected void onHandleIntent(Intent intent) { ...}
To create an IntentService component for your app, define a class that extends IntentService, and within it, define a method that overrides onHandleIntent().
Also, see the source code of the IntentService, it's constructor and life cycle methods like onStartCommand...
#Override
public int More ...onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
Service together an AsyncTask is one of best approaches for many
use cases where the payload is not huge. or just create a class
extending IntentSerivce. From Android version 4.0 all network
operations should be in background process otherwise the application compile/build fails.
separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. For more discussion of this topic, see the blog post
from Android developers guide:
IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent, in turn, using a worker thread, and stops itself when it runs out of work.
Design pattern used in IntentService
:
This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.
All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.
The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness. Also, an IntentService isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask.
An IntentService has a few limitations:
It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity.
Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished.
An operation running on an IntentService can't be interrupted.
However, in most cases
IntentService is the preferred way to simple background operations
**
Volley Library
There is the library called volley-library for developing android networking applications
The source code is available for the public in GitHub.
The android official documentation for Best practices for Background jobs:
helps better understand on intent service, thread, handler, service. and also Performing Network Operations
I'm sure you can find an extensive list of differences by simply googling something such as 'Android IntentService vs Service'
One of the more important differences per example is that IntentService ends itself once it's done.
Some examples (quickly made up) could be;
IntentService: If you want to download a bunch of images at the start of opening your app. It's a one-time process and can clean itself up once everything is downloaded.
Service: A Service which will constantly be used to communicate between your app and back-end with web API calls. Even if it is finished with its current task, you still want it to be around a few minutes later, for more communication.
IntentService
IntentService runs on its own thread.
It will stop itself when it's done. More like fire and forget.
Subsequent calls will be queued. Good for queuing calls.
You can also spin multiple threads within IntentServiceif you need to- You can achieve this using ThreadPoolExecutor.
I say this because many people asked me "why use IntentService since it doesn't support parallel execution".
IntentService is just a thread. You can do whatever you need inside it- Even spinning multiple threads. The only caveat is that IntentService finishes as soon as you spin those multiple threads. It doesn't wait for those threads to come back. You need to take care of this. So I recommend using ThreadPoolExecutor in those scenarios.
Good for Syncing, uploading etc …
Service
By Default Service runs on the main thread. You need to spin a worker thread to do your job.
You need to stop service explicitly.
I used it for a situation when you need to run stuff in the background even when you move away from your app and come back more for a Headless service.
Again you can run multiple threads if you need to.
Can be used for apps like music players.
You can always communicate back to your activity using BroadcastReceivers if you need to.
An IntentService is an extension of a Service that is made to ease the execution of a task that needs to be executed in background and in a seperated thread.
IntentService starts, create a thread and runs its task in the thread. once done, it cleans everything. Only one instance of a IntentService can run at the same time, several calls are enqueued.
It is very simple to use and very convenient for a lot of uses, for instance downloading stuff. But it has limitations that can make you want to use instead the more basic (not simple) Service.
For example, a service connected to a xmpp server and bound by activities cannot be simply done using an IntentService. You'll end up ignoring or overriding IntentService stuffs.
Android IntentService vs Service
1.Service
A Service is invoked using startService().
A Service can be invoked from any thread.
A Service runs background operations on the Main Thread of the
Application by default. Hence it can block your Application’s UI.
A Service invoked multiple times would create multiple instances.
A service needs to be stopped using stopSelf() or stopService().
Android service can run parallel operations.
2. IntentService
An IntentService is invoked using Intent.
An IntentService can in invoked from the Main thread only.
An IntentService creates a separate worker thread to run background
operations.
An IntentService invoked multiple times won’t create multiple
instances.
An IntentService automatically stops after the queue is completed. No
need to trigger stopService() or stopSelf().
In an IntentService, multiple intent calls are automatically Queued
and they would be executed sequentially.
An IntentService cannot run parallel operation like a Service.
Refer from Here
If someone can show me an example of something that you can be done with an IntentService and can not be done with a service and the other way around.
IntentService can not be used for Long Time Listening, Like for XMPP Listeners, its a single time operator, do the job and wave goodbye.
Also it has just one threadworker, but with a trick, you can use it as unlimited.
The Major Difference between a Service and an IntentService is described as follows:
Service :
1.A Service by default, runs on the application's main thread.(here no default worker thread is available).So the user needs to create a separate thread and do the required work in that thread.
2.Allows Multiple requests at a time.(Multi Threading)
IntentService :
1.Now, coming to IntentService, here a default worker thread is available to perform any operation. Note that - You need to implement onHandleIntent() method ,which receives the intent for each start request, where you can do the background work.
2.But it allows only one request at a time.

Difference between Service, Async Task & Thread?

What is the difference between Service, Async Task & Thread. If i am not wrong all of them are used to do some stuff in background. So, how to decide which to use and when?
Probably you already read the documentation description about them, I won't repeat them, instead I will try to give answer with my own words, hope they will help you.
Service is like an Activity but has no user interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.
A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.
An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are three methods that run on UI thread, which is good to update UI components.
I am using Services, AsyncTasks frequently. Thread less, or not at all, as I can do almost everything with AsyncTask.
This is the easiest answer for your question
Thread
is an unit of execution who run "parallel" to the Main Thread is an important point, you can't update a UI component from the any thread here except main thread.
AsyncTask
is a special thread, which gives you helper methods to update UI so basically you can update the UI even AsyncTask will run on a background thread. Interprocess communication handling is not required to be done explicitly.
Service
solve the above problem because it live separate from the activity that invoke it so it can continue running even when the activity is destroyed, it run in the Main Thread(beware of ANR) use a background service (extend IntentService it create the worker thread automatically for you). Service is like an activity without UI,
is good for long task
Few more information I wish someone had told me a few days ago:
You can share global variables - such as threads - between Activities and Services.
Your application together with all its global variables will not be wiped out as long as there is an Activity or a Service still present.
If you have an instance of a Service in your app and the OS needs resources, it first kills your Activities, but as long as there is the Service, the OS won't wipe out your application together with its global variables.
My use case is like this: I have one thread in global space that is connected to a server and an Activity that shows the results. When user presses the home button, the Activity goes to background and a new Service is started. This service then reads results from the thread and displays information in the notification area when needed. I don't worry about the OS destroying my Activity because I know that as long as the Service is running it won'd destroy the thread.
In short, Service for time consuming tasks, AsyncTask for short-lived tasks, Thread is a standard java construction for threads.
From developer's perspective:
Thread: Used to execute the set to codes parallely to the main thread. But you cannot handle the UI inside the thread. For that you need to use Handler. Hadler binds thread Runnable with Looper that makes it a UI thread.
ASyncTask: Used for handling those tasks that you cannot make to work on the main thread. For example, an HTTP request is a very heavy work that cannot be handled on the main thread, so you handle the HTTP request in the ASyncTask It works parallelly with your main thread Asynchronously in the background. It has a few callback methods that are invoked on their corresponding events.
Service: Works in the background under the same Application process. It is implemented when you have to do some processing that doesn't have any UI associated with it.
service is like activity long time consuming task but Async task allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.

Categories

Resources