android - 多个前台服务的相同通知,如果其中任何一个服务停止,则保留通知
问题描述
我正在创建一个使用两个前台服务的应用程序:
- 一种用于获取位置
- 另一个将其上传到服务器(每 30 秒)
我目前正在使用运行 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)'但没有运气
解决方案
推荐阅读
- algorithm - 斐波那契搜索与二分搜索相比的时间复杂度
- python - 如何在 MultiIndex Groupby 中高效地执行乘法
- meson-build - 如何使用介子构建系统将多个转换规则应用于文件列表
- node.js - DiscordJS reactCollector 'remove' 永远不会发出
- python - 使用 Python 进行多处理
- json - 使用 JQ 到特定的 csv 格式
- c# - 根据对象的属性生成唯一的字符串键(cachekey)
- raspbian - 当我尝试在我的树莓派 3 上安装 PyQtWebEngine 时出错
- python - python Parralize 在函数内部并返回字典
- python - Python:数据类的唯一整数?