Android - Service (background operation without UI interaction)

> Android

1 - About

A Service is a component that performs operations in the background without a user interface. (such as download a file)

You start a service by passing an intent.


Default Services have a higher priority that background activity.

A service has its own context.

To wake it self up, you need to implement a broadcast receiver. It will receive a PendingIntent (Intent with permission) from the Alarm Manager.


3 - Priority

Priority Activity Type Service Type
Critical Active Foreground
High Visible Running (Default)
Low Background Na

Any background app will be killed as needed from older to newer.

4 - Snippet

public class MyService extends Service {
    public void onCreate() { ....} 
    public int onStartCommand(Intent intent, int flags, int startId) {
         // Set the service as a foreground activity, 
         // therefore increasing its priority 
         // and decreasing its chance to be killed (mainly impossible)
        // TODO: Initiate background Task
        return Service;
    public void onDestory() { .... }
    public IBinder onBind(Intent intent) {
        return null;

5 - Type

5.1 - IntentService

Service run on the main thread then you need to use a background running thread to do what you want to do within your service.

The IntentService class implements a background thread pattern with a intent queue. The service start when an intent is received and stop when the queue is empty.

  • Adding a intent to the services queue
Intent intent = new Intent(getActivity(), myService.class);
// Pass a value to the service that can be retrieved with intent.getStringExtra(KEY_VALUE);
// Start the service (ie place the intent in the service queue)
  • Implementing the service
public class MyIntentService extends IntentService
    protected void onHandleIntent(Intent intent) {
        // TODO: Task to be performed

5.2 - SyncAdapter

Performing data sync operations. See Android - Sync Manager Framework (SyncAdapter)

6 - Declaration

As a service is a component, it must be declared in the AndroidManifest.xml file

<service android:name="com.example.myapp.service.myService"/>

7 - Documentation / Reference