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

Android中notificationManager.notify和startForeground有什么区别?,android,notifications,Android,Notifications,我只是想知道Android中notificationManager.notify和startForeground之间有什么区别。使用,您可以发布任意数量的通知更新,包括对进度条的调整,通过这种方式,您只向用户显示一条通知,它是startForeground所要求的 当您想要更新startForeground()设置的通知时,只需构建一个新的通知,然后使用NotificationManager来通知它 关键是使用相同的通知id 我没有测试重复调用startForeground()来更新通知的场景,

我只是想知道Android中notificationManager.notify和startForeground之间有什么区别。

使用,您可以发布任意数量的通知更新,包括对进度条的调整,通过这种方式,您只向用户显示一条通知,它是
startForeground
所要求的

当您想要更新startForeground()设置的通知时,只需构建一个新的通知,然后使用NotificationManager来通知它

关键是使用相同的通知id

我没有测试重复调用
startForeground()
来更新通知的场景,但我认为使用
NotificationManager.notify
会更好

更新通知不会将服务从前台状态删除(这只能通过调用
stopforgfround
来完成)

以下是一个例子:

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
的用法可以在我们的前台服务案例中找到

如果服务没有其他通知(因为至少需要一个通知才能使其保持活动状态),我们就使用
startForeground
,否则我们只需使用
NotificationManagerCompat.from(serviceContext.notify)(myId,builder.build())更新
技术。例如,Android的
VPN服务在断开连接之前提供自己的通知,但如果您需要为其他任务激活服务,即使VPN断开连接,您也需要使用
startForeground
方法(如果服务在后台运行,没有任何活动打开),但这只是第一次,稍后使用
NotificationManager
进行更新。前几天,我们正在查看一个我们支持的应用程序,并注意到它定期调用startForeground来更新通知,而没有任何问题。因此,startForeground和NotificationManager.notify的行为似乎类似(至少在用户看来)。