62

I am currently writing my first Android application and I keep running into references to background and foreground services. Since I intend on using a service in my application I was hoping to get a clarification between the two and how they are used.

mohsen
  • 1,763
  • 3
  • 17
  • 55
Andrew Guenther
  • 1,362
  • 2
  • 12
  • 30

3 Answers3

58

Perhaps this will answer your question:

A started service can use the startForeground API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm.

More info can be found here

Airon Tark
  • 8,900
  • 4
  • 23
  • 19
Asahi
  • 13,378
  • 12
  • 67
  • 87
  • How can you know if your service really started as foreground service? is there any trace in logcat? – Alex Jan 21 '11 at 22:56
  • 2
    Whether the service is in foreground or background depends on two factors: the service state and the way you started it. http://developer.android.com/reference/android/app/Service.html#ProcessLifecycle – m-ric Sep 18 '12 at 17:22
57

Foreground: The process relies on onPause() and onResume()...i.e you play music player and pressing pause and play

Background: The process which runs without user interaction i.e receiving a message, incoming call, receiving mails, or setting alarms. The method used here is onStart() and onStop().

For example, check it on your phone. Create an alarm at 6:30am. When the system clock reaches 6:30am it fires. In order to kill the alarm service, just go to menu-->settings-->application-->Running service-->click stop service. It stops the alarm service even when your system reaches the time it won't fire.

Brandon Ling
  • 3,841
  • 6
  • 34
  • 49
DineshKumar
  • 1,641
  • 15
  • 13
  • 1
    Better to attach a link to the relevant official documentation, like this one: https://developer.android.com/guide/components/services – Yoav Feuerstein Feb 11 '19 at 14:03
4

Foreground Service is used when User is interaction with application and when Service is doing something visible to user. Background Service is used when even user close application (discard from recents) and when Service is doing something not visible to user like downloading data from server, load data from a ContentProvider etc.. And Foreground Service is less likely to be killed by system on low memory.

Samir Alakbarov
  • 1,120
  • 11
  • 21