How to use NotificationCompat.Builder and startForeground?

android developer picture android developer · Apr 28, 2013 · Viewed 11.6k times · Source

Short question:

I'm trying to use the NotificationCompat.Builder class in order to create a notification that will be used for the service, but for some reason, i either don't see the notification, or can't cancel it when the service should be destroyed (or stopping from being in the foreground) .

my code:

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    final String action = intent == null ? null : intent.getAction();
    Log.d("APP", "service action:" + action);
    if (ACTION_ENABLE_STICKING.equals(action)) {
        final NotificationCompat.Builder builder = new Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle("content title");
        builder.setTicker("ticker");
        builder.setContentText("content text");
        final Intent notificationIntent = new Intent(this, FakeActivity.class);
        final PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        builder.setContentIntent(pi);
        final Notification notification = builder.build();
        // notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
        // notification.flags |= Notification.FLAG_NO_CLEAR;
        // notification.flags |= Notification.FLAG_ONGOING_EVENT;

        startForeground(NOTIFICATION_ID, notification);
        // mNotificationManager.notify(NOTIFICATION_ID, notification);

    } else if (ACTION_DISABLE_STICKING.equals(action)) {
        stopForeground(true);
        stopSelf();
        // mNotificationManager.cancel(NOTIFICATION_ID);
    }
    return super.onStartCommand(intent, flags, startId);
}

The commented commands are my trials to make it work. none worked for some reason.

I even added a fake activity since it wanted a contentIntent , but it still doesn't work.

Can anyone please help?

Answer

Joffrey picture Joffrey · Apr 28, 2013

I had the exact same problem a while ago, and I found out that for some reason, the notification ID 0 doesn't work well with startForeground(), is it the value of NOTIFICATION_ID in your code?


EDIT: the documentation has now been updated to state that 0 is an invalid ID