我正在创建一个使用两个前台服务的应用程序:
我目前正在使用运行Nougat的设备测试我的应用程序,但我想使其适合Oreo。
首先,我为每个前台服务使用了一个不同的Notification,但是后来我想尝试为this SO answer使用相同的通知。
如果我通过调用 stopService(intent)停止了其中任何一项服务,那么即使另一个前台服务仍在运行,该通知也会消失。
即使停止其中一项服务后,是否仍可以保留通知?
然后,当两个服务都关闭时,我将手动删除通知
这是我的服务的样子(它们基本上是相同的):
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)
也会从前台删除该服务。因此,对stopForeground(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)'