Android - Service (background operation without UI interaction)

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.

startService(MyService)
stopService(MyService)

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.

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.

Snippet

public class MyService extends Service {

    @Override
    public void onCreate() { ....} 
    
    @Override
    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)
         startForeground(notification); 
         
        // TODO: Initiate background Task
           
        return Service;
           
    }
    
    @Override
    public void onDestory() { .... }
    
    @Override
    public IBinder onBind(Intent intent) {
    
        return null;
        
    }
    
}

Type

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);
intent.putExtra(myService.KEY_VALUE,"value"); 
// Start the service (ie place the intent in the service queue)
getActivity().startService(intent);
  • Implementing the service
public class MyIntentService extends IntentService
    
    @Override
    protected void onHandleIntent(Intent intent) {
        
        // TODO: Task to be performed
        
    }
    
}

SyncAdapter

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

Declaration

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

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

Documentation / Reference


Powered by ComboStrap