Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Service for background tasks?

Tags:

android

An activity can use AsyncTask or Handler framework for background work. Both will continue to work even after user has moved away from the activity that started them and the onDestroy for the activity has been called. In other words, an activity is fully capable of doing background work even after its GUI has been shutdown.

In this scenario, use of Service for background work seems like redundancy. What does Service bring to the table that an activity can not do? Thanks.

like image 391
Raj Avatar asked Nov 02 '10 14:11

Raj


1 Answers

What is a Service?

Most confusion about the Service class actually revolves around what it is not:

  • A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
  • A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

Thus a Service itself is actually very simple, providing two main features:

  • A facility for the application to tell the system about something it wants to be doing in the background (even when the user is not directly interacting with the application). This corresponds to calls to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
  • A facility for an application to expose some of its functionality to other applications. This corresponds to calls to Context.bindService(), which allows a long-standing connection to be made to the service in order to interact with it.

Read the rest of the documentation for more info

So one instance of a service would be something you want to happen at set intervals on its own without having to launch an activity or anything else to "launch" it. For example, SMSBackup is just a service that runs in the background, polling every X minutes your SMS messages and copies them into a gmail label, as a "backup" service.

like image 64
Bryan Denny Avatar answered Sep 21 '22 12:09

Bryan Denny