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;
}