首页 > 解决方案 > 多个前台服务的相同通知,如果其中任何一个服务停止,则保留通知

问题描述

我正在创建一个使用两个前台服务的应用程序:

我目前正在使用运行 Nougat 的设备测试我的应用程序,但我想让它准备好奥利奥。

首先,我为每个前台服务使用不同的通知,但后来我想尝试对两者使用相同的通知,就像在这个 SO answer中一样。

如果我通过调用stopService(intent)停止任何这些服务,那么即使另一个foregroundService 仍在运行,通知也会消失。

即使在停止其中一项服务后,有没有办法保留通知?

然后,当两个服务都关闭时,我将手动删除通知

根据要求编辑添加的代码

这就是我的服务的样子(它们基本相同):

public class TrackingService extends Service{

@Override
public void onCreate() {
    startForeground(getNotificationId(), getNotification(this));
    // Some other tracking/server stuff 
}


@Override
public IBinder onBind(Intent intent) {
    return null;
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Some other tracking/server stuff
    return START_STICKY;
}


@Override
public void onDestroy() {
    stopForeground(false);
}

我开始他们:

Intent intent = new Intent(getApplicationContext(), TrackingService.class);
    startService(intent);

然后停止:

Intent intent = new Intent(getApplicationContext(), TrackingService.class);
    stopService(intent);

我读过调用stopService(intent)也会从前台删除该服务。所以调用 tostopForeground(false)是多余的,但我还是留下了它。

通知的单例是:

public abstract class SingleNotificacion {
private static final int NOTIFICATION_ID = 1999;
private static Notification notification;

public static Notification getNotification(Context context) {
    if(notification == null) {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "default")
                .setSmallIcon(R.drawable.ic_stat_notify)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setContentTitle(context.getString(R.string.settings_status_on_summary))
                .setColor(ContextCompat.getColor(context, R.color.colorPrimaryDark));

        notification = builder.build();
    }

    return notification;
}


public static int getNotificationId() {
    return NOTIFICATION_ID;
}

public static void cancelNotification(Context context){
    ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(NOTIFICATION_ID);
}
}

在创建通知时我也尝试设置onGoing(true)和'autoCancel(false)'但没有运气

标签: androidandroid-notificationsforeground-service

解决方案


推荐阅读