user1090751
user1090751

Reputation: 336

What is the difference between notificationManager.notify and startForeground in Android?

I am just curious to know what are the differences between NotificationManager.notify and startForeground in Android.

Upvotes: 5

Views: 2289

Answers (1)

Omkar C.
Omkar C.

Reputation: 751

Using NotificationManager.notify you can post as many updates to a notification as you like including adjustments to progress bars via Noticiation.Builder.setProgress in this way you only show one notification to the User, and its the one required by startForeground.

When you want to update a Notification set by startForeground(), simply build a new notication and then use NotificationManager to notify it.

The KEY point is to use the same notification id.

I didn't test the scenario of repeatedly calling startForeground() to update the Notification, but I think that using NotificationManager.notify would be better.

Updating the Notification will not remove the Service from the foreground status (this can be done only by calling stopForground.

Here is an example:

private static final int notif_id=1;

@Override
public void onCreate (){
    this.startForeground();
}

private void startForeground() {
    startForeground(notif_id, getMyActivityNotification(""));
}

private Notification getMyActivityNotification(String text){
    // The PendingIntent to launch our activity if the user selects
    // this notification
    CharSequence title = getText(R.string.title_activity);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0);

    return new Notification.Builder(this)
            .setContentTitle(title)
            .setContentText(text)
            .setSmallIcon(R.drawable.ic_launcher_b3)
            .setContentIntent(contentIntent).getNotification();     
}

/**
 * this is the method that can be called to update the Notification
 */
private void updateNotification() {
    String text = "Some text that will update the notification";

    Notification notification = getMyActivityNotification(text);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(notif_id, notification);
}

You can find more examples and clarification on NotificationManager.notify here

I'd also suggest you to refer this page in order to understand more on startForeground

Usages of startForeground could be found here

Upvotes: 3

Related Questions