37

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

Community
  • 1
  • 1
N Sharma
  • 33,489
  • 95
  • 256
  • 444

5 Answers5

41

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

user1506104
  • 6,554
  • 4
  • 71
  • 89
  • 1
    As a complement to this information please read http://stackoverflow.com/questions/15524280/service-vs-intentservice – Eduardo Pinheiro Nov 03 '16 at 12:51
  • 4
    Please be aware, as explained in the first post, that Service does not run in a separate thread meaning that it may block the Main Thread if you do intensive CPU work. Read this post for more information http://stackoverflow.com/questions/7875926/does-android-service-run-from-a-seperated-thread-instead-of-ui – Eduardo Pinheiro Nov 03 '16 at 12:53
  • 2
    please add the exact page link of the google document which explains this as a Further Reading note. – Khay Jul 22 '17 at 04:44
  • A raw thread in activity? Please be careful as this may result to a leak especially if the thread is long-running. – user1506104 Nov 25 '18 at 13:03
  • In your response you said "Another notable difference between these two approaches is that Thread will sleep if your device sleeps". It is wrong. Thread will NOT sleep. – Nick Nov 25 '18 at 13:08
  • The thread will sleep if the device sleeps. In fact everything will sleep if device sleeps aside from GSM and probably AlarmManager. Are you referring to screen off? Please bear in mind that 'device sleep' and 'screen off' are different and do not happen at the same time. – user1506104 Nov 25 '18 at 17:41
  • "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" ... Services CANNOT perform when device sleeps https://stackoverflow.com/questions/51460417/who-killed-my-service/51587562#51587562 – Nick Nov 28 '18 at 09:33
  • If iam correct please edit your answer. Also using wakelock doesnt make any difference, music will stop after a while https://developer.android.com/training/monitoring-device-state/doze-standby – Nick Nov 28 '18 at 10:03
  • Your answer has been edited because can be misleading for some people. – Nick Nov 28 '18 at 10:28
  • That is correct. That's why if you want to, lets say, play music while screen is off, you need to use service (with a wakelock or more recently with foreground service). – user1506104 Nov 28 '18 at 10:33
  • Its not best practice to play music with a service using wakelock, THAT IS WRONG. Eventually the music WILL stop regardless of the wakelock. People get confused from your un-searched answer – Nick Nov 28 '18 at 10:37
  • https://developer.android.com/training/monitoring-device-state/doze-standby – Nick Nov 28 '18 at 11:18
29

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.

liggiorgio
  • 217
  • 7
  • 18
N Sharma
  • 33,489
  • 95
  • 256
  • 444
  • 2
    But say you want to play music. That would be something in the background/independently of any activity so you would use a service right? But couldn't you also start a thread to do the work of playing the music without using a service? – committedandroider Aug 18 '15 at 21:40
  • 1
    We know thread may lead to activity leaks if you don't coordinate it's lifecircle over the activity.Which means when the activity is destroyed, the thread is still active if it's task is not finished.So I think thread is independent from the activity. – Allen Vork Jun 30 '16 at 07:38
  • 2
    @committedandroider You can but should't use thread alone in that case because application thread will stop when device screen turns off stopping your music also. Instead you can create a Service and use a worker thread in it or simply you can go for IntentService, which is a Service along with a worker thread. – CopsOnRoad Sep 12 '17 at 05:45
  • 1
    Sorry for disrupting you. However, I can't understand the `run any task in the background`. Could you explain it more detail? I think that run in the background means to run on the different thread. – Trần Đức Tâm Aug 21 '18 at 03:48
  • 1
    @TrầnĐứcTâm 'run any task in the background' has 2 ways to understand. First, it means that runs in the main thread but not show UI, like Service when starting as default. And the second is run in a background thread. – Albert Khang Jan 15 '21 at 04:44
11

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.
Vinay W
  • 9,912
  • 8
  • 41
  • 47
  • So if you were playing music, would you use a thread because it depends on which activity you're on - splash screen, etc? – committedandroider Aug 18 '15 at 21:42
  • 1
    Music starts and ends on the splash screen? Thread, Yes. Even the main thread would do, unless you're streaming remotely(which might not be a good idea for a splash screen which lasts for 2-3 seconds as the stream might take longer to even begin). – Vinay W Aug 19 '15 at 05:27
  • So service would be like Spotify when you continue to stream the music without interacting with the UI? – committedandroider Aug 19 '15 at 17:08
  • 2
    Correct. If that's what you want to achieve, you should use a service. – Vinay W Aug 20 '15 at 05:22
2

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.

Elsa Lin
  • 243
  • 1
  • 3
  • 10
0

My Approach for explanation is simple:

  1. 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

  2. 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.

Harpreet Singh
  • 878
  • 1
  • 7
  • 5