2 * Copyright (C) 2019 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.systemui.statusbar;
19 import android.annotation.NonNull;
20 import android.app.Notification;
21 import android.os.Handler;
22 import android.os.Looper;
23 import android.util.ArraySet;
25 import com.android.internal.annotations.VisibleForTesting;
26 import com.android.systemui.statusbar.NotificationData;
29 * Extends the lifetime of foreground notification services such that they show for at least
32 public class ForegroundServiceLifetimeExtender implements NotificationLifetimeExtender {
33 private static final String TAG = "FGSLifetimeExtender";
36 public static final int MIN_FGS_TIME_MS = 5000;
38 private NotificationSafeToRemoveCallback mNotificationSafeToRemoveCallback;
39 private ArraySet<NotificationData.Entry> mManagedEntries = new ArraySet<>();
40 private Handler mHandler = new Handler(Looper.getMainLooper());
42 public ForegroundServiceLifetimeExtender() {
46 public void setCallback(@NonNull NotificationSafeToRemoveCallback callback) {
47 mNotificationSafeToRemoveCallback = callback;
51 public boolean shouldExtendLifetime(@NonNull NotificationData.Entry entry) {
52 if ((entry.notification.getNotification().flags
53 & Notification.FLAG_FOREGROUND_SERVICE) == 0) {
56 long currentTime = System.currentTimeMillis();
57 return currentTime - entry.notification.getPostTime() < MIN_FGS_TIME_MS;
61 public boolean shouldExtendLifetimeForPendingNotification(
62 @NonNull NotificationData.Entry entry) {
63 return shouldExtendLifetime(entry);
67 public void setShouldManageLifetime(
68 @NonNull NotificationData.Entry entry, boolean shouldManage) {
69 android.util.Log.d("FGSExtender", "setShouldManageLifetime " + shouldManage);
71 mManagedEntries.remove(entry);
74 mManagedEntries.add(entry);
76 if (mManagedEntries.contains(entry)) {
77 mManagedEntries.remove(entry);
78 if (mNotificationSafeToRemoveCallback != null) {
79 mNotificationSafeToRemoveCallback.onSafeToRemove(entry.key);
83 long delayAmt = MIN_FGS_TIME_MS
84 - (System.currentTimeMillis() - entry.notification.getPostTime());
85 mHandler.postDelayed(r, delayAmt);