Long running background services in Android

We all know for service should be in running even when app is killed is through sticky service. Just override the onStartCommand() method and return START_STICKY. The code snippet is,

  public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    return START_STICKY;

Here one tricky situation could arise. If app is killed background service will restart, basically its onCreate() will get called and reinitialises every variables.  If your business logic doesn't want this situation, basically if the service is holding some state machine, then we may have to store the state details in a persistent way.

Another way we can ensure service doesn't restart even though app get killed is through notification. We should effectively call startForeground(id, Notification). We can do this in onCreate() of the service. The code snippet is,

  public void onCreate() {
    startForeground(1001, createNotification());

  private Notification createNotification() {
    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("TEXT", "Sample");
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,

    NotificationCompat.Builder notificationBuilder = null;
    try {
        notificationBuilder = new NotificationCompat.Builder(this)
        .setContentTitle(URLDecoder.decode("Title", "UTF-8"))
        .setContentText(URLDecoder.decode("Message", "UTF-8"))
    } catch (Exception e) {

    if (notificationBuilder != null) {
       return notificationBuilder.build();
    } else {
       Log.e(TAG, "Notification builder is null");
       return null;

Happy Coding
Team Androidians


Popular posts from this blog

Open Gallery and get the selected image in appplication

Dismiss or Cancel dialog by swipe gesture

AlarmManager and Notification in Android