14

我创建了一个发送电子邮件的服务(EmailService)......每次我需要使用我的应用程序发送电子邮件时,它都会启动服务并通过意图传递电子邮件的ID......

startforeground(id_of_email, mynotifcation);用来防止它被杀死并向用户显示电子邮件发送状态的通知。

我需要允许用户同时发送多封电子邮件,因此当用户需要发送另一封电子邮件时,它会再次startservice以新的意图(电子邮件的不同 ID)调用......所以它startforeground(new_id_of_email, mynotifcation);再次调用。

问题是新的呼叫startforeground覆盖了以前的通知......(所以用户丢失了以前的通知并且不知道他以前的电子邮件发生了什么)

4

3 回答 3

6

查看Service.startForeground()源代码显示多次调用 startForeground 只会替换当前显示的通知。实际上,对 startForeground 的调用与 相同stopForeground(),只是removeNotificationset 始终设置为 true。

如果您希望您的服务显示正在处理的每封电子邮件的通知,您将必须从该服务单独管理每个通知。

public final void startForeground(int id, Notification notification) {
    try {
        mActivityManager.setServiceForeground(
                new ComponentName(this, mClassName), mToken, id,
                notification, true);
    } catch (RemoteException ex) {
    }
}

public final void stopForeground(boolean removeNotification) {
    try {
        mActivityManager.setServiceForeground(
                new ComponentName(this, mClassName), mToken, 0, 
                null, removeNotification);
    } catch (RemoteException ex) {
    }
}

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.3_r1/android/app/Service.java#Service.startForeground%28int%2Candroid.app.Notification %29

于 2015-02-26T00:02:27.313 回答
2

也可以使用STOP_FOREGROUND_DETACH标志。

引用文档

STOP_FOREGROUND_DETACH

在 API 级别 24 中添加 int STOP_FOREGROUND_DETACH 用于 stopForeground(int) 的标志:如果设置,则先前提供给 startForeground(int, Notification) 的通知将与服务分离。仅在未设置 STOP_FOREGROUND_REMOVE 时才有意义——在这种情况下,通知将保持显示,但与服务完全分离,因此不再更改,除非通过直接调用通知管理器。

常数值:2 (0x00000002)

因此,在重复调用之前,startForeground()您可以调用stopForeground(STOP_FOREGROUND_DETACH);. 如果您使用不同的通知 ID ,这将分离通知并且重复调用startForeground()不会对其进行修改。

此外,“分离”通知现在不代表“正在进行的服务”,因此用户可以通过滑动将其删除。

奖金 :

为了兼容性,可以使用此处记录ServiceCompat的类及其static方法。ServiceCompat.stopForeground(MyService.this, STOP_FOREGROUND_DETACH)

于 2017-11-02T07:37:31.227 回答
0

我根据@zeekhuge 的回答创建了一个实用程序类来管理前台服务通知。您可以在此处找到代码段:https ://stackoverflow.com/a/62604739/4522359

于 2020-06-27T01:15:38.350 回答