1

As for the other application components like activities,Intent, Broadcast Receiver, i can understand their use case but whatever use case of Service is written in the documentation can be achieved using simple Java class having static members (variables and methods) . Like if i need a download file service . I can have a static method which will receive taskListener and other required parameters (eg. url of file) in the argument and download the file async and give the callback to taskListener's callback method. So why should i use service for that.

Please someone explain me the reason of using service with example

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3024215
  • 196
  • 1
  • 7
  • A `Service` has its own life cycle and time independent of the `Activity`. With static fields and async tasks you have so many possibilities to fail. – tynn May 25 '16 at 13:41
  • Because the process (and your download) will very likely be removed from memory unless the user has the phone screen on and the user is looking directly at your Activity without closing it for the entire duration of the download. When the system needs memory, it will close Activities first before moving on to Services. – DeeV May 25 '16 at 13:41

1 Answers1

2

First, a service can be started or bound to from outside the application, if you wish, by having the service be exported. That cannot be done via a simple Java class. This is essential for most of the specialized services (input methods, AccessibilityService, TileService, etc.).

Second, a service raises the importance of a process, telling Android that it is doing work on behalf of a user. This helps keep the process around for longer, before Android terminates that process to free up system RAM for other apps. That cannot be done via a simple Java class. So, for example, while you can download a file using a simple Java class, Android might terminate your process before that download can be completed. This is less likely if the download is managed by a service.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491