2011-09-14

Android ongoing notifications for foreground services

It took several hours to find the solution for my issue, so I describe it for you.

Issue
The ongoing notification will only shortly be displayed in the notification center, then it disappears.
Solution
The following key points must be fulfilled
- Override, onStartCommand in your service, don't try to use onHandleIntent()
- Don't call super.onStartCommand()
- Return START_STICKY
- Use proper icons as described in the user guide

public int onStartCommand(Intent intent, int flags, int startId) {
	Notification notification = new Notification(R.drawable.status_bar_icon, "text", System.currentTimeMillis());

	Intent main = new Intent(this, Main.class);
	main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
	PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main,	PendingIntent.FLAG_UPDATE_CURRENT);

	notification.setLatestEventInfo(this, "title", "text", pendingIntent);
	notification.flags |= Notification.FLAG_ONGOING_EVENT |	Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;

	startForeground(2, notification);

	return START_STICKY;
}

7 comments:

  1. Anonymous15/3/13 19:43

    Hmm all fine, but i suppose this should be set in onCretead() instead.

    ReplyDelete
    Replies
    1. Anonymous6/4/13 04:42

      Because onStartCommand can be called more than once.

      Delete
  2. Anonymous21/5/14 10:25

    Good suggestion....

    ReplyDelete
  3. how to update some title on notification is running in Foreground ?

    ReplyDelete
  4. What happens if we return START_NOT_STICKY in case of start service in Foreground

    ReplyDelete
  5. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete