difference between asyntask and service in android - android

I am a beginner of Android Programming, and when I learn something about Service ,the problem has become.
We all know that the UI thread cannot run a long-time process, so we should run them in a new thread, and immediately ,we have recognised that something about Handler AsyncTask and Service even send a BroadCast when the task has been finished.However, I am not sure when to use them.
For example, we often using an activity to login, when the data should be posted, maybe post to the remote server, it may cost a long-time,we cannot write something in LoginActivity maybe in an AsyncTask or a Service to do that.But which is the better choice ?

As a general rule:
A service is running in background and does some (periodic) work for
you. For example if you want to fetch news from a REST-API every 15
minutes and informed the user within the app or with a notification
than use a service.
An AsyncTask is an separated thread for work intensive jobs to
prevent the UI thread from blocking. For example fetch the news after
the user clicks the "Get News" button.
In your case, the expectation of the user is important. The user tries to login and waits in an activity for the responds of the server. You should send the request to the server in an AsyncTask and e.g. show the user a waitscreen until the response is there ("Try to login"). So the UI is still responsive but the user clearly knows, that he has to wait for a response.

A service is running all the time on background on your device.
An AsynkTack is launch when you need it and executed in background. When it's done, the thread is destroyed.

Services - A Service is an application component that can perform long-running operations in the background, and it does not provide a user interface.A service is a task with no UI.Runs always on main thread and can also block main thread.We can start service by calling method startService()
AysnTask - The AsyncTask class allows to run instructions in the background and to synchronize again with the main thread. It also reporting progress of the running tasks.Used for task in parallel.We start it by calling method execute().Wrok on worker thread and triggered from main thread.It can not run in loop.

Related

How to create a service that runs in the background and performs async tasks in Android

I'm having great difficulty understanding when to use Service vs IntentService in Android.
I'm trying to create a Manager Class that can, download, verify and install APKs.
The process of doing this require me to spawn a service(DownloadManager) to download the file, which causes my service to be destroyed prematurely.
It also needs to run an activity to install the apk.
This download manager has no front end, I just want it to be a background process that does its thing and returns the results programmatically.
I've read into both Service and Intent Service and although the documentation clearly says that Intent Services are meant to be used when the processing should be done off the UI thread, but nearly every forum I visit says that you should not do async work inside an IntentService.
For example:
Waiting for asynchronous callback in Android's IntentService
In general, an IntentService is useful for when you have discrete tasks that you want executed one at a time off of the UI thread. The IntentService will keep track of each request in a queue, execute one request at a time - on a separate, non-UI thread - and then will shut down when the queue is empty. If a new request arrives later, it will start up again, then shut down again once the queue is empty.
The warnings about running "async" work inside of an IntentService are because once onHandleIntent exits, the IntentService thinks that item has finished processing. It has no way of knowing if you created another thread that you want it to wait for. So once it has called onHandleIntent for all outstanding requests, it's going to shut down, even if there are child threads still running.
A non-intent Service gives you control over when the service starts and stops, regardless of whether there's any work to do. Also, unless you specifically make it otherwise, everything the Service does happens on the UI thread - so if you want work done on a background thread, you need to explicitly implement that. It's also up to you to implement how the Service handles multiple incoming requests. But, the service won't shut down until you tell it to (or the OS runs out of resources).
It sounds based on your description like you probably have two choices:
If you're ok with the service processing requests one at a time, you could use an IntentService - but you'll need to make onHandleIntent wait for each request to finish. This is still happening off of the UI thread, but it does mean that if you have multiple download requests, they're not going to happen in parallel.
You could use a non-intent Service to process each download request on its own child thread, all in parallel. Then it's up to you to keep track of all the processing threads.

Service vs Thread in Android

I am looking for what service should be used in android applicaton.
Docs says
A Service is an application component that can perform long-running operations in the background and does not provide a user interface.
I have read this thread Application threads vs Service threads that saying same services are for running operation in background.
But here this can be done using Thread also. Any difference between them and where you should use them
UPDATE based on latest documentation:
Android has included in its documentation on when you should use Service vs Thread. Here is what it says:
If you need to perform work outside your main thread, but only while
the user is interacting with your application, then you should
probably instead create a new thread and not a service. For example,
if you want to play some music, but only while your activity is
running, you might create a thread in onCreate(), start running it in
onStart(), then stop it in onStop(). Also consider using AsyncTask or
HandlerThread, instead of the traditional Thread class. See the
Processes and Threading document for more information about threads.
Remember that if you do use a service, it still runs in your
application's main thread by default, so you should still create a new
thread within the service if it performs intensive or blocking
operations.
Another notable difference between these two approaches is that Thread will sleep if your device sleeps. Whereas, Service can perform operation even if the device goes to sleep. Let's take for example playing music using both approaches.
Thread Approach: the music will only play if your app is active or screen display is on.
Service Approach: the music can still play even if you minimized your app or screen is off.
Note: Starting API Level 23, you should Test your app with Doze.
Android Documentation - Services
A Service is meant to run your task independently of the Activity, it allows you to run any task in background. This run on the main UI thread so when you want to perform any network or heavy load operation then you have to use the Thread there.
Example : Suppose you want to take backup of your instant messages daily in the background then here you would use the Service.
Threads is for run your task in its own thread instead of main UI thread. You would use when you want to do some heavy network operation like sending bytes to the server continuously, and it is associated with the Android components. When your component destroy who started this then you should have stop it also.
Example : You are using the Thread in the Activity for some purpose, it is good practice to stop it when your activity destroy.
This is the principle i largely follow
Use a Thread when
app is required to be visible when the operation occurs.
background operation is relatively short running (less than a minute or two)
the activity/screen/app is highly coupled with the background operation, the user usually 'waits' for this operation to finish before doing anything else in the app.
Using a thread in these cases leads to cleaner, more readable & maintainable code. That being said its possible to use a Service( or IntentService).
Use a Service when
app could be invisible when the operation occurs (Features like Foreground service could help with operations being interrupted)
User is not required to 'wait' for the operation to finish to do other things in the app.
app is visible and the operation is independent of the app/screen context.
Reference from https://developer.android.com/guide/components/services.html
A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.
If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service.
For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop().
Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.
My Approach for explanation is simple:
Create a thread when you are in the activity and want to do some background operation with frequent communication with the main thread.
Alert- Don't create too many threads as 1 thread is equal to 1 processor thread. If you want to do parallel processing with threads(multiple) try your hands on Executors
Now you want long running operations with less interaction with UI then go for Service. Keep in mind service runs on UI thread. But now you want the processing should be done in background thread, then go for Intent Service.Intent service maintains their Thread Pools and do not create new threads and runs your tasks serially.

Service and IntentService, Which is better to run a service that poll database value from the server?

I had read quite a number of resources regarding the Service and IntentService. However when come to make a decision, I am not confident enough to choose which type to use in order to create a background service that will poll data from database in a time interval and stop it when I get the data I want since the data represent a status of a request, eg. ordering medicine confirmation status(pending, completed, in progress). I need to detect when a status is set to "completed" and send a notification to alert the user that the order is completed. After that the service will stop itself automatically.
Please kindly advice. Thank you.
Intent Service -
Works in Worker Thread , not in Main Thread.
Intended to execute their action is separate thread and then get shut down.
They do perform their operation and stops.
Ideal to perfrom things like htp get ,don't require to stay connected with server.
Service -
Runs in main thread.
Ideal when there is requirement to stay connected with server
(i.e. permanent tcp connection), the way you can go is to have a service (not an intent one) that performs the networking stuff using an asynctask or a more classic thread hosted in the service
It makes no difference. Use whatever you find easier. This question isn't worth spending any time worrying about. Just make sure you understand what code needs to run on the main (UI) thread and what code needs to run on a background (worker) thread. In IntentService the "long-running operation" needs to run in onHandleIntent() If you are using Service in onStartCommand() you would start your own background thread and execute the "long-running operation" on that.

Android service or thread

Hi in android I need send requests to a server every 30 seconds while the app is running without interfering with the user. Would it be advisable to do this in a service or thread, or a service with a new thread?
Cheers
Better to use Service.Use AlarmManager to call the service.In service write the code for send request to server
Service: A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user
While thread is a concurrent unit of execution.You can use both for your purpose and another option is Runnable with Handler where you can call operation or code for every 30 seconds
Check out AlarmManager (as Chaitu said) as well as IntentService.
I suggest you use a Service rather than creating one thread. The Android developer site states the following:
Note that services, like other application objects, run in the main
thread of their hosting process. This means that, if your service is
going to do any CPU intensive (such as MP3 playback) or blocking (such
as networking) operations, it should spawn its own thread in which to
do that work. More information on this can be found in Processes and
Threads. The IntentService class is available as a standard
implementation of Service that has its own thread where it schedules
its work to be done.
Since the Service runs in the UI thread you should create a new thread in the service that makes request every 30 seconds to the server.
I hope this helps.
I will suggest you to write an IntentService not a simple Service and inside it write a static method to send a request to server with backoff time 30 seconds and in your activity just start the service.
To simply answer - "Should you use a service or a thread?"
A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.
If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service.
Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

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