15

在我的应用程序中,我将我的服务放在前台,以防止它被使用:

startForeground(NOTIFY_ID, notification);

这也会向用户显示通知(这很棒)。问题是稍后我需要更新通知。所以我使用代码:

notification.setLatestEventInfo(getApplicationContext(), someString, someOtherString, contentIntent);
mNotificationManager.notify(NOTIFY_ID, notification);

那么问题是:这样做会将服务从其特殊的前台状态中剔除吗?

这个答案中,CommonsWare表示这种行为是可能的,但他不确定。那么有人知道实际答案吗?


注意:我知道摆脱这个问题的一个简单方法是startForeground()每次我想更新通知时重复调用。我想知道这种替代方案是否也有效。

4

3 回答 3

13

为了澄清这里所说的:

据我了解,如果您取消通知,该服务将不再是前台服务,因此请记住这一点;如果取消通知,则需要再次调用 startForeground() 来恢复服务的前台状态。

这部分答案表明可以通过在 persistent 上使用Notificationa 来删除正在进行的集合。这不是真的。使用 删除正在进行的通知集是不可能的。ServiceNotificationManager.cancel()NotificationstartForeground()NotificationManager.cancel()

删除它的唯一方法是调用stopForeground(true),因此正在进行的通知被删除,这当然也使Service停止在前台。所以实际上是相反的;Service不会因为被取消而停止在前台,Notification只能Notification通过停止Service在前台来取消。

自然可以startForeground()马上调用,用新的Notification. 如果必须再次显示代码文本,您想要这样做的一个原因是,它只会在第一次Notification显示时运行。

这种行为没有记录,我浪费了 4 个小时试图弄清楚为什么我无法删除Notification. 更多关于这里的问题:NotificationManager.cancel() 对我不起作用

于 2012-07-09T07:33:58.117 回答
12

Android 开发者网站上的RandomMusicPlayer (已归档)应用程序使用 NotificationManager 来更新前台服务的通知,因此它保留前台状态的可能性很大。

(参见MusicService.java 类中的 setUpAsForeground()updateNotification()。)

据我了解,如果您取消通知,该服务将不再是前台服务,因此请记住这一点;如果取消通知,则需要再次调用 startForeground() 来恢复服务的前台状态。

于 2011-12-07T22:52:27.530 回答
5

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

关键是使用相同的通知ID。

更新通知不会将服务从前台状态中删除(这只能通过调用 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);
}
于 2013-11-22T10:23:14.830 回答