在Android中,notificationManager.notify和startForeground有什么区别?

5

我只是好奇了解在Android中NotificationManager.notifystartForeground之间有什么区别。


在我们的前台服务案例中,如果服务没有其他通知(因为至少需要一个通知来保持其活动状态),我们使用 startForeground 方法,否则我们只需使用 NotificationManagerCompat.from(serviceContext).notify(myId, builder.build()); 技术进行更新。 - Top-Master
例如,Android的VpnService在断开连接之前提供自己的通知,但是如果您需要该服务保持活动状态以执行其他任务,即使VPN已断开连接,您需要使用startForeground方法(如果服务在后台运行而没有任何打开的活动),但只需第一次更新后使用NotificationManager - Top-Master
1个回答

3
使用NotificationManager.notify,您可以发布任意数量的通知更新,包括通过Noticiation.Builder.setProgress调整进度条。这样,您只向用户显示一个通知,并且它是由startForeground所需的通知。
当您想要更新由startForeground()设置的通知时,只需构建一个新的通知,然后使用NotificationManager通知它即可。
关键点是使用相同的通知ID。
我没有测试反复调用startForeground()以更新通知的情况,但我认为使用NotificationManager.notify会更好。
更新通知不会将服务从前台状态中删除(只能通过调用stopForground来完成此操作)。
以下是示例:
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);
}

您可以在这里找到更多有关NotificationManager.notify的例子和解释。
我还建议您参考此页面以了解更多关于startForeground的内容。 startForeground的用法可以在这里找到。

1
前几天我在查看我们支持的一个应用程序时,注意到它经常调用startForeground来更新通知,而没有任何问题。因此,似乎startForeground和notificationManager.notify表现类似(至少从用户的角度来看是这样)。 - denver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接