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,


  @Override
  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,


  @Override
  public void onCreate() {
    super.onCreate();
    startForeground(1001, createNotification());
  }

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

    NotificationCompat.Builder notificationBuilder = null;
    try {
        notificationBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle(URLDecoder.decode("Title", "UTF-8"))
        .setContentText(URLDecoder.decode("Message", "UTF-8"))
        .setAutoCancel(true)
        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
        .setContentIntent(pendingIntent);
    } catch (Exception e) {
            e.printStackTrace();
    }

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

Happy Coding
Team Androidians

Comments

Popular posts from this blog

Open Gallery and get the selected image in appplication

AlarmManager and Notification in Android

Dismiss or Cancel dialog by swipe gesture