Merge "Allow companion apps to start background activities from PendingIntents (even if they aren't foreground)"
diff --git a/Android.bp b/Android.bp
index b9b1bd8..5b8e6e1 100644
--- a/Android.bp
+++ b/Android.bp
@@ -375,6 +375,7 @@
         "core/java/android/view/IDisplayFoldListener.aidl",
         "core/java/android/view/IGraphicsStats.aidl",
         "core/java/android/view/IGraphicsStatsCallback.aidl",
+        "core/java/android/view/IInputMonitorHost.aidl",
         "core/java/android/view/IInputFilter.aidl",
         "core/java/android/view/IInputFilterHost.aidl",
         "core/java/android/view/IOnKeyguardExitResult.aidl",
diff --git a/api/current.txt b/api/current.txt
index 1394ba3..d4a1554 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -34275,6 +34275,7 @@
     ctor public Binder(@Nullable String);
     method public void attachInterface(@Nullable android.os.IInterface, @Nullable String);
     method public static final long clearCallingIdentity();
+    method public static final long clearCallingWorkSource();
     method public void dump(@NonNull java.io.FileDescriptor, @Nullable String[]);
     method protected void dump(@NonNull java.io.FileDescriptor, @NonNull java.io.PrintWriter, @Nullable String[]);
     method public void dumpAsync(@NonNull java.io.FileDescriptor, @Nullable String[]);
@@ -34283,6 +34284,7 @@
     method public static final int getCallingUid();
     method public static final int getCallingUidOrThrow();
     method @NonNull public static final android.os.UserHandle getCallingUserHandle();
+    method public static final int getCallingWorkSourceUid();
     method @Nullable public String getInterfaceDescriptor();
     method public boolean isBinderAlive();
     method public static final void joinThreadPool();
@@ -34291,6 +34293,8 @@
     method public boolean pingBinder();
     method @Nullable public android.os.IInterface queryLocalInterface(@NonNull String);
     method public static final void restoreCallingIdentity(long);
+    method public static final void restoreCallingWorkSource(long);
+    method public static final long setCallingWorkSourceUid(int);
     method public final boolean transact(int, @NonNull android.os.Parcel, @Nullable android.os.Parcel, int) throws android.os.RemoteException;
     method public boolean unlinkToDeath(@NonNull android.os.IBinder.DeathRecipient, int);
   }
@@ -37069,12 +37073,6 @@
     field public static final String CACHED_NUMBER_TYPE = "numbertype";
     field public static final String CACHED_PHOTO_ID = "photo_id";
     field public static final String CACHED_PHOTO_URI = "photo_uri";
-    field public static final String CALL_ID_APP_NAME = "call_id_app_name";
-    field public static final String CALL_ID_DESCRIPTION = "call_id_description";
-    field public static final String CALL_ID_DETAILS = "call_id_details";
-    field public static final String CALL_ID_NAME = "call_id_name";
-    field public static final String CALL_ID_NUISANCE_CONFIDENCE = "call_id_nuisance_confidence";
-    field public static final String CALL_ID_PACKAGE_NAME = "call_id_package_name";
     field public static final String CALL_SCREENING_APP_NAME = "call_screening_app_name";
     field public static final String CALL_SCREENING_COMPONENT_NAME = "call_screening_component_name";
     field public static final android.net.Uri CONTENT_FILTER_URI;
@@ -43257,7 +43255,6 @@
     method public android.telecom.PhoneAccountHandle getAccountHandle();
     method public int getCallCapabilities();
     method public int getCallDirection();
-    method @Nullable public android.telecom.CallIdentification getCallIdentification();
     method public int getCallProperties();
     method public String getCallerDisplayName();
     method public int getCallerDisplayNamePresentation();
@@ -43339,34 +43336,6 @@
     field public static final int ROUTE_WIRED_OR_EARPIECE = 5; // 0x5
   }
 
-  public final class CallIdentification implements android.os.Parcelable {
-    method public int describeContents();
-    method @NonNull public CharSequence getCallScreeningAppName();
-    method @NonNull public String getCallScreeningPackageName();
-    method @Nullable public CharSequence getDescription();
-    method @Nullable public CharSequence getDetails();
-    method @Nullable public CharSequence getName();
-    method public int getNuisanceConfidence();
-    method @Nullable public android.graphics.drawable.Icon getPhoto();
-    method public void writeToParcel(android.os.Parcel, int);
-    field public static final int CONFIDENCE_LIKELY_NOT_NUISANCE = -1; // 0xffffffff
-    field public static final int CONFIDENCE_LIKELY_NUISANCE = 1; // 0x1
-    field public static final int CONFIDENCE_NOT_NUISANCE = -2; // 0xfffffffe
-    field public static final int CONFIDENCE_NUISANCE = 2; // 0x2
-    field public static final int CONFIDENCE_UNKNOWN = 0; // 0x0
-    field @NonNull public static final android.os.Parcelable.Creator<android.telecom.CallIdentification> CREATOR;
-  }
-
-  public static final class CallIdentification.Builder {
-    ctor public CallIdentification.Builder();
-    method @NonNull public android.telecom.CallIdentification build();
-    method @NonNull public android.telecom.CallIdentification.Builder setDescription(@Nullable CharSequence);
-    method @NonNull public android.telecom.CallIdentification.Builder setDetails(@Nullable CharSequence);
-    method @NonNull public android.telecom.CallIdentification.Builder setName(@Nullable CharSequence);
-    method @NonNull public android.telecom.CallIdentification.Builder setNuisanceConfidence(int);
-    method @NonNull public android.telecom.CallIdentification.Builder setPhoto(@Nullable android.graphics.drawable.Icon);
-  }
-
   public abstract class CallRedirectionService extends android.app.Service {
     ctor public CallRedirectionService();
     method public final void cancelCall();
@@ -43382,17 +43351,7 @@
     ctor public CallScreeningService();
     method public android.os.IBinder onBind(android.content.Intent);
     method public abstract void onScreenCall(@NonNull android.telecom.Call.Details);
-    method public final void provideCallIdentification(@NonNull android.telecom.Call.Details, @NonNull android.telecom.CallIdentification);
     method public final void respondToCall(@NonNull android.telecom.Call.Details, @NonNull android.telecom.CallScreeningService.CallResponse);
-    field public static final String ACTION_NUISANCE_CALL_STATUS_CHANGED = "android.telecom.action.NUISANCE_CALL_STATUS_CHANGED";
-    field public static final int CALL_DURATION_LONG = 4; // 0x4
-    field public static final int CALL_DURATION_MEDIUM = 3; // 0x3
-    field public static final int CALL_DURATION_SHORT = 2; // 0x2
-    field public static final int CALL_DURATION_VERY_SHORT = 1; // 0x1
-    field public static final String EXTRA_CALL_DURATION = "android.telecom.extra.CALL_DURATION";
-    field public static final String EXTRA_CALL_HANDLE = "android.telecom.extra.CALL_HANDLE";
-    field public static final String EXTRA_CALL_TYPE = "android.telecom.extra.CALL_TYPE";
-    field public static final String EXTRA_IS_NUISANCE = "android.telecom.extra.IS_NUISANCE";
     field public static final String SERVICE_INTERFACE = "android.telecom.CallScreeningService";
   }
 
@@ -44001,7 +43960,6 @@
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public boolean isVoiceMailNumber(android.telecom.PhoneAccountHandle, String);
     method @RequiresPermission(anyOf={android.Manifest.permission.CALL_PHONE, android.Manifest.permission.MANAGE_OWN_CALLS}) public void placeCall(android.net.Uri, android.os.Bundle);
     method public void registerPhoneAccount(android.telecom.PhoneAccount);
-    method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public void reportNuisanceCallStatus(@NonNull android.net.Uri, boolean);
     method @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE) public void showInCallScreen(boolean);
     method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void silenceRinger();
     method public void unregisterPhoneAccount(android.telecom.PhoneAccountHandle);
diff --git a/api/system-current.txt b/api/system-current.txt
index 9609cc0..d1018be 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -1462,7 +1462,7 @@
     method @Nullable public String getCategory();
     method @NonNull public String getPackageName();
     method @Nullable public String getTargetOverlayableName();
-    method @Nullable public String getTargetPackageName();
+    method @NonNull public String getTargetPackageName();
     method public int getUserId();
     method public boolean isEnabled();
     method public void writeToParcel(android.os.Parcel, int);
@@ -5143,10 +5143,6 @@
   }
 
   public class Binder implements android.os.IBinder {
-    method public static final long clearCallingWorkSource();
-    method public static final int getCallingWorkSourceUid();
-    method public static final void restoreCallingWorkSource(long);
-    method public static final long setCallingWorkSourceUid(int);
     method public static void setProxyTransactListener(@Nullable android.os.Binder.ProxyTransactListener);
   }
 
diff --git a/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java b/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
index 98ab666..680ccfc 100644
--- a/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
+++ b/cmds/bmgr/src/com/android/commands/bmgr/Bmgr.java
@@ -112,6 +112,11 @@
             return;
         }
 
+        if ("activated".equals(op)) {
+            doActivated(userId);
+            return;
+        }
+
         if (!isBackupActive(userId)) {
             return;
         }
@@ -200,6 +205,21 @@
         return true;
     }
 
+    private String activatedToString(boolean activated) {
+        return activated ? "activated" : "deactivated";
+    }
+
+    private void doActivated(@UserIdInt int userId) {
+        try {
+            System.out.println("Backup Manager currently "
+                    + activatedToString(mBmgr.isBackupServiceActive(userId)));
+        } catch (RemoteException e) {
+            System.err.println(e.toString());
+            System.err.println(BMGR_NOT_RUNNING_ERR);
+        }
+
+    }
+
     private String enableToString(boolean enabled) {
         return enabled ? "enabled" : "disabled";
     }
@@ -907,6 +927,7 @@
         System.err.println("       bmgr cancel backups");
         System.err.println("       bmgr init TRANSPORT...");
         System.err.println("       bmgr activate BOOL");
+        System.err.println("       bmgr activated");
         System.err.println("");
         System.err.println("The '--user' option specifies the user on which the operation is run.");
         System.err.println("It must be the first argument before the operation.");
@@ -978,6 +999,9 @@
         System.err.println("If the argument is 'true' it will be activated, otherwise it will be");
         System.err.println("deactivated. When deactivated, the service will not be running and no");
         System.err.println("operations can be performed until activation.");
+        System.err.println("");
+        System.err.println("The 'activated' command reports the current activated/deactivated");
+        System.err.println("state of the backup mechanism.");
     }
 
     private static class BackupMonitor extends IBackupManagerMonitor.Stub {
diff --git a/cmds/incidentd/src/Broadcaster.cpp b/cmds/incidentd/src/Broadcaster.cpp
index 39e5393..63464f2 100644
--- a/cmds/incidentd/src/Broadcaster.cpp
+++ b/cmds/incidentd/src/Broadcaster.cpp
@@ -22,6 +22,7 @@
 
 #include <android/os/DropBoxManager.h>
 #include <binder/IServiceManager.h>
+#include <thread>
 
 namespace android {
 namespace os {
@@ -391,13 +392,20 @@
         return NO_ERROR;
     }
 
-    // Start a thread to write the data to dropbox.
-    int readFd = -1;
-    err = file->startFilteringData(&readFd, args);
-    if (err != NO_ERROR) {
-        return err;
+    int fds[2];
+    if (pipe(fds) != 0) {
+        ALOGW("Error opening pipe to filter incident report: %s", file->getDataFileName().c_str());
+        return NO_ERROR;
     }
 
+    int readFd = fds[0];
+    int writeFd = fds[1];
+
+    // spawn a thread to write the data. Release the writeFd ownership to the thread.
+    thread th([file, writeFd, args]() { file->startFilteringData(writeFd, args); });
+
+    th.detach();
+
     // Takes ownership of readFd.
     Status status = dropbox->addFile(String16("incident"), readFd, 0);
     if (!status.isOk()) {
diff --git a/cmds/incidentd/src/IncidentService.cpp b/cmds/incidentd/src/IncidentService.cpp
index 4ba31b4..b4021d1 100644
--- a/cmds/incidentd/src/IncidentService.cpp
+++ b/cmds/incidentd/src/IncidentService.cpp
@@ -32,6 +32,7 @@
 #include <log/log.h>
 #include <private/android_filesystem_config.h>
 #include <utils/Looper.h>
+#include <thread>
 
 #include <unistd.h>
 
@@ -117,7 +118,8 @@
 }
 
 static string build_uri(const string& pkg, const string& cls, const string& id) {
-    return "build_uri not implemented " + pkg + "/" + cls + "/" + id;
+    return "content://android.os.IncidentManager/pending?pkg="
+        + pkg + "&receiver=" + cls + "&r=" + id;
 }
 
 // ================================================================================
@@ -358,17 +360,21 @@
     IncidentReportArgs args;
     sp<ReportFile> file = mWorkDirectory->getReport(pkg, cls, id, &args);
     if (file != nullptr) {
-        int fd;
-        err = file->startFilteringData(&fd, args);
-        if (err != 0) {
-            ALOGW("Error reading data file that we think should exist: %s",
-                    file->getDataFileName().c_str());
+        // Create pipe
+        int fds[2];
+        if (pipe(fds) != 0) {
+            ALOGW("Error opening pipe to filter incident report: %s",
+                  file->getDataFileName().c_str());
             return Status::ok();
         }
-
         result->setTimestampNs(file->getTimestampNs());
         result->setPrivacyPolicy(file->getEnvelope().privacy_policy());
-        result->takeFileDescriptor(fd);
+        result->takeFileDescriptor(fds[0]);
+        int writeFd = fds[1];
+        // spawn a thread to write the data. Release the writeFd ownership to the thread.
+        thread th([file, writeFd, args]() { file->startFilteringData(writeFd, args); });
+
+        th.detach();
     }
 
     return Status::ok();
diff --git a/cmds/incidentd/src/Reporter.cpp b/cmds/incidentd/src/Reporter.cpp
index e773e74..218c1b2 100644
--- a/cmds/incidentd/src/Reporter.cpp
+++ b/cmds/incidentd/src/Reporter.cpp
@@ -551,7 +551,7 @@
              buf++) {
             // If there was an error now, there will be an error later and we will remove
             // it from the list then.
-            write_header_section(request->getFd(), *buf);
+            write_header_section(request->getFd(), buf->data(), buf->size());
         }
     });
 
diff --git a/cmds/incidentd/src/WorkDirectory.cpp b/cmds/incidentd/src/WorkDirectory.cpp
index aa376dd..ae640c6 100644
--- a/cmds/incidentd/src/WorkDirectory.cpp
+++ b/cmds/incidentd/src/WorkDirectory.cpp
@@ -18,6 +18,7 @@
 
 #include "WorkDirectory.h"
 
+#include "proto_util.h"
 #include "PrivacyFilter.h"
 
 #include <google/protobuf/io/zero_copy_stream_impl.h>
@@ -64,6 +65,9 @@
  */
 const ComponentName DROPBOX_SENTINEL("android", "DROPBOX");
 
+/** metadata field id in IncidentProto */
+const int FIELD_ID_INCIDENT_METADATA = 2;
+
 /**
  * Read a protobuf from disk into the message.
  */
@@ -386,65 +390,53 @@
     }
 }
 
-status_t ReportFile::startFilteringData(int* fd, const IncidentReportArgs& args) {
+status_t ReportFile::startFilteringData(int writeFd, const IncidentReportArgs& args) {
     // Open data file.
     int dataFd = open(mDataFileName.c_str(), O_RDONLY | O_CLOEXEC);
     if (dataFd < 0) {
+        ALOGW("Error opening incident report '%s' %s", getDataFileName().c_str(), strerror(-errno));
+        close(writeFd);
         return -errno;
     }
 
     // Check that the size on disk is what we thought we wrote.
     struct stat st;
     if (fstat(dataFd, &st) != 0) {
+        ALOGW("Error running fstat incident report '%s' %s", getDataFileName().c_str(),
+              strerror(-errno));
+        close(writeFd);
         return -errno;
     }
     if (st.st_size != mEnvelope.data_file_size()) {
         ALOGW("File size mismatch. Envelope says %" PRIi64 " bytes but data file is %" PRIi64
-                " bytes: %s", (int64_t)mEnvelope.data_file_size(), st.st_size,
-                mDataFileName.c_str());
+              " bytes: %s",
+              (int64_t)mEnvelope.data_file_size(), st.st_size, mDataFileName.c_str());
         ALOGW("Removing incident report");
         mWorkDirectory->remove(this);
+        close(writeFd);
         return BAD_VALUE;
     }
 
-    // Create pipe
-    int fds[2];
-    if (pipe(fds) != 0) {
-        ALOGW("Error opening pipe to filter incident report: %s", getDataFileName().c_str());
-        return -errno;
+    status_t err;
+
+    for (const auto& report : mEnvelope.report()) {
+        for (const auto& header : report.header()) {
+           write_header_section(writeFd,
+               reinterpret_cast<const uint8_t*>(header.c_str()), header.size());
+        }
     }
 
-    *fd = fds[0];
-    int writeFd = fds[1];
+    if (mEnvelope.has_metadata()) {
+        write_section(writeFd, FIELD_ID_INCIDENT_METADATA, mEnvelope.metadata());
+    }
 
-    // Spawn off a thread to do the filtering and writing
-    thread th([this, dataFd, writeFd, args]() {
-        ALOGD("worker thread started dataFd=%d writeFd=%d", dataFd, writeFd);
-        status_t err;
+    err = filter_and_write_report(writeFd, dataFd, mEnvelope.privacy_policy(), args);
+    if (err != NO_ERROR) {
+        ALOGW("Error writing incident report '%s' to dropbox: %s", getDataFileName().c_str(),
+                strerror(-err));
+    }
 
-        err = filter_and_write_report(writeFd, dataFd, mEnvelope.privacy_policy(), args);
-        close(writeFd);
-
-        if (err != NO_ERROR) {
-            ALOGW("Error writing incident report '%s' to dropbox: %s", getDataFileName().c_str(),
-                    strerror(-err));
-            // If there's an error here, there will also be an error returned from
-            // addFile, so we'll use that error to reschedule the send_to_dropbox.
-            // If the file is corrupted, we will put some logs in logcat, but won't
-            // actually return an error.
-            return;
-        }
-    });
-
-    // Better would be to join this thread after write is back, but there is no
-    // timeout parameter for that, which means we can't clean up if system server
-    // is stuck. Better is to leak the thread, which will eventually clean itself
-    // up after system server eventually dies, which it probably will.
-    th.detach();
-
-    // If the thread fails to start, we should return an error, but the thread
-    // class doesn't give us a good way to determine that.  Just pretend everything
-    // is ok.
+    close(writeFd);
     return NO_ERROR;
 }
 
@@ -501,7 +493,7 @@
 
 
 // ================================================================================
-// 
+//
 
 WorkDirectory::WorkDirectory()
         :mDirectory("/data/misc/incidents"),
diff --git a/cmds/incidentd/src/WorkDirectory.h b/cmds/incidentd/src/WorkDirectory.h
index e344371..3c6a2f2 100644
--- a/cmds/incidentd/src/WorkDirectory.h
+++ b/cmds/incidentd/src/WorkDirectory.h
@@ -135,14 +135,14 @@
     void closeDataFile();
 
     /**
-     * Spawn a thread to start writing and filtering data to a pipe, the read end of which
-     * will be returned in fd.  This thread will be detached and run until somebody finishes
-     * reading from the fd or closes it.  If there is an error, returns it and you will not
-     * get an fd.
+     * Use the privacy and section configuration from the args parameter to filter data, write
+     * to [writeFd] and take the ownership of [writeFd].
      *
-     * Use the privacy and section configuraiton from the args parameter.
+     * Note: this call is blocking. When the writeFd is a pipe fd for IPC, caller should make sure
+     * it's called on a separate thread so that reader can start to read without waiting for writer
+     * to finish writing (which may not happen due to pipe buffer overflow).
      */
-    status_t startFilteringData(int* fd, const IncidentReportArgs& args);
+    status_t startFilteringData(int writeFd, const IncidentReportArgs& args);
 
     /**
      * Get the name of the data file on disk.
diff --git a/cmds/incidentd/src/proto_util.cpp b/cmds/incidentd/src/proto_util.cpp
index be2f24f..4e8ff71 100644
--- a/cmds/incidentd/src/proto_util.cpp
+++ b/cmds/incidentd/src/proto_util.cpp
@@ -33,11 +33,10 @@
 // special section ids
 const int FIELD_ID_INCIDENT_HEADER = 1;
 
-status_t write_header_section(int fd, const vector<uint8_t>& buf) {
+status_t write_header_section(int fd, const uint8_t* buf, size_t bufSize) {
     status_t err;
-    const size_t bufSize = buf.size();
 
-    if (buf.empty()) {
+    if (bufSize == 0) {
         return NO_ERROR;
     }
 
@@ -46,7 +45,7 @@
         return err;
     }
 
-    err = WriteFully(fd, (uint8_t const*)buf.data(), bufSize);
+    err = WriteFully(fd, buf, bufSize);
     if (err != NO_ERROR) {
         return err;
     }
diff --git a/cmds/incidentd/src/proto_util.h b/cmds/incidentd/src/proto_util.h
index b9df6cb..2c0ab48 100644
--- a/cmds/incidentd/src/proto_util.h
+++ b/cmds/incidentd/src/proto_util.h
@@ -32,7 +32,7 @@
 /**
  * Write the IncidentHeaderProto section
  */
-status_t write_header_section(int fd, const vector<uint8_t>& buf);
+status_t write_header_section(int fd, const uint8_t* buf, size_t bufSize);
 
 /**
  * Write the prologue for a section in the incident report
diff --git a/cmds/statsd/src/StatsLogProcessor.h b/cmds/statsd/src/StatsLogProcessor.h
index 8de1881..305a4ce 100644
--- a/cmds/statsd/src/StatsLogProcessor.h
+++ b/cmds/statsd/src/StatsLogProcessor.h
@@ -66,7 +66,7 @@
 
     void onDumpReport(const ConfigKey& key, const int64_t dumpTimeNs,
                       const bool include_current_partial_bucket, const bool erase_data,
-                      const DumpReportReason dumpReportReason, 
+                      const DumpReportReason dumpReportReason,
                       const DumpLatency dumpLatency,
                       vector<uint8_t>* outData);
     void onDumpReport(const ConfigKey& key, const int64_t dumpTimeNs,
@@ -260,6 +260,9 @@
     FRIEND_TEST(AlarmE2eTest, TestMultipleAlarms);
     FRIEND_TEST(ConfigTtlE2eTest, TestCountMetric);
     FRIEND_TEST(MetricActivationE2eTest, TestCountMetric);
+    FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithOneDeactivation);
+    FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithTwoDeactivations);
+    FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithTwoMetricsTwoDeactivations);
 };
 
 }  // namespace statsd
diff --git a/cmds/statsd/src/metrics/MetricProducer.cpp b/cmds/statsd/src/metrics/MetricProducer.cpp
index 4cf5333..5ed95ed 100644
--- a/cmds/statsd/src/metrics/MetricProducer.cpp
+++ b/cmds/statsd/src/metrics/MetricProducer.cpp
@@ -70,11 +70,11 @@
 bool MetricProducer::evaluateActiveStateLocked(int64_t elapsedTimestampNs) {
     bool isActive = mEventActivationMap.empty();
     for (auto& it : mEventActivationMap) {
-        if (it.second.state == ActivationState::kActive &&
-            elapsedTimestampNs > it.second.ttl_ns + it.second.activation_ns) {
-            it.second.state = ActivationState::kNotActive;
+        if (it.second->state == ActivationState::kActive &&
+            elapsedTimestampNs > it.second->ttl_ns + it.second->activation_ns) {
+            it.second->state = ActivationState::kNotActive;
         }
-        if (it.second.state == ActivationState::kActive) {
+        if (it.second->state == ActivationState::kActive) {
             isActive = true;
         }
     }
@@ -92,7 +92,8 @@
     }
 }
 
-void MetricProducer::addActivation(int activationTrackerIndex, int64_t ttl_seconds) {
+void MetricProducer::addActivation(int activationTrackerIndex, int64_t ttl_seconds,
+                                   int deactivationTrackerIndex) {
     std::lock_guard<std::mutex> lock(mMutex);
     // When a metric producer does not depend on any activation, its mIsActive is true.
     // Therefore, if this is the 1st activation, mIsActive will turn to false. Otherwise it does not
@@ -100,7 +101,12 @@
     if  (mEventActivationMap.empty()) {
         mIsActive = false;
     }
-    mEventActivationMap[activationTrackerIndex].ttl_ns = ttl_seconds * NS_PER_SEC;
+    std::shared_ptr<Activation> activation = std::make_shared<Activation>();
+    activation->ttl_ns = ttl_seconds * NS_PER_SEC;
+    mEventActivationMap.emplace(activationTrackerIndex, activation);
+    if (-1 != deactivationTrackerIndex) {
+        mEventDeactivationMap.emplace(deactivationTrackerIndex, activation);
+    }
 }
 
 void MetricProducer::activateLocked(int activationTrackerIndex, int64_t elapsedTimestampNs) {
@@ -109,27 +115,35 @@
         return;
     }
     if (mActivationType == MetricActivation::ACTIVATE_ON_BOOT &&
-        it->second.state == ActivationState::kNotActive) {
-        it->second.state = ActivationState::kActiveOnBoot;
+        it->second->state == ActivationState::kNotActive) {
+        it->second->state = ActivationState::kActiveOnBoot;
         return;
     }
-    it->second.activation_ns = elapsedTimestampNs;
-    it->second.state = ActivationState::kActive;
+    it->second->activation_ns = elapsedTimestampNs;
+    it->second->state = ActivationState::kActive;
     mIsActive = true;
 }
 
+void MetricProducer::cancelEventActivationLocked(int deactivationTrackerIndex) {
+    auto it = mEventDeactivationMap.find(deactivationTrackerIndex);
+    if (it == mEventDeactivationMap.end()) {
+        return;
+    }
+    it->second->state = ActivationState::kNotActive;
+}
+
 void MetricProducer::setActiveLocked(int64_t currentTimeNs, int64_t remainingTtlNs) {
     if (mEventActivationMap.size() == 0) {
         return;
     }
     for (auto& pair : mEventActivationMap) {
         auto& activation = pair.second;
-        if (activation.ttl_ns >= remainingTtlNs) {
-            activation.activation_ns = currentTimeNs + remainingTtlNs - activation.ttl_ns;
-            activation.state = kActive;
+        if (activation->ttl_ns >= remainingTtlNs) {
+            activation->activation_ns = currentTimeNs + remainingTtlNs - activation->ttl_ns;
+            activation->state = kActive;
             mIsActive = true;
-            VLOG("setting new activation time to %lld, %lld, %lld",
-                 (long long)activation.activation_ns, (long long)currentTimeNs,
+            VLOG("setting new activation->time to %lld, %lld, %lld",
+                 (long long)activation->activation_ns, (long long)currentTimeNs,
                  (long long)remainingTtlNs);
             return;
         }
@@ -140,8 +154,8 @@
 int64_t MetricProducer::getRemainingTtlNsLocked(int64_t currentTimeNs) const {
     int64_t maxTtl = 0;
     for (const auto& activation : mEventActivationMap) {
-        if (activation.second.state == kActive) {
-            maxTtl = std::max(maxTtl, activation.second.ttl_ns + activation.second.activation_ns -
+        if (activation.second->state == kActive) {
+            maxTtl = std::max(maxTtl, activation.second->ttl_ns + activation.second->activation_ns -
                                               currentTimeNs);
         }
     }
@@ -153,9 +167,9 @@
         return;
     }
     for (auto& activation : mEventActivationMap) {
-        if (activation.second.state == kActiveOnBoot) {
-            activation.second.state = kActive;
-            activation.second.activation_ns = currentTimeNs;
+        if (activation.second->state == kActiveOnBoot) {
+            activation.second->state = kActive;
+            activation.second->activation_ns = currentTimeNs;
             mIsActive = true;
         }
     }
diff --git a/cmds/statsd/src/metrics/MetricProducer.h b/cmds/statsd/src/metrics/MetricProducer.h
index 046f996..70fbd47 100644
--- a/cmds/statsd/src/metrics/MetricProducer.h
+++ b/cmds/statsd/src/metrics/MetricProducer.h
@@ -228,6 +228,11 @@
         activateLocked(activationTrackerIndex, elapsedTimestampNs);
     }
 
+    void cancelEventActivation(int deactivationTrackerIndex) {
+        std::lock_guard<std::mutex> lock(mMutex);
+        cancelEventActivationLocked(deactivationTrackerIndex);
+    }
+
     bool isActive() const {
         std::lock_guard<std::mutex> lock(mMutex);
         return isActiveLocked();
@@ -238,7 +243,8 @@
         prepActiveForBootIfNecessaryLocked(currentTimeNs);
     }
 
-    void addActivation(int activationTrackerIndex, int64_t ttl_seconds);
+    void addActivation(int activationTrackerIndex, int64_t ttl_seconds,
+                       int deactivationTrackerIndex = -1);
 
     inline void setActivationType(const MetricActivation::ActivationType& activationType) {
         mActivationType = activationType;
@@ -263,6 +269,7 @@
     bool evaluateActiveStateLocked(int64_t elapsedTimestampNs);
 
     void activateLocked(int activationTrackerIndex, int64_t elapsedTimestampNs);
+    void cancelEventActivationLocked(int deactivationTrackerIndex);
 
     inline bool isActiveLocked() const {
         return mIsActive;
@@ -391,13 +398,19 @@
     };
     // When the metric producer has multiple activations, these activations are ORed to determine
     // whether the metric producer is ready to generate metrics.
-    std::unordered_map<int, Activation> mEventActivationMap;
+    std::unordered_map<int, std::shared_ptr<Activation>> mEventActivationMap;
+
+    // Maps index of atom matcher for deactivation to Activation struct.
+    std::unordered_map<int, std::shared_ptr<Activation>> mEventDeactivationMap;
 
     bool mIsActive;
 
     MetricActivation::ActivationType mActivationType;
 
     FRIEND_TEST(MetricActivationE2eTest, TestCountMetric);
+    FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithOneDeactivation);
+    FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithTwoDeactivations);
+    FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithTwoMetricsTwoDeactivations);
 
     FRIEND_TEST(StatsLogProcessorTest, TestActiveConfigMetricDiskWriteRead);
     FRIEND_TEST(StatsLogProcessorTest, TestActivationOnBoot);
diff --git a/cmds/statsd/src/metrics/MetricsManager.cpp b/cmds/statsd/src/metrics/MetricsManager.cpp
index 4b3bfd3..095f9dd 100644
--- a/cmds/statsd/src/metrics/MetricsManager.cpp
+++ b/cmds/statsd/src/metrics/MetricsManager.cpp
@@ -74,7 +74,8 @@
             timeBaseNs, currentTimeNs, mTagIds, mAllAtomMatchers, mAllConditionTrackers,
             mAllMetricProducers, mAllAnomalyTrackers, mAllPeriodicAlarmTrackers,
             mConditionToMetricMap, mTrackerToMetricMap, mTrackerToConditionMap,
-            mActivationAtomTrackerToMetricMap, mMetricIndexesWithActivation, mNoReportMetricIds);
+            mActivationAtomTrackerToMetricMap, mDeactivationAtomTrackerToMetricMap,
+            mMetricIndexesWithActivation, mNoReportMetricIds);
 
     mHashStringsInReport = config.hash_strings_in_metric_report();
     mVersionStringsInReport = config.version_strings_in_metric_report();
@@ -255,7 +256,7 @@
 
 bool MetricsManager::checkLogCredentials(const LogEvent& event) {
     if (android::util::AtomsInfo::kWhitelistedAtoms.find(event.GetTagId()) !=
-      android::util::AtomsInfo::kWhitelistedAtoms.end()) 
+      android::util::AtomsInfo::kWhitelistedAtoms.end())
     {
         return true;
     }
@@ -344,24 +345,61 @@
     int64_t eventTimeNs = event.GetElapsedTimestampNs();
 
     bool isActive = mIsAlwaysActive;
-    for (int metric : mMetricIndexesWithActivation) {
-        mAllMetricProducers[metric]->flushIfExpire(eventTimeNs);
-        isActive |= mAllMetricProducers[metric]->isActive();
+
+    // Set of metrics that are still active after flushing.
+    unordered_set<int> activeMetricsIndices;
+
+    // Update state of all metrics w/ activation conditions as of eventTimeNs.
+    for (int metricIndex : mMetricIndexesWithActivation) {
+        const sp<MetricProducer>& metric = mAllMetricProducers[metricIndex];
+        metric->flushIfExpire(eventTimeNs);
+        if (metric->isActive()) {
+            // If this metric w/ activation condition is still active after
+            // flushing, remember it.
+            activeMetricsIndices.insert(metricIndex);
+        }
     }
 
-    mIsActive = isActive;
+    mIsActive = isActive || !activeMetricsIndices.empty();
 
     if (mTagIds.find(tagId) == mTagIds.end()) {
-        // not interesting...
+        // Not interesting...
         return;
     }
 
     vector<MatchingState> matcherCache(mAllAtomMatchers.size(), MatchingState::kNotComputed);
 
+    // Evaluate all atom matchers.
     for (auto& matcher : mAllAtomMatchers) {
         matcher->onLogEvent(event, mAllAtomMatchers, matcherCache);
     }
 
+    // Set of metrics that received an activation cancellation.
+    unordered_set<int> metricIndicesWithCanceledActivations;
+
+    // Determine which metric activations received a cancellation and cancel them.
+    for (const auto& it : mDeactivationAtomTrackerToMetricMap) {
+        if (matcherCache[it.first] == MatchingState::kMatched) {
+            for (int metricIndex : it.second) {
+                mAllMetricProducers[metricIndex]->cancelEventActivation(it.first);
+                metricIndicesWithCanceledActivations.insert(metricIndex);
+            }
+        }
+    }
+
+    // Determine whether any metrics are no longer active after cancelling metric activations.
+    for (const int metricIndex : metricIndicesWithCanceledActivations) {
+        const sp<MetricProducer>& metric = mAllMetricProducers[metricIndex];
+        metric->flushIfExpire(eventTimeNs);
+        if (!metric->isActive()) {
+            activeMetricsIndices.erase(metricIndex);
+        }
+    }
+
+    isActive |= !activeMetricsIndices.empty();
+
+
+    // Determine which metric activations should be turned on and turn them on
     for (const auto& it : mActivationAtomTrackerToMetricMap) {
         if (matcherCache[it.first] == MatchingState::kMatched) {
             for (int metricIndex : it.second) {
@@ -406,12 +444,12 @@
         if (pair != mConditionToMetricMap.end()) {
             auto& metricList = pair->second;
             for (auto metricIndex : metricList) {
-                // metric cares about non sliced condition, and it's changed.
+                // Metric cares about non sliced condition, and it's changed.
                 // Push the new condition to it directly.
                 if (!mAllMetricProducers[metricIndex]->isConditionSliced()) {
                     mAllMetricProducers[metricIndex]->onConditionChanged(conditionCache[i],
                                                                          eventTimeNs);
-                    // metric cares about sliced conditions, and it may have changed. Send
+                    // Metric cares about sliced conditions, and it may have changed. Send
                     // notification, and the metric can query the sliced conditions that are
                     // interesting to it.
                 } else {
diff --git a/cmds/statsd/src/metrics/MetricsManager.h b/cmds/statsd/src/metrics/MetricsManager.h
index 3904460..d317f8e 100644
--- a/cmds/statsd/src/metrics/MetricsManager.h
+++ b/cmds/statsd/src/metrics/MetricsManager.h
@@ -225,18 +225,21 @@
 
     // The following map is initialized from the statsd_config.
 
-    // maps from the index of the LogMatchingTracker to index of MetricProducer.
+    // Maps from the index of the LogMatchingTracker to index of MetricProducer.
     std::unordered_map<int, std::vector<int>> mTrackerToMetricMap;
 
-    // maps from LogMatchingTracker to ConditionTracker
+    // Maps from LogMatchingTracker to ConditionTracker
     std::unordered_map<int, std::vector<int>> mTrackerToConditionMap;
 
-    // maps from ConditionTracker to MetricProducer
+    // Maps from ConditionTracker to MetricProducer
     std::unordered_map<int, std::vector<int>> mConditionToMetricMap;
 
-    // maps from life span triggering event to MetricProducers.
+    // Maps from life span triggering event to MetricProducers.
     std::unordered_map<int, std::vector<int>> mActivationAtomTrackerToMetricMap;
 
+    // Maps deactivation triggering event to MetricProducers.
+    std::unordered_map<int, std::vector<int>> mDeactivationAtomTrackerToMetricMap;
+
     std::vector<int> mMetricIndexesWithActivation;
 
     void initLogSourceWhiteList();
@@ -281,6 +284,9 @@
     FRIEND_TEST(AlarmE2eTest, TestMultipleAlarms);
     FRIEND_TEST(ConfigTtlE2eTest, TestCountMetric);
     FRIEND_TEST(MetricActivationE2eTest, TestCountMetric);
+    FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithOneDeactivation);
+    FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithTwoDeactivations);
+    FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithTwoMetricsTwoDeactivations);
 
     FRIEND_TEST(StatsLogProcessorTest, TestActiveConfigMetricDiskWriteRead);
     FRIEND_TEST(StatsLogProcessorTest, TestActivationOnBoot);
diff --git a/cmds/statsd/src/metrics/metrics_manager_util.cpp b/cmds/statsd/src/metrics/metrics_manager_util.cpp
index 463b5a0..082382c 100644
--- a/cmds/statsd/src/metrics/metrics_manager_util.cpp
+++ b/cmds/statsd/src/metrics/metrics_manager_util.cpp
@@ -711,6 +711,7 @@
                            const unordered_map<int64_t, int> &metricProducerMap,
                            vector<sp<MetricProducer>>& allMetricProducers,
                            unordered_map<int, std::vector<int>>& activationAtomTrackerToMetricMap,
+                           unordered_map<int, std::vector<int>>& deactivationAtomTrackerToMetricMap,
                            vector<int>& metricsWithActivation) {
     for (int i = 0; i < config.metric_activation_size(); ++i) {
         const MetricActivation& metric_activation = config.metric_activation(i);
@@ -725,8 +726,8 @@
             ALOGE("Invalid metric tracker index.");
             return false;
         }
-        allMetricProducers[metricTrackerIndex]->setActivationType(
-                metric_activation.activation_type());
+        const sp<MetricProducer>& metric = allMetricProducers[metricTrackerIndex];
+        metric->setActivationType(metric_activation.activation_type());
         metricsWithActivation.push_back(metricTrackerIndex);
         for (int j = 0; j < metric_activation.event_activation_size(); ++j) {
             const EventActivation& activation = metric_activation.event_activation(j);
@@ -738,8 +739,22 @@
             const int atomMatcherIndex = logTrackerIt->second;
             activationAtomTrackerToMetricMap[atomMatcherIndex].push_back(
                 metricTrackerIndex);
-            allMetricProducers[metricTrackerIndex]->addActivation(
-                atomMatcherIndex, activation.ttl_seconds());
+
+            if (activation.has_deactivation_atom_matcher_id()) {
+                auto deactivationAtomMatcherIt =
+                        logEventTrackerMap.find(activation.deactivation_atom_matcher_id());
+                if (deactivationAtomMatcherIt == logEventTrackerMap.end()) {
+                    ALOGE("Atom matcher not found for event deactivation.");
+                    return false;
+                }
+                const int deactivationMatcherIndex = deactivationAtomMatcherIt->second;
+                deactivationAtomTrackerToMetricMap[deactivationMatcherIndex]
+                        .push_back(metricTrackerIndex);
+                metric->addActivation(atomMatcherIndex, activation.ttl_seconds(),
+                                      deactivationMatcherIndex);
+            } else {
+                metric->addActivation(atomMatcherIndex, activation.ttl_seconds());
+            }
         }
     }
     return true;
@@ -759,6 +774,7 @@
                       unordered_map<int, std::vector<int>>& trackerToMetricMap,
                       unordered_map<int, std::vector<int>>& trackerToConditionMap,
                       unordered_map<int, std::vector<int>>& activationAtomTrackerToMetricMap,
+                      unordered_map<int, std::vector<int>>& deactivationAtomTrackerToMetricMap,
                       vector<int>& metricsWithActivation,
                       std::set<int64_t>& noReportMetricIds) {
     unordered_map<int64_t, int> logTrackerMap;
@@ -795,7 +811,8 @@
         return false;
     }
     if (!initMetricActivations(key, config, currentTimeNs, logTrackerMap, metricProducerMap,
-            allMetricProducers, activationAtomTrackerToMetricMap, metricsWithActivation)) {
+            allMetricProducers, activationAtomTrackerToMetricMap,
+            deactivationAtomTrackerToMetricMap, metricsWithActivation)) {
         ALOGE("initMetricActivations failed");
         return false;
     }
diff --git a/cmds/statsd/src/metrics/metrics_manager_util.h b/cmds/statsd/src/metrics/metrics_manager_util.h
index 9ffceda..028231f 100644
--- a/cmds/statsd/src/metrics/metrics_manager_util.h
+++ b/cmds/statsd/src/metrics/metrics_manager_util.h
@@ -108,8 +108,9 @@
                       std::unordered_map<int, std::vector<int>>& conditionToMetricMap,
                       std::unordered_map<int, std::vector<int>>& trackerToMetricMap,
                       std::unordered_map<int, std::vector<int>>& trackerToConditionMap,
-                      unordered_map<int, std::vector<int>>& lifeSpanEventTrackerToMetricMap,
-                      vector<int>& metricsWithLifeSpan,
+                      unordered_map<int, std::vector<int>>& activationAtomTrackerToMetricMap,
+                      unordered_map<int, std::vector<int>>& deactivationAtomTrackerToMetricMap,
+                      vector<int>& metricsWithActivation,
                       std::set<int64_t>& noReportMetricIds);
 
 bool isStateTracker(const SimplePredicate& simplePredicate, std::vector<Matcher>* primaryKeys);
diff --git a/cmds/statsd/src/statsd_config.proto b/cmds/statsd/src/statsd_config.proto
index 0e91f52..257e65e 100644
--- a/cmds/statsd/src/statsd_config.proto
+++ b/cmds/statsd/src/statsd_config.proto
@@ -380,6 +380,7 @@
 message EventActivation {
   optional int64 atom_matcher_id = 1;
   optional int64 ttl_seconds = 2;
+  optional int64 deactivation_atom_matcher_id = 3;
 }
 
 message MetricActivation {
diff --git a/cmds/statsd/tests/MetricsManager_test.cpp b/cmds/statsd/tests/MetricsManager_test.cpp
index f8184d8..71adc57 100644
--- a/cmds/statsd/tests/MetricsManager_test.cpp
+++ b/cmds/statsd/tests/MetricsManager_test.cpp
@@ -282,8 +282,9 @@
     unordered_map<int, std::vector<int>> conditionToMetricMap;
     unordered_map<int, std::vector<int>> trackerToMetricMap;
     unordered_map<int, std::vector<int>> trackerToConditionMap;
-    unordered_map<int, std::vector<int>> lifeSpanEventTrackerToMetricMap;
-    vector<int> metricsWithLifeSpan;
+    unordered_map<int, std::vector<int>> activationAtomTrackerToMetricMap;
+    unordered_map<int, std::vector<int>> deactivationAtomTrackerToMetricMap;
+    vector<int> metricsWithActivation;
     std::set<int64_t> noReportMetricIds;
 
     EXPECT_TRUE(initStatsdConfig(kConfigKey, config, uidMap, pullerManager, anomalyAlarmMonitor,
@@ -291,8 +292,8 @@
                                  allAtomMatchers, allConditionTrackers, allMetricProducers,
                                  allAnomalyTrackers, allAlarmTrackers, conditionToMetricMap,
                                  trackerToMetricMap, trackerToConditionMap,
-                                 lifeSpanEventTrackerToMetricMap, metricsWithLifeSpan,
-                                 noReportMetricIds));
+                                 activationAtomTrackerToMetricMap, deactivationAtomTrackerToMetricMap,
+                                 metricsWithActivation, noReportMetricIds));
     EXPECT_EQ(1u, allMetricProducers.size());
     EXPECT_EQ(1u, allAnomalyTrackers.size());
     EXPECT_EQ(1u, noReportMetricIds.size());
@@ -313,8 +314,9 @@
     unordered_map<int, std::vector<int>> conditionToMetricMap;
     unordered_map<int, std::vector<int>> trackerToMetricMap;
     unordered_map<int, std::vector<int>> trackerToConditionMap;
-    unordered_map<int, std::vector<int>> lifeSpanEventTrackerToMetricMap;
-    vector<int> metricsWithLifeSpan;
+    unordered_map<int, std::vector<int>> activationAtomTrackerToMetricMap;
+    unordered_map<int, std::vector<int>> deactivationAtomTrackerToMetricMap;
+    vector<int> metricsWithActivation;
     std::set<int64_t> noReportMetricIds;
 
     EXPECT_FALSE(initStatsdConfig(kConfigKey, config, uidMap, pullerManager, anomalyAlarmMonitor,
@@ -322,8 +324,8 @@
                                   allAtomMatchers, allConditionTrackers, allMetricProducers,
                                   allAnomalyTrackers, allAlarmTrackers, conditionToMetricMap,
                                   trackerToMetricMap, trackerToConditionMap,
-                                  lifeSpanEventTrackerToMetricMap, metricsWithLifeSpan,
-                                  noReportMetricIds));
+                                  activationAtomTrackerToMetricMap, deactivationAtomTrackerToMetricMap,
+                                  metricsWithActivation, noReportMetricIds));
 }
 
 TEST(MetricsManagerTest, TestCircleLogMatcherDependency) {
@@ -341,8 +343,9 @@
     unordered_map<int, std::vector<int>> conditionToMetricMap;
     unordered_map<int, std::vector<int>> trackerToMetricMap;
     unordered_map<int, std::vector<int>> trackerToConditionMap;
-    unordered_map<int, std::vector<int>> lifeSpanEventTrackerToMetricMap;
-    vector<int> metricsWithLifeSpan;
+    unordered_map<int, std::vector<int>> activationAtomTrackerToMetricMap;
+    unordered_map<int, std::vector<int>> deactivationAtomTrackerToMetricMap;
+    vector<int> metricsWithActivation;
     std::set<int64_t> noReportMetricIds;
 
     EXPECT_FALSE(initStatsdConfig(kConfigKey, config, uidMap, pullerManager, anomalyAlarmMonitor,
@@ -350,8 +353,8 @@
                                   allAtomMatchers, allConditionTrackers, allMetricProducers,
                                   allAnomalyTrackers, allAlarmTrackers, conditionToMetricMap,
                                   trackerToMetricMap, trackerToConditionMap,
-                                  lifeSpanEventTrackerToMetricMap, metricsWithLifeSpan,
-                                  noReportMetricIds));
+                                  activationAtomTrackerToMetricMap, deactivationAtomTrackerToMetricMap,
+                                  metricsWithActivation, noReportMetricIds));
 }
 
 TEST(MetricsManagerTest, TestMissingMatchers) {
@@ -369,16 +372,17 @@
     unordered_map<int, std::vector<int>> conditionToMetricMap;
     unordered_map<int, std::vector<int>> trackerToMetricMap;
     unordered_map<int, std::vector<int>> trackerToConditionMap;
-    unordered_map<int, std::vector<int>> lifeSpanEventTrackerToMetricMap;
-    vector<int> metricsWithLifeSpan;
+    unordered_map<int, std::vector<int>> activationAtomTrackerToMetricMap;
+    unordered_map<int, std::vector<int>> deactivationAtomTrackerToMetricMap;
+    vector<int> metricsWithActivation;
     std::set<int64_t> noReportMetricIds;
     EXPECT_FALSE(initStatsdConfig(kConfigKey, config, uidMap, pullerManager, anomalyAlarmMonitor,
                                   periodicAlarmMonitor, timeBaseSec, timeBaseSec, allTagIds,
                                   allAtomMatchers, allConditionTrackers, allMetricProducers,
                                   allAnomalyTrackers, allAlarmTrackers, conditionToMetricMap,
                                   trackerToMetricMap, trackerToConditionMap,
-                                  lifeSpanEventTrackerToMetricMap, metricsWithLifeSpan,
-                                  noReportMetricIds));
+                                  activationAtomTrackerToMetricMap, deactivationAtomTrackerToMetricMap,
+                                  metricsWithActivation, noReportMetricIds));
 }
 
 TEST(MetricsManagerTest, TestMissingPredicate) {
@@ -396,16 +400,17 @@
     unordered_map<int, std::vector<int>> conditionToMetricMap;
     unordered_map<int, std::vector<int>> trackerToMetricMap;
     unordered_map<int, std::vector<int>> trackerToConditionMap;
-    unordered_map<int, std::vector<int>> lifeSpanEventTrackerToMetricMap;
-    vector<int> metricsWithLifeSpan;
+    unordered_map<int, std::vector<int>> activationAtomTrackerToMetricMap;
+    unordered_map<int, std::vector<int>> deactivationAtomTrackerToMetricMap;
+    vector<int> metricsWithActivation;
     std::set<int64_t> noReportMetricIds;
     EXPECT_FALSE(initStatsdConfig(kConfigKey, config, uidMap, pullerManager, anomalyAlarmMonitor,
                                   periodicAlarmMonitor, timeBaseSec, timeBaseSec, allTagIds,
                                   allAtomMatchers, allConditionTrackers, allMetricProducers,
                                   allAnomalyTrackers, allAlarmTrackers, conditionToMetricMap,
                                   trackerToMetricMap, trackerToConditionMap,
-                                  lifeSpanEventTrackerToMetricMap, metricsWithLifeSpan,
-                                  noReportMetricIds));
+                                  activationAtomTrackerToMetricMap, deactivationAtomTrackerToMetricMap,
+                                  metricsWithActivation, noReportMetricIds));
 }
 
 TEST(MetricsManagerTest, TestCirclePredicateDependency) {
@@ -423,8 +428,9 @@
     unordered_map<int, std::vector<int>> conditionToMetricMap;
     unordered_map<int, std::vector<int>> trackerToMetricMap;
     unordered_map<int, std::vector<int>> trackerToConditionMap;
-    unordered_map<int, std::vector<int>> lifeSpanEventTrackerToMetricMap;
-    vector<int> metricsWithLifeSpan;
+    unordered_map<int, std::vector<int>> activationAtomTrackerToMetricMap;
+    unordered_map<int, std::vector<int>> deactivationAtomTrackerToMetricMap;
+    vector<int> metricsWithActivation;
     std::set<int64_t> noReportMetricIds;
 
     EXPECT_FALSE(initStatsdConfig(kConfigKey, config, uidMap, pullerManager, anomalyAlarmMonitor,
@@ -432,8 +438,8 @@
                                   allAtomMatchers, allConditionTrackers, allMetricProducers,
                                   allAnomalyTrackers, allAlarmTrackers, conditionToMetricMap,
                                   trackerToMetricMap, trackerToConditionMap,
-                                  lifeSpanEventTrackerToMetricMap, metricsWithLifeSpan,
-                                  noReportMetricIds));
+                                  activationAtomTrackerToMetricMap, deactivationAtomTrackerToMetricMap,
+                                  metricsWithActivation, noReportMetricIds));
 }
 
 TEST(MetricsManagerTest, testAlertWithUnknownMetric) {
@@ -451,8 +457,9 @@
     unordered_map<int, std::vector<int>> conditionToMetricMap;
     unordered_map<int, std::vector<int>> trackerToMetricMap;
     unordered_map<int, std::vector<int>> trackerToConditionMap;
-    unordered_map<int, std::vector<int>> lifeSpanEventTrackerToMetricMap;
-    vector<int> metricsWithLifeSpan;
+    unordered_map<int, std::vector<int>> activationAtomTrackerToMetricMap;
+    unordered_map<int, std::vector<int>> deactivationAtomTrackerToMetricMap;
+    vector<int> metricsWithActivation;
     std::set<int64_t> noReportMetricIds;
 
     EXPECT_FALSE(initStatsdConfig(kConfigKey, config, uidMap, pullerManager, anomalyAlarmMonitor,
@@ -460,8 +467,8 @@
                                   allAtomMatchers, allConditionTrackers, allMetricProducers,
                                   allAnomalyTrackers, allAlarmTrackers, conditionToMetricMap,
                                   trackerToMetricMap, trackerToConditionMap,
-                                  lifeSpanEventTrackerToMetricMap, metricsWithLifeSpan,
-                                  noReportMetricIds));
+                                  activationAtomTrackerToMetricMap, deactivationAtomTrackerToMetricMap,
+                                  metricsWithActivation, noReportMetricIds));
 }
 
 #else
diff --git a/cmds/statsd/tests/StatsLogProcessor_test.cpp b/cmds/statsd/tests/StatsLogProcessor_test.cpp
index 88aa180..91e282a 100644
--- a/cmds/statsd/tests/StatsLogProcessor_test.cpp
+++ b/cmds/statsd/tests/StatsLogProcessor_test.cpp
@@ -610,26 +610,26 @@
     // Assert that all 3 metrics with activation are inactive and that the ttls were properly set.
     EXPECT_FALSE(metricProducer1003->isActive());
     const auto& activation1003 = metricProducer1003->mEventActivationMap.begin()->second;
-    EXPECT_EQ(100 * NS_PER_SEC, activation1003.ttl_ns);
-    EXPECT_EQ(0, activation1003.activation_ns);
+    EXPECT_EQ(100 * NS_PER_SEC, activation1003->ttl_ns);
+    EXPECT_EQ(0, activation1003->activation_ns);
     EXPECT_FALSE(metricProducer1005->isActive());
     const auto& activation1005 = metricProducer1005->mEventActivationMap.begin()->second;
-    EXPECT_EQ(100 * NS_PER_SEC, activation1005.ttl_ns);
-    EXPECT_EQ(0, activation1005.activation_ns);
+    EXPECT_EQ(100 * NS_PER_SEC, activation1005->ttl_ns);
+    EXPECT_EQ(0, activation1005->activation_ns);
     EXPECT_FALSE(metricProducer1006->isActive());
     const auto& activation1006 = metricProducer1006->mEventActivationMap.begin()->second;
-    EXPECT_EQ(200 * NS_PER_SEC, activation1006.ttl_ns);
-    EXPECT_EQ(0, activation1006.activation_ns);
+    EXPECT_EQ(200 * NS_PER_SEC, activation1006->ttl_ns);
+    EXPECT_EQ(0, activation1006->activation_ns);
 
     processor2->LoadMetricsActivationFromDisk();
 
     // After loading activations from disk, assert that all 3 metrics are active.
     EXPECT_TRUE(metricProducer1003->isActive());
-    EXPECT_EQ(timeBase2 + ttl3 - activation1003.ttl_ns, activation1003.activation_ns);
+    EXPECT_EQ(timeBase2 + ttl3 - activation1003->ttl_ns, activation1003->activation_ns);
     EXPECT_TRUE(metricProducer1005->isActive());
-    EXPECT_EQ(timeBase2 + ttl5 - activation1005.ttl_ns, activation1005.activation_ns);
+    EXPECT_EQ(timeBase2 + ttl5 - activation1005->ttl_ns, activation1005->activation_ns);
     EXPECT_TRUE(metricProducer1006->isActive());
-    EXPECT_EQ(timeBase2 + ttl6 - activation1006.ttl_ns, activation1003.activation_ns);
+    EXPECT_EQ(timeBase2 + ttl6 - activation1006->ttl_ns, activation1003->activation_ns);
 
     // Make sure no more broadcasts have happened.
     EXPECT_EQ(broadcastCount, 1);
@@ -696,17 +696,17 @@
     EXPECT_TRUE(metricProducer2->isActive());
 
     const auto& activation1 = metricProducer1->mEventActivationMap.begin()->second;
-    EXPECT_EQ(100 * NS_PER_SEC, activation1.ttl_ns);
-    EXPECT_EQ(0, activation1.activation_ns);
-    EXPECT_EQ(kNotActive, activation1.state);
+    EXPECT_EQ(100 * NS_PER_SEC, activation1->ttl_ns);
+    EXPECT_EQ(0, activation1->activation_ns);
+    EXPECT_EQ(kNotActive, activation1->state);
 
     std::vector<AttributionNodeInternal> attributions1 = {CreateAttribution(111, "App1")};
     auto event = CreateAcquireWakelockEvent(attributions1, "wl1", 100 + timeBase1);
     processor->OnLogEvent(event.get());
 
     EXPECT_FALSE(metricProducer1->isActive());
-    EXPECT_EQ(0, activation1.activation_ns);
-    EXPECT_EQ(kActiveOnBoot, activation1.state);
+    EXPECT_EQ(0, activation1->activation_ns);
+    EXPECT_EQ(kActiveOnBoot, activation1->state);
 
     int64_t shutDownTime = timeBase1 + 100 * NS_PER_SEC;
 
@@ -746,14 +746,14 @@
     EXPECT_TRUE(metricProducer1002->isActive());
 
     const auto& activation1001 = metricProducer1001->mEventActivationMap.begin()->second;
-    EXPECT_EQ(100 * NS_PER_SEC, activation1001.ttl_ns);
-    EXPECT_EQ(0, activation1001.activation_ns);
-    EXPECT_EQ(kNotActive, activation1001.state);
+    EXPECT_EQ(100 * NS_PER_SEC, activation1001->ttl_ns);
+    EXPECT_EQ(0, activation1001->activation_ns);
+    EXPECT_EQ(kNotActive, activation1001->state);
 
     processor2->LoadMetricsActivationFromDisk();
 
     EXPECT_TRUE(metricProducer1001->isActive());
-    EXPECT_EQ(timeBase2 + ttl1 - activation1001.ttl_ns, activation1001.activation_ns);
+    EXPECT_EQ(timeBase2 + ttl1 - activation1001->ttl_ns, activation1001->activation_ns);
 }
 
 #else
diff --git a/cmds/statsd/tests/e2e/MetricActivation_e2e_test.cpp b/cmds/statsd/tests/e2e/MetricActivation_e2e_test.cpp
index 7fb43f8a..bf52bb0 100644
--- a/cmds/statsd/tests/e2e/MetricActivation_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/MetricActivation_e2e_test.cpp
@@ -31,9 +31,9 @@
 StatsdConfig CreateStatsdConfig() {
     StatsdConfig config;
     config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+    auto saverModeMatcher = CreateBatterySaverModeStartAtomMatcher();
     auto crashMatcher = CreateProcessCrashAtomMatcher();
     auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
-    auto saverModeMatcher = CreateBatterySaverModeStartAtomMatcher();
 
     *config.add_atom_matcher() = saverModeMatcher;
     *config.add_atom_matcher() = crashMatcher;
@@ -60,13 +60,149 @@
     return config;
 }
 
+StatsdConfig CreateStatsdConfigWithOneDeactivation() {
+    StatsdConfig config;
+    config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+    auto saverModeMatcher = CreateBatterySaverModeStartAtomMatcher();
+    auto crashMatcher = CreateProcessCrashAtomMatcher();
+    auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
+    auto brightnessChangedMatcher = CreateScreenBrightnessChangedAtomMatcher();
+
+    *config.add_atom_matcher() = saverModeMatcher;
+    *config.add_atom_matcher() = crashMatcher;
+    *config.add_atom_matcher() = screenOnMatcher;
+    *config.add_atom_matcher() = brightnessChangedMatcher;
+
+    int64_t metricId = 123456;
+    auto countMetric = config.add_count_metric();
+    countMetric->set_id(metricId);
+    countMetric->set_what(crashMatcher.id());
+    countMetric->set_bucket(FIVE_MINUTES);
+    countMetric->mutable_dimensions_in_what()->set_field(
+        android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+    countMetric->mutable_dimensions_in_what()->add_child()->set_field(1);  // uid field
+
+    auto metric_activation1 = config.add_metric_activation();
+    metric_activation1->set_metric_id(metricId);
+    auto event_activation1 = metric_activation1->add_event_activation();
+    event_activation1->set_atom_matcher_id(saverModeMatcher.id());
+    event_activation1->set_ttl_seconds(60 * 6);  // 6 minutes
+    event_activation1->set_deactivation_atom_matcher_id(brightnessChangedMatcher.id());
+    auto event_activation2 = metric_activation1->add_event_activation();
+    event_activation2->set_atom_matcher_id(screenOnMatcher.id());
+    event_activation2->set_ttl_seconds(60 * 2);  // 2 minutes
+
+    return config;
+}
+
+StatsdConfig CreateStatsdConfigWithTwoDeactivations() {
+    StatsdConfig config;
+    config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+    auto saverModeMatcher = CreateBatterySaverModeStartAtomMatcher();
+    auto crashMatcher = CreateProcessCrashAtomMatcher();
+    auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
+    auto brightnessChangedMatcher = CreateScreenBrightnessChangedAtomMatcher();
+    auto brightnessChangedMatcher2 = CreateScreenBrightnessChangedAtomMatcher();
+    brightnessChangedMatcher2.set_id(StringToId("ScreenBrightnessChanged2"));
+
+    *config.add_atom_matcher() = saverModeMatcher;
+    *config.add_atom_matcher() = crashMatcher;
+    *config.add_atom_matcher() = screenOnMatcher;
+    *config.add_atom_matcher() = brightnessChangedMatcher;
+    *config.add_atom_matcher() = brightnessChangedMatcher2;
+
+    int64_t metricId = 123456;
+    auto countMetric = config.add_count_metric();
+    countMetric->set_id(metricId);
+    countMetric->set_what(crashMatcher.id());
+    countMetric->set_bucket(FIVE_MINUTES);
+    countMetric->mutable_dimensions_in_what()->set_field(
+        android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+    countMetric->mutable_dimensions_in_what()->add_child()->set_field(1);  // uid field
+
+    auto metric_activation1 = config.add_metric_activation();
+    metric_activation1->set_metric_id(metricId);
+    auto event_activation1 = metric_activation1->add_event_activation();
+    event_activation1->set_atom_matcher_id(saverModeMatcher.id());
+    event_activation1->set_ttl_seconds(60 * 6);  // 6 minutes
+    event_activation1->set_deactivation_atom_matcher_id(brightnessChangedMatcher.id());
+    auto event_activation2 = metric_activation1->add_event_activation();
+    event_activation2->set_atom_matcher_id(screenOnMatcher.id());
+    event_activation2->set_ttl_seconds(60 * 2);  // 2 minutes
+    event_activation2->set_deactivation_atom_matcher_id(brightnessChangedMatcher2.id());
+
+    return config;
+}
+
+StatsdConfig CreateStatsdConfigWithTwoMetricsTwoDeactivations() {
+    StatsdConfig config;
+    config.add_allowed_log_source("AID_ROOT"); // LogEvent defaults to UID of root.
+    auto saverModeMatcher = CreateBatterySaverModeStartAtomMatcher();
+    auto crashMatcher = CreateProcessCrashAtomMatcher();
+    auto foregroundMatcher = CreateMoveToForegroundAtomMatcher();
+    auto screenOnMatcher = CreateScreenTurnedOnAtomMatcher();
+    auto brightnessChangedMatcher = CreateScreenBrightnessChangedAtomMatcher();
+    auto brightnessChangedMatcher2 = CreateScreenBrightnessChangedAtomMatcher();
+    brightnessChangedMatcher2.set_id(StringToId("ScreenBrightnessChanged2"));
+
+    *config.add_atom_matcher() = saverModeMatcher;
+    *config.add_atom_matcher() = crashMatcher;
+    *config.add_atom_matcher() = screenOnMatcher;
+    *config.add_atom_matcher() = brightnessChangedMatcher;
+    *config.add_atom_matcher() = brightnessChangedMatcher2;
+    *config.add_atom_matcher() = foregroundMatcher;
+
+    int64_t metricId = 123456;
+    auto countMetric = config.add_count_metric();
+    countMetric->set_id(metricId);
+    countMetric->set_what(crashMatcher.id());
+    countMetric->set_bucket(FIVE_MINUTES);
+    countMetric->mutable_dimensions_in_what()->set_field(
+        android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+    countMetric->mutable_dimensions_in_what()->add_child()->set_field(1);  // uid field
+
+    int64_t metricId2 = 234567;
+    countMetric = config.add_count_metric();
+    countMetric->set_id(metricId2);
+    countMetric->set_what(foregroundMatcher.id());
+    countMetric->set_bucket(FIVE_MINUTES);
+    countMetric->mutable_dimensions_in_what()->set_field(
+        android::util::ACTIVITY_FOREGROUND_STATE_CHANGED);
+    countMetric->mutable_dimensions_in_what()->add_child()->set_field(1);  // uid field
+
+    auto metric_activation1 = config.add_metric_activation();
+    metric_activation1->set_metric_id(metricId);
+    auto event_activation1 = metric_activation1->add_event_activation();
+    event_activation1->set_atom_matcher_id(saverModeMatcher.id());
+    event_activation1->set_ttl_seconds(60 * 6);  // 6 minutes
+    event_activation1->set_deactivation_atom_matcher_id(brightnessChangedMatcher.id());
+    auto event_activation2 = metric_activation1->add_event_activation();
+    event_activation2->set_atom_matcher_id(screenOnMatcher.id());
+    event_activation2->set_ttl_seconds(60 * 2);  // 2 minutes
+    event_activation2->set_deactivation_atom_matcher_id(brightnessChangedMatcher2.id());
+
+    metric_activation1 = config.add_metric_activation();
+    metric_activation1->set_metric_id(metricId2);
+    event_activation1 = metric_activation1->add_event_activation();
+    event_activation1->set_atom_matcher_id(saverModeMatcher.id());
+    event_activation1->set_ttl_seconds(60 * 6);  // 6 minutes
+    event_activation1->set_deactivation_atom_matcher_id(brightnessChangedMatcher.id());
+    event_activation2 = metric_activation1->add_event_activation();
+    event_activation2->set_atom_matcher_id(screenOnMatcher.id());
+    event_activation2->set_ttl_seconds(60 * 2);  // 2 minutes
+    event_activation2->set_deactivation_atom_matcher_id(brightnessChangedMatcher2.id());
+
+    return config;
+}
+
 }  // namespace
 
 TEST(MetricActivationE2eTest, TestCountMetric) {
     auto config = CreateStatsdConfig();
 
-    int64_t bucketStartTimeNs = 10000000000;
-    int64_t bucketSizeNs = TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000;
+    int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
+    int64_t bucketSizeNs =
+            TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
 
     int uid = 12345;
     int64_t cfgId = 98765;
@@ -108,12 +244,12 @@
     EXPECT_EQ(eventActivationMap.size(), 2u);
     EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
     EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
-    EXPECT_EQ(eventActivationMap[0].state, ActivationState::kNotActive);
-    EXPECT_EQ(eventActivationMap[0].activation_ns, 0);
-    EXPECT_EQ(eventActivationMap[0].ttl_ns, 60 * 6 * NS_PER_SEC);
-    EXPECT_EQ(eventActivationMap[2].state, ActivationState::kNotActive);
-    EXPECT_EQ(eventActivationMap[2].activation_ns, 0);
-    EXPECT_EQ(eventActivationMap[2].ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
 
     std::unique_ptr<LogEvent> event;
 
@@ -131,12 +267,12 @@
     EXPECT_EQ(broadcastCount, 1);
     EXPECT_EQ(activeConfigsBroadcast.size(), 1);
     EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-    EXPECT_EQ(eventActivationMap[0].state, ActivationState::kActive);
-    EXPECT_EQ(eventActivationMap[0].activation_ns, bucketStartTimeNs + 10);
-    EXPECT_EQ(eventActivationMap[0].ttl_ns, 60 * 6 * NS_PER_SEC);
-    EXPECT_EQ(eventActivationMap[2].state, ActivationState::kNotActive);
-    EXPECT_EQ(eventActivationMap[2].activation_ns, 0);
-    EXPECT_EQ(eventActivationMap[2].ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
 
     // First processed event.
     event = CreateAppCrashEvent(222, bucketStartTimeNs + 15);
@@ -148,12 +284,12 @@
     processor.OnLogEvent(event.get());
     EXPECT_TRUE(metricsManager->isActive());
     EXPECT_TRUE(metricProducer->mIsActive);
-    EXPECT_EQ(eventActivationMap[0].state, ActivationState::kActive);
-    EXPECT_EQ(eventActivationMap[0].activation_ns, bucketStartTimeNs + 10);
-    EXPECT_EQ(eventActivationMap[0].ttl_ns, 60 * 6 * NS_PER_SEC);
-    EXPECT_EQ(eventActivationMap[2].state, ActivationState::kActive);
-    EXPECT_EQ(eventActivationMap[2].activation_ns, bucketStartTimeNs + 20);
-    EXPECT_EQ(eventActivationMap[2].ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
 
     // 2nd processed event.
     // The activation by screen_on event expires, but the one by battery save mode is still active.
@@ -161,12 +297,12 @@
     processor.OnLogEvent(event.get());
     EXPECT_TRUE(metricsManager->isActive());
     EXPECT_TRUE(metricProducer->mIsActive);
-    EXPECT_EQ(eventActivationMap[0].state, ActivationState::kActive);
-    EXPECT_EQ(eventActivationMap[0].activation_ns, bucketStartTimeNs + 10);
-    EXPECT_EQ(eventActivationMap[0].ttl_ns, 60 * 6 * NS_PER_SEC);
-    EXPECT_EQ(eventActivationMap[2].state, ActivationState::kNotActive);
-    EXPECT_EQ(eventActivationMap[2].activation_ns, bucketStartTimeNs + 20);
-    EXPECT_EQ(eventActivationMap[2].ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
     // No new broadcast since the config should still be active.
     EXPECT_EQ(broadcastCount, 1);
 
@@ -182,14 +318,14 @@
     // New broadcast since the config is no longer active.
     EXPECT_EQ(broadcastCount, 2);
     EXPECT_EQ(activeConfigsBroadcast.size(), 0);
-    EXPECT_EQ(eventActivationMap[0].state, ActivationState::kNotActive);
-    EXPECT_EQ(eventActivationMap[0].activation_ns, bucketStartTimeNs + 10);
-    EXPECT_EQ(eventActivationMap[0].ttl_ns, 60 * 6 * NS_PER_SEC);
-    EXPECT_EQ(eventActivationMap[2].state, ActivationState::kNotActive);
-    EXPECT_EQ(eventActivationMap[2].activation_ns, bucketStartTimeNs + 20);
-    EXPECT_EQ(eventActivationMap[2].ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
 
-    // Re-activate.
+    // Re-activate metric via screen on.
     event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
                                           bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
     processor.OnLogEvent(event.get());
@@ -198,13 +334,14 @@
     EXPECT_EQ(broadcastCount, 3);
     EXPECT_EQ(activeConfigsBroadcast.size(), 1);
     EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
-    EXPECT_EQ(eventActivationMap[0].state, ActivationState::kNotActive);
-    EXPECT_EQ(eventActivationMap[0].activation_ns, bucketStartTimeNs + 10);
-    EXPECT_EQ(eventActivationMap[0].ttl_ns, 60 * 6 * NS_PER_SEC);
-    EXPECT_EQ(eventActivationMap[2].state, ActivationState::kActive);
-    EXPECT_EQ(eventActivationMap[2].activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
-    EXPECT_EQ(eventActivationMap[2].ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
 
+    // 4th processed event.
     event = CreateAppCrashEvent(666, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
     processor.OnLogEvent(event.get());
 
@@ -272,9 +409,1192 @@
               data.bucket_info(0).start_bucket_elapsed_nanos());
     EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs,
               data.bucket_info(0).end_bucket_elapsed_nanos());
-
 }
 
+TEST(MetricActivationE2eTest, TestCountMetricWithOneDeactivation) {
+    auto config = CreateStatsdConfigWithOneDeactivation();
+
+    int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
+    int64_t bucketSizeNs =
+            TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
+
+    int uid = 12345;
+    int64_t cfgId = 98765;
+    ConfigKey cfgKey(uid, cfgId);
+
+    sp<UidMap> m = new UidMap();
+    sp<StatsPullerManager> pullerManager = new StatsPullerManager();
+    sp<AlarmMonitor> anomalyAlarmMonitor;
+    sp<AlarmMonitor> subscriberAlarmMonitor;
+    vector<int64_t> activeConfigsBroadcast;
+
+    long timeBase1 = 1;
+    int broadcastCount = 0;
+    StatsLogProcessor processor(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor,
+            bucketStartTimeNs, [](const ConfigKey& key) { return true; },
+            [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
+                    const vector<int64_t>& activeConfigs) {
+                broadcastCount++;
+                EXPECT_EQ(broadcastUid, uid);
+                activeConfigsBroadcast.clear();
+                activeConfigsBroadcast.insert(activeConfigsBroadcast.end(),
+                        activeConfigs.begin(), activeConfigs.end());
+                return true;
+            });
+
+    processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
+
+    EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
+    sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
+    EXPECT_TRUE(metricsManager->isConfigValid());
+    EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+    sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+    auto& eventActivationMap = metricProducer->mEventActivationMap;
+    auto& eventDeactivationMap = metricProducer->mEventDeactivationMap;
+
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
+    // triggered by screen on event (tracker index 2).
+    EXPECT_EQ(eventActivationMap.size(), 2u);
+    EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
+    EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap.size(), 1u);
+    EXPECT_TRUE(eventDeactivationMap.find(3) != eventDeactivationMap.end());
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+
+    std::unique_ptr<LogEvent> event;
+
+    event = CreateAppCrashEvent(111, bucketStartTimeNs + 5);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 0);
+
+    // Activated by battery save mode.
+    event = CreateBatterySaverOnEvent(bucketStartTimeNs + 10);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 1);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+
+    // First processed event.
+    event = CreateAppCrashEvent(222, bucketStartTimeNs + 15);
+    processor.OnLogEvent(event.get());
+
+    // Activated by screen on event.
+    event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
+                                          bucketStartTimeNs + 20);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+
+    // 2nd processed event.
+    // The activation by screen_on event expires, but the one by battery save mode is still active.
+    event = CreateAppCrashEvent(333, bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    // No new broadcast since the config should still be active.
+    EXPECT_EQ(broadcastCount, 1);
+
+    // 3rd processed event.
+    event = CreateAppCrashEvent(444, bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
+    processor.OnLogEvent(event.get());
+
+    // All activations expired.
+    event = CreateAppCrashEvent(555, bucketStartTimeNs + NS_PER_SEC * 60 * 8);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    // New broadcast since the config is no longer active.
+    EXPECT_EQ(broadcastCount, 2);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+
+    // Re-activate metric via screen on.
+    event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
+                                          bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 3);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+
+    // 4th processed event.
+    event = CreateAppCrashEvent(666, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
+    processor.OnLogEvent(event.get());
+
+    // Re-enable battery saver mode activation.
+    event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 3);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+
+    // 5th processed event.
+    event = CreateAppCrashEvent(777, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
+    processor.OnLogEvent(event.get());
+
+    // Cancel battery saver mode activation.
+    event = CreateScreenBrightnessChangedEvent(64, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 3);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+
+    // Screen-on activation expired.
+    event = CreateAppCrashEvent(888, bucketStartTimeNs + NS_PER_SEC * 60 * 13);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    // New broadcast since the config is no longer active.
+    EXPECT_EQ(broadcastCount, 4);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+
+    event = CreateAppCrashEvent(999, bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
+    processor.OnLogEvent(event.get());
+
+    // Re-enable battery saver mode activation.
+    event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 5);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+
+    // Cancel battery saver mode activation.
+    event = CreateScreenBrightnessChangedEvent(140, bucketStartTimeNs + NS_PER_SEC * 60 * 16);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 6);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+
+    ConfigMetricsReportList reports;
+    vector<uint8_t> buffer;
+    processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
+                            ADB_DUMP, FAST, &buffer);
+    EXPECT_TRUE(buffer.size() > 0);
+    EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+    backfillDimensionPath(&reports);
+    backfillStartEndTimestamp(&reports);
+    EXPECT_EQ(1, reports.reports_size());
+    EXPECT_EQ(1, reports.reports(0).metrics_size());
+    EXPECT_EQ(5, reports.reports(0).metrics(0).count_metrics().data_size());
+
+    StatsLogReport::CountMetricDataWrapper countMetrics;
+    sortMetricDataByDimensionsValue(
+            reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+    EXPECT_EQ(5, countMetrics.data_size());
+
+    auto data = countMetrics.data(0);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(1);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(2);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    // Partial bucket as metric is deactivated.
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(3);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+              data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 13,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(4);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+              data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 13,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+}
+
+TEST(MetricActivationE2eTest, TestCountMetricWithTwoDeactivations) {
+    auto config = CreateStatsdConfigWithTwoDeactivations();
+
+    int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
+    int64_t bucketSizeNs =
+            TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
+
+    int uid = 12345;
+    int64_t cfgId = 98765;
+    ConfigKey cfgKey(uid, cfgId);
+
+    sp<UidMap> m = new UidMap();
+    sp<StatsPullerManager> pullerManager = new StatsPullerManager();
+    sp<AlarmMonitor> anomalyAlarmMonitor;
+    sp<AlarmMonitor> subscriberAlarmMonitor;
+    vector<int64_t> activeConfigsBroadcast;
+
+    long timeBase1 = 1;
+    int broadcastCount = 0;
+    StatsLogProcessor processor(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor,
+            bucketStartTimeNs, [](const ConfigKey& key) { return true; },
+            [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
+                    const vector<int64_t>& activeConfigs) {
+                broadcastCount++;
+                EXPECT_EQ(broadcastUid, uid);
+                activeConfigsBroadcast.clear();
+                activeConfigsBroadcast.insert(activeConfigsBroadcast.end(),
+                        activeConfigs.begin(), activeConfigs.end());
+                return true;
+            });
+
+    processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
+
+    EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
+    sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
+    EXPECT_TRUE(metricsManager->isConfigValid());
+    EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 1);
+    sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+    auto& eventActivationMap = metricProducer->mEventActivationMap;
+    auto& eventDeactivationMap = metricProducer->mEventDeactivationMap;
+
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
+    // triggered by screen on event (tracker index 2).
+    EXPECT_EQ(eventActivationMap.size(), 2u);
+    EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
+    EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap.size(), 2u);
+    EXPECT_TRUE(eventDeactivationMap.find(3) != eventDeactivationMap.end());
+    EXPECT_TRUE(eventDeactivationMap.find(4) != eventDeactivationMap.end());
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+
+    std::unique_ptr<LogEvent> event;
+
+    event = CreateAppCrashEvent(111, bucketStartTimeNs + 5);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 0);
+
+    // Activated by battery save mode.
+    event = CreateBatterySaverOnEvent(bucketStartTimeNs + 10);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 1);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+
+    // First processed event.
+    event = CreateAppCrashEvent(222, bucketStartTimeNs + 15);
+    processor.OnLogEvent(event.get());
+
+    // Activated by screen on event.
+    event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
+                                          bucketStartTimeNs + 20);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+
+    // 2nd processed event.
+    // The activation by screen_on event expires, but the one by battery save mode is still active.
+    event = CreateAppCrashEvent(333, bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+    // No new broadcast since the config should still be active.
+    EXPECT_EQ(broadcastCount, 1);
+
+    // 3rd processed event.
+    event = CreateAppCrashEvent(444, bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
+    processor.OnLogEvent(event.get());
+
+    // All activations expired.
+    event = CreateAppCrashEvent(555, bucketStartTimeNs + NS_PER_SEC * 60 * 8);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    // New broadcast since the config is no longer active.
+    EXPECT_EQ(broadcastCount, 2);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+
+    // Re-activate metric via screen on.
+    event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
+                                          bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 3);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+
+    // 4th processed event.
+    event = CreateAppCrashEvent(666, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
+    processor.OnLogEvent(event.get());
+
+    // Re-enable battery saver mode activation.
+    event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 3);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+
+    // 5th processed event.
+    event = CreateAppCrashEvent(777, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
+    processor.OnLogEvent(event.get());
+
+    // Cancel battery saver mode and screen on activation.
+    event = CreateScreenBrightnessChangedEvent(64, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    // New broadcast since the config is no longer active.
+    EXPECT_EQ(broadcastCount, 4);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+
+    // Screen-on activation expired.
+    event = CreateAppCrashEvent(888, bucketStartTimeNs + NS_PER_SEC * 60 * 13);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 4);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+
+    event = CreateAppCrashEvent(999, bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
+    processor.OnLogEvent(event.get());
+
+    // Re-enable battery saver mode activation.
+    event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 5);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+
+    // Cancel battery saver mode and screen on activation.
+    event = CreateScreenBrightnessChangedEvent(140, bucketStartTimeNs + NS_PER_SEC * 60 * 16);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    EXPECT_EQ(broadcastCount, 6);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+
+    ConfigMetricsReportList reports;
+    vector<uint8_t> buffer;
+    processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
+                            ADB_DUMP, FAST, &buffer);
+    EXPECT_TRUE(buffer.size() > 0);
+    EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+    backfillDimensionPath(&reports);
+    backfillStartEndTimestamp(&reports);
+    EXPECT_EQ(1, reports.reports_size());
+    EXPECT_EQ(1, reports.reports(0).metrics_size());
+    EXPECT_EQ(5, reports.reports(0).metrics(0).count_metrics().data_size());
+
+    StatsLogReport::CountMetricDataWrapper countMetrics;
+    sortMetricDataByDimensionsValue(
+            reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+    EXPECT_EQ(5, countMetrics.data_size());
+
+    auto data = countMetrics.data(0);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(1);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(2);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    // Partial bucket as metric is deactivated.
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(3);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+              data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(4);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+              data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+}
+
+TEST(MetricActivationE2eTest, TestCountMetricWithTwoMetricsTwoDeactivations) {
+    auto config = CreateStatsdConfigWithTwoMetricsTwoDeactivations();
+
+    int64_t bucketStartTimeNs = NS_PER_SEC * 10; // 10 secs
+    int64_t bucketSizeNs =
+            TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000LL * 1000LL;
+
+    int uid = 12345;
+    int64_t cfgId = 98765;
+    ConfigKey cfgKey(uid, cfgId);
+
+    sp<UidMap> m = new UidMap();
+    sp<StatsPullerManager> pullerManager = new StatsPullerManager();
+    sp<AlarmMonitor> anomalyAlarmMonitor;
+    sp<AlarmMonitor> subscriberAlarmMonitor;
+    vector<int64_t> activeConfigsBroadcast;
+
+    long timeBase1 = 1;
+    int broadcastCount = 0;
+    StatsLogProcessor processor(m, pullerManager, anomalyAlarmMonitor, subscriberAlarmMonitor,
+            bucketStartTimeNs, [](const ConfigKey& key) { return true; },
+            [&uid, &broadcastCount, &activeConfigsBroadcast](const int& broadcastUid,
+                    const vector<int64_t>& activeConfigs) {
+                broadcastCount++;
+                EXPECT_EQ(broadcastUid, uid);
+                activeConfigsBroadcast.clear();
+                activeConfigsBroadcast.insert(activeConfigsBroadcast.end(),
+                        activeConfigs.begin(), activeConfigs.end());
+                return true;
+            });
+
+    processor.OnConfigUpdated(bucketStartTimeNs, cfgKey, config);
+
+    EXPECT_EQ(processor.mMetricsManagers.size(), 1u);
+    sp<MetricsManager> metricsManager = processor.mMetricsManagers.begin()->second;
+    EXPECT_TRUE(metricsManager->isConfigValid());
+    EXPECT_EQ(metricsManager->mAllMetricProducers.size(), 2);
+    sp<MetricProducer> metricProducer = metricsManager->mAllMetricProducers[0];
+    auto& eventActivationMap = metricProducer->mEventActivationMap;
+    auto& eventDeactivationMap = metricProducer->mEventDeactivationMap;
+    sp<MetricProducer> metricProducer2 = metricsManager->mAllMetricProducers[1];
+    auto& eventActivationMap2 = metricProducer2->mEventActivationMap;
+    auto& eventDeactivationMap2 = metricProducer2->mEventDeactivationMap;
+
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    EXPECT_FALSE(metricProducer2->mIsActive);
+    // Two activations: one is triggered by battery saver mode (tracker index 0), the other is
+    // triggered by screen on event (tracker index 2).
+    EXPECT_EQ(eventActivationMap.size(), 2u);
+    EXPECT_TRUE(eventActivationMap.find(0) != eventActivationMap.end());
+    EXPECT_TRUE(eventActivationMap.find(2) != eventActivationMap.end());
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap.size(), 2u);
+    EXPECT_TRUE(eventDeactivationMap.find(3) != eventDeactivationMap.end());
+    EXPECT_TRUE(eventDeactivationMap.find(4) != eventDeactivationMap.end());
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+
+    EXPECT_EQ(eventActivationMap2.size(), 2u);
+    EXPECT_TRUE(eventActivationMap2.find(0) != eventActivationMap2.end());
+    EXPECT_TRUE(eventActivationMap2.find(2) != eventActivationMap2.end());
+    EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[0]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[2]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap2.size(), 2u);
+    EXPECT_TRUE(eventDeactivationMap2.find(3) != eventDeactivationMap2.end());
+    EXPECT_TRUE(eventDeactivationMap2.find(4) != eventDeactivationMap2.end());
+    EXPECT_EQ(eventDeactivationMap2[3], eventActivationMap2[0]);
+    EXPECT_EQ(eventDeactivationMap2[4], eventActivationMap2[2]);
+
+    std::unique_ptr<LogEvent> event;
+
+    event = CreateAppCrashEvent(111, bucketStartTimeNs + 5);
+    processor.OnLogEvent(event.get());
+    event = CreateMoveToForegroundEvent(1111, bucketStartTimeNs + 5);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_FALSE(metricProducer->mIsActive);
+    EXPECT_FALSE(metricProducer2->mIsActive);
+    EXPECT_EQ(broadcastCount, 0);
+
+    // Activated by battery save mode.
+    event = CreateBatterySaverOnEvent(bucketStartTimeNs + 10);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_EQ(broadcastCount, 1);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+    EXPECT_TRUE(metricProducer2->mIsActive);
+    EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap2[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[2]->activation_ns, 0);
+    EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap2[3], eventActivationMap2[0]);
+    EXPECT_EQ(eventDeactivationMap2[4], eventActivationMap2[2]);
+
+    // First processed event.
+    event = CreateAppCrashEvent(222, bucketStartTimeNs + 15);
+    processor.OnLogEvent(event.get());
+    event = CreateMoveToForegroundEvent(2222, bucketStartTimeNs + 15);
+    processor.OnLogEvent(event.get());
+
+    // Activated by screen on event.
+    event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
+                                          bucketStartTimeNs + 20);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+    EXPECT_TRUE(metricProducer2->mIsActive);
+    EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap2[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap2[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap2[3], eventActivationMap2[0]);
+    EXPECT_EQ(eventDeactivationMap2[4], eventActivationMap2[2]);
+
+    // 2nd processed event.
+    // The activation by screen_on event expires, but the one by battery save mode is still active.
+    event = CreateAppCrashEvent(333, bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
+    processor.OnLogEvent(event.get());
+    event = CreateMoveToForegroundEvent(3333, bucketStartTimeNs + NS_PER_SEC * 60 * 2 + 25);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+    EXPECT_TRUE(metricProducer2->mIsActive);
+    EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap2[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap2[3], eventActivationMap2[0]);
+    EXPECT_EQ(eventDeactivationMap2[4], eventActivationMap2[2]);
+    // No new broadcast since the config should still be active.
+    EXPECT_EQ(broadcastCount, 1);
+
+    // 3rd processed event.
+    event = CreateAppCrashEvent(444, bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
+    processor.OnLogEvent(event.get());
+    event = CreateMoveToForegroundEvent(4444, bucketStartTimeNs + NS_PER_SEC * 60 * 5 + 25);
+    processor.OnLogEvent(event.get());
+
+    // All activations expired.
+    event = CreateAppCrashEvent(555, bucketStartTimeNs + NS_PER_SEC * 60 * 8);
+    processor.OnLogEvent(event.get());
+    event = CreateMoveToForegroundEvent(5555, bucketStartTimeNs + NS_PER_SEC * 60 * 8);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    // New broadcast since the config is no longer active.
+    EXPECT_EQ(broadcastCount, 2);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+    EXPECT_FALSE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+    EXPECT_FALSE(metricProducer2->mIsActive);
+    EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[2]->activation_ns, bucketStartTimeNs + 20);
+    EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap2[3], eventActivationMap2[0]);
+    EXPECT_EQ(eventDeactivationMap2[4], eventActivationMap2[2]);
+
+    // Re-activate metric via screen on.
+    event = CreateScreenStateChangedEvent(android::view::DISPLAY_STATE_ON,
+                                          bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_EQ(broadcastCount, 3);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+    EXPECT_TRUE(metricProducer2->mIsActive);
+    EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[0]->activation_ns, bucketStartTimeNs + 10);
+    EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap2[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap2[3], eventActivationMap2[0]);
+    EXPECT_EQ(eventDeactivationMap2[4], eventActivationMap2[2]);
+
+    // 4th processed event.
+    event = CreateAppCrashEvent(666, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
+    processor.OnLogEvent(event.get());
+    event = CreateMoveToForegroundEvent(6666, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 1);
+    processor.OnLogEvent(event.get());
+
+    // Re-enable battery saver mode activation.
+    event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_EQ(broadcastCount, 3);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+    EXPECT_TRUE(metricProducer2->mIsActive);
+    EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap2[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap2[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap2[3], eventActivationMap2[0]);
+    EXPECT_EQ(eventDeactivationMap2[4], eventActivationMap2[2]);
+
+    // 5th processed event.
+    event = CreateAppCrashEvent(777, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
+    processor.OnLogEvent(event.get());
+    event = CreateMoveToForegroundEvent(7777, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 40);
+    processor.OnLogEvent(event.get());
+
+    // Cancel battery saver mode and screen on activation.
+    event = CreateScreenBrightnessChangedEvent(64, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 60);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    // New broadcast since the config is no longer active.
+    EXPECT_EQ(broadcastCount, 4);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+    EXPECT_FALSE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+    EXPECT_FALSE(metricProducer2->mIsActive);
+    EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap2[3], eventActivationMap2[0]);
+    EXPECT_EQ(eventDeactivationMap2[4], eventActivationMap2[2]);
+
+    // Screen-on activation expired.
+    event = CreateAppCrashEvent(888, bucketStartTimeNs + NS_PER_SEC * 60 * 13);
+    processor.OnLogEvent(event.get());
+    event = CreateMoveToForegroundEvent(8888, bucketStartTimeNs + NS_PER_SEC * 60 * 13);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_EQ(broadcastCount, 4);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+    EXPECT_FALSE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+    EXPECT_FALSE(metricProducer2->mIsActive);
+    EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 11 + 15);
+    EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap2[3], eventActivationMap2[0]);
+    EXPECT_EQ(eventDeactivationMap2[4], eventActivationMap2[2]);
+
+    event = CreateAppCrashEvent(999, bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
+    processor.OnLogEvent(event.get());
+    event = CreateMoveToForegroundEvent(9999, bucketStartTimeNs + NS_PER_SEC * 60 * 14 + 1);
+    processor.OnLogEvent(event.get());
+
+    // Re-enable battery saver mode activation.
+    event = CreateBatterySaverOnEvent(bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+    processor.OnLogEvent(event.get());
+    EXPECT_TRUE(metricsManager->isActive());
+    EXPECT_EQ(broadcastCount, 5);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 1);
+    EXPECT_EQ(activeConfigsBroadcast[0], cfgId);
+    EXPECT_TRUE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+    EXPECT_TRUE(metricProducer2->mIsActive);
+    EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kActive);
+    EXPECT_EQ(eventActivationMap2[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+    EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap2[3], eventActivationMap2[0]);
+    EXPECT_EQ(eventDeactivationMap2[4], eventActivationMap2[2]);
+
+    // Cancel battery saver mode and screen on activation.
+    event = CreateScreenBrightnessChangedEvent(140, bucketStartTimeNs + NS_PER_SEC * 60 * 16);
+    processor.OnLogEvent(event.get());
+    EXPECT_FALSE(metricsManager->isActive());
+    EXPECT_EQ(broadcastCount, 6);
+    EXPECT_EQ(activeConfigsBroadcast.size(), 0);
+    EXPECT_FALSE(metricProducer->mIsActive);
+    EXPECT_EQ(eventActivationMap[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+    EXPECT_EQ(eventActivationMap[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap[3], eventActivationMap[0]);
+    EXPECT_EQ(eventDeactivationMap[4], eventActivationMap[2]);
+    EXPECT_FALSE(metricProducer2->mIsActive);
+    EXPECT_EQ(eventActivationMap2[0]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[0]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 15);
+    EXPECT_EQ(eventActivationMap2[0]->ttl_ns, 60 * 6 * NS_PER_SEC);
+    EXPECT_EQ(eventActivationMap2[2]->state, ActivationState::kNotActive);
+    EXPECT_EQ(eventActivationMap2[2]->activation_ns, bucketStartTimeNs + NS_PER_SEC * 60 * 10 + 10);
+    EXPECT_EQ(eventActivationMap2[2]->ttl_ns, 60 * 2 * NS_PER_SEC);
+    EXPECT_EQ(eventDeactivationMap2[3], eventActivationMap2[0]);
+    EXPECT_EQ(eventDeactivationMap2[4], eventActivationMap2[2]);
+
+    ConfigMetricsReportList reports;
+    vector<uint8_t> buffer;
+    processor.onDumpReport(cfgKey, bucketStartTimeNs + NS_PER_SEC * 60 * 15 + 1, false, true,
+                            ADB_DUMP, FAST, &buffer);
+    EXPECT_TRUE(buffer.size() > 0);
+    EXPECT_TRUE(reports.ParseFromArray(&buffer[0], buffer.size()));
+    backfillDimensionPath(&reports);
+    backfillStartEndTimestamp(&reports);
+    EXPECT_EQ(1, reports.reports_size());
+    EXPECT_EQ(2, reports.reports(0).metrics_size());
+    EXPECT_EQ(5, reports.reports(0).metrics(0).count_metrics().data_size());
+    EXPECT_EQ(5, reports.reports(0).metrics(1).count_metrics().data_size());
+
+    StatsLogReport::CountMetricDataWrapper countMetrics;
+
+    sortMetricDataByDimensionsValue(
+            reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+    EXPECT_EQ(5, countMetrics.data_size());
+
+    auto data = countMetrics.data(0);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(1);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(2);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    // Partial bucket as metric is deactivated.
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(3);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+              data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(4);
+    EXPECT_EQ(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+              data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+
+
+   countMetrics.clear_data();
+    sortMetricDataByDimensionsValue(
+            reports.reports(0).metrics(1).count_metrics(), &countMetrics);
+    EXPECT_EQ(5, countMetrics.data_size());
+
+    data = countMetrics.data(0);
+    EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(2222, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(1);
+    EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(3333, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(2);
+    EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(4444, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    // Partial bucket as metric is deactivated.
+    EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 8,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(3);
+    EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(6666, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+              data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+
+    data = countMetrics.data(4);
+    EXPECT_EQ(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, data.dimensions_in_what().field());
+    EXPECT_EQ(1, data.dimensions_in_what().value_tuple().dimensions_value_size());
+    EXPECT_EQ(1 /* uid field */,
+              data.dimensions_in_what().value_tuple().dimensions_value(0).field());
+    EXPECT_EQ(7777, data.dimensions_in_what().value_tuple().dimensions_value(0).value_int());
+    EXPECT_EQ(1, data.bucket_info_size());
+    EXPECT_EQ(1, data.bucket_info(0).count());
+    EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs,
+              data.bucket_info(0).start_bucket_elapsed_nanos());
+    EXPECT_EQ(bucketStartTimeNs + NS_PER_SEC * 60 * 11,
+              data.bucket_info(0).end_bucket_elapsed_nanos());
+}
 
 #else
 GTEST_LOG_(INFO) << "This test does nothing.\n";
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index b2b1e77..38006dc 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -5920,6 +5920,10 @@
                                                 UserHandle.myUserId());
         VMRuntime.setProcessPackageName(data.appInfo.packageName);
 
+        // Pass data directory path to ART. This is used for caching information and
+        // should be set before any application code is loaded.
+        VMRuntime.setProcessDataDirectory(data.appInfo.dataDir);
+
         if (mProfiler.profileFd != null) {
             mProfiler.startProfiling();
         }
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 8a52265..83c5e20 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -2147,8 +2147,8 @@
         public static final int UPDATE_ERROR_INCORRECT_OS_VERSION = 2;
 
         /**
-         * Represents the update file being wrong, i.e. payloads are mismatched, wrong compressions
-         * method.
+         * Represents the update file being wrong; e.g. payloads are mismatched, or the wrong
+         * compression method is used.
          */
         public static final int UPDATE_ERROR_UPDATE_FILE_INVALID = 3;
 
diff --git a/core/java/android/content/LoggingContentInterface.java b/core/java/android/content/LoggingContentInterface.java
index 6e12a57..83c0c91 100644
--- a/core/java/android/content/LoggingContentInterface.java
+++ b/core/java/android/content/LoggingContentInterface.java
@@ -48,191 +48,197 @@
         this.delegate = delegate;
     }
 
-    private void log(String method, Object res, Object... args) {
-        // First, force-unparcel any bundles so we can log them
-        for (Object arg : args) {
-            if (arg instanceof Bundle) {
-                ((Bundle) arg).size();
+    private class Logger implements AutoCloseable {
+        private final StringBuilder sb = new StringBuilder();
+
+        public Logger(String method, Object... args) {
+            // First, force-unparcel any bundles so we can log them
+            for (Object arg : args) {
+                if (arg instanceof Bundle) {
+                    ((Bundle) arg).size();
+                }
+            }
+
+            sb.append("callingUid=").append(Binder.getCallingUid()).append(' ');
+            sb.append(method);
+            sb.append('(').append(deepToString(args)).append(')');
+        }
+
+        private String deepToString(Object value) {
+            if (value != null && value.getClass().isArray()) {
+                return Arrays.deepToString((Object[]) value);
+            } else {
+                return String.valueOf(value);
             }
         }
 
-        final StringBuilder sb = new StringBuilder();
-        sb.append("callingUid=").append(Binder.getCallingUid()).append(' ');
-        sb.append(method);
-        sb.append('(').append(deepToString(args)).append(')');
-        if (res instanceof Cursor) {
-            sb.append('\n');
-            DatabaseUtils.dumpCursor((Cursor) res, sb);
-        } else {
-            sb.append(" = ").append(deepToString(res));
+        public <T> T setResult(T res) {
+            if (res instanceof Cursor) {
+                sb.append('\n');
+                DatabaseUtils.dumpCursor((Cursor) res, sb);
+            } else {
+                sb.append(" = ").append(deepToString(res));
+            }
+            return res;
         }
 
-        if (res instanceof Exception) {
-            Log.e(tag, sb.toString());
-        } else {
+        @Override
+        public void close() {
             Log.v(tag, sb.toString());
         }
     }
 
-    private String deepToString(Object value) {
-        if (value != null && value.getClass().isArray()) {
-            return Arrays.deepToString((Object[]) value);
-        } else {
-            return String.valueOf(value);
-        }
-    }
-
     @Override
     public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
             @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal)
             throws RemoteException {
-        try {
-            final Cursor res = delegate.query(uri, projection, queryArgs, cancellationSignal);
-            log("query", res, uri, projection, queryArgs, cancellationSignal);
-            return res;
-        } catch (Exception res) {
-            log("query", res, uri, projection, queryArgs, cancellationSignal);
-            throw res;
+        try (Logger l = new Logger("query", uri, projection, queryArgs, cancellationSignal)) {
+            try {
+                return l.setResult(delegate.query(uri, projection, queryArgs, cancellationSignal));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public @Nullable String getType(@NonNull Uri uri) throws RemoteException {
-        try {
-            final String res = delegate.getType(uri);
-            log("getType", res, uri);
-            return res;
-        } catch (Exception res) {
-            log("getType", res, uri);
-            throw res;
+        try (Logger l = new Logger("getType", uri)) {
+            try {
+                return l.setResult(delegate.getType(uri));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter)
             throws RemoteException {
-        try {
-            final String[] res = delegate.getStreamTypes(uri, mimeTypeFilter);
-            log("getStreamTypes", res, uri, mimeTypeFilter);
-            return res;
-        } catch (Exception res) {
-            log("getStreamTypes", res, uri, mimeTypeFilter);
-            throw res;
+        try (Logger l = new Logger("getStreamTypes", uri, mimeTypeFilter)) {
+            try {
+                return l.setResult(delegate.getStreamTypes(uri, mimeTypeFilter));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public @Nullable Uri canonicalize(@NonNull Uri uri) throws RemoteException {
-        try {
-            final Uri res = delegate.canonicalize(uri);
-            log("canonicalize", res, uri);
-            return res;
-        } catch (Exception res) {
-            log("canonicalize", res, uri);
-            throw res;
+        try (Logger l = new Logger("canonicalize", uri)) {
+            try {
+                return l.setResult(delegate.canonicalize(uri));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public @Nullable Uri uncanonicalize(@NonNull Uri uri) throws RemoteException {
-        try {
-            final Uri res = delegate.uncanonicalize(uri);
-            log("uncanonicalize", res, uri);
-            return res;
-        } catch (Exception res) {
-            log("uncanonicalize", res, uri);
-            throw res;
+        try (Logger l = new Logger("uncanonicalize", uri)) {
+            try {
+                return l.setResult(delegate.uncanonicalize(uri));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public boolean refresh(@NonNull Uri uri, @Nullable Bundle args,
             @Nullable CancellationSignal cancellationSignal) throws RemoteException {
-        try {
-            final boolean res = delegate.refresh(uri, args, cancellationSignal);
-            log("refresh", res, uri, args, cancellationSignal);
-            return res;
-        } catch (Exception res) {
-            log("refresh", res, uri, args, cancellationSignal);
-            throw res;
+        try (Logger l = new Logger("refresh", uri, args, cancellationSignal)) {
+            try {
+                return l.setResult(delegate.refresh(uri, args, cancellationSignal));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues initialValues)
             throws RemoteException {
-        try {
-            final Uri res = delegate.insert(uri, initialValues);
-            log("insert", res, uri, initialValues);
-            return res;
-        } catch (Exception res) {
-            log("insert", res, uri, initialValues);
-            throw res;
+        try (Logger l = new Logger("insert", uri, initialValues)) {
+            try {
+                return l.setResult(delegate.insert(uri, initialValues));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] initialValues)
             throws RemoteException {
-        try {
-            final int res = delegate.bulkInsert(uri, initialValues);
-            log("bulkInsert", res, uri, initialValues);
-            return res;
-        } catch (Exception res) {
-            log("bulkInsert", res, uri, initialValues);
-            throw res;
+        try (Logger l = new Logger("bulkInsert", uri, initialValues)) {
+            try {
+                return l.setResult(delegate.bulkInsert(uri, initialValues));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public int delete(@NonNull Uri uri, @Nullable String selection,
             @Nullable String[] selectionArgs) throws RemoteException {
-        try {
-            final int res = delegate.delete(uri, selection, selectionArgs);
-            log("delete", res, uri, selection, selectionArgs);
-            return res;
-        } catch (Exception res) {
-            log("delete", res, uri, selection, selectionArgs);
-            throw res;
+        try (Logger l = new Logger("delete", uri, selection, selectionArgs)) {
+            try {
+                return l.setResult(delegate.delete(uri, selection, selectionArgs));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection,
             @Nullable String[] selectionArgs) throws RemoteException {
-        try {
-            final int res = delegate.update(uri, values, selection, selectionArgs);
-            log("update", res, uri, values, selection, selectionArgs);
-            return res;
-        } catch (Exception res) {
-            log("update", res, uri, values, selection, selectionArgs);
-            throw res;
+        try (Logger l = new Logger("update", uri, values, selection, selectionArgs)) {
+            try {
+                return l.setResult(delegate.update(uri, values, selection, selectionArgs));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
             @Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
-        try {
-            final ParcelFileDescriptor res = delegate.openFile(uri, mode, signal);
-            log("openFile", res, uri, mode, signal);
-            return res;
-        } catch (Exception res) {
-            log("openFile", res, uri, mode, signal);
-            throw res;
+        try (Logger l = new Logger("openFile", uri, mode, signal)) {
+            try {
+                return l.setResult(delegate.openFile(uri, mode, signal));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
             @Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
-        try {
-            final AssetFileDescriptor res = delegate.openAssetFile(uri, mode, signal);
-            log("openAssetFile", res, uri, mode, signal);
-            return res;
-        } catch (Exception res) {
-            log("openAssetFile", res, uri, mode, signal);
-            throw res;
+        try (Logger l = new Logger("openAssetFile", uri, mode, signal)) {
+            try {
+                return l.setResult(delegate.openAssetFile(uri, mode, signal));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
@@ -240,13 +246,13 @@
     public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
             @NonNull String mimeTypeFilter, @Nullable Bundle opts,
             @Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
-        try {
-            final AssetFileDescriptor res = delegate.openTypedAssetFile(uri, mimeTypeFilter, opts, signal);
-            log("openTypedAssetFile", res, uri, mimeTypeFilter, opts, signal);
-            return res;
-        } catch (Exception res) {
-            log("openTypedAssetFile", res, uri, mimeTypeFilter, opts, signal);
-            throw res;
+        try (Logger l = new Logger("openTypedAssetFile", uri, mimeTypeFilter, opts, signal)) {
+            try {
+                return l.setResult(delegate.openTypedAssetFile(uri, mimeTypeFilter, opts, signal));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
@@ -254,26 +260,26 @@
     public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
             @NonNull ArrayList<ContentProviderOperation> operations)
             throws RemoteException, OperationApplicationException {
-        try {
-            final ContentProviderResult[] res = delegate.applyBatch(authority, operations);
-            log("applyBatch", res, authority, operations);
-            return res;
-        } catch (Exception res) {
-            log("applyBatch", res, authority, operations);
-            throw res;
+        try (Logger l = new Logger("applyBatch", authority, operations)) {
+            try {
+                return l.setResult(delegate.applyBatch(authority, operations));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 
     @Override
     public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
             @Nullable String arg, @Nullable Bundle extras) throws RemoteException {
-        try {
-            final Bundle res = delegate.call(authority, method, arg, extras);
-            log("call", res, authority, method, arg, extras);
-            return res;
-        } catch (Exception res) {
-            log("call", res, authority, method, arg, extras);
-            throw res;
+        try (Logger l = new Logger("call", authority, method, arg, extras)) {
+            try {
+                return l.setResult(delegate.call(authority, method, arg, extras));
+            } catch (Exception res) {
+                l.setResult(res);
+                throw res;
+            }
         }
     }
 }
diff --git a/core/java/android/content/om/OverlayInfo.java b/core/java/android/content/om/OverlayInfo.java
index 91424f4..fc79a42 100644
--- a/core/java/android/content/om/OverlayInfo.java
+++ b/core/java/android/content/om/OverlayInfo.java
@@ -255,7 +255,7 @@
      * @hide
      */
     @SystemApi
-    @Nullable
+    @NonNull
     public String getTargetPackageName() {
         return targetPackageName;
     }
diff --git a/core/java/android/database/CursorWindow.java b/core/java/android/database/CursorWindow.java
index 44bd883..647448c 100644
--- a/core/java/android/database/CursorWindow.java
+++ b/core/java/android/database/CursorWindow.java
@@ -61,7 +61,10 @@
 
     private final CloseGuard mCloseGuard = CloseGuard.get();
 
+    // May throw CursorWindowAllocationException
     private static native long nativeCreate(String name, int cursorWindowSize);
+
+    // May throw CursorWindowAllocationException
     private static native long nativeCreateFromParcel(Parcel parcel);
     private static native void nativeDispose(long windowPtr);
     private static native void nativeWriteToParcel(long windowPtr, Parcel parcel);
@@ -135,8 +138,7 @@
         mName = name != null && name.length() != 0 ? name : "<unnamed>";
         mWindowPtr = nativeCreate(mName, (int) windowSizeBytes);
         if (mWindowPtr == 0) {
-            throw new CursorWindowAllocationException("Cursor window allocation of " +
-                    windowSizeBytes + " bytes failed. " + printStats());
+            throw new IllegalStateException(); // Shouldn't happen.
         }
         mCloseGuard.open("close");
         recordNewWindow(Binder.getCallingPid(), mWindowPtr);
@@ -164,8 +166,7 @@
         mStartPos = source.readInt();
         mWindowPtr = nativeCreateFromParcel(source);
         if (mWindowPtr == 0) {
-            throw new CursorWindowAllocationException("Cursor window could not be "
-                    + "created from binder.");
+            throw new IllegalStateException(); // Shouldn't happen.
         }
         mName = nativeGetName(mWindowPtr);
         mCloseGuard.open("close");
diff --git a/core/java/android/hardware/input/IInputManager.aidl b/core/java/android/hardware/input/IInputManager.aidl
index 2923bbf..0daf30f25 100644
--- a/core/java/android/hardware/input/IInputManager.aidl
+++ b/core/java/android/hardware/input/IInputManager.aidl
@@ -16,6 +16,7 @@
 
 package android.hardware.input;
 
+import android.graphics.Rect;
 import android.hardware.input.InputDeviceIdentifier;
 import android.hardware.input.KeyboardLayout;
 import android.hardware.input.IInputDevicesChangedListener;
@@ -24,6 +25,7 @@
 import android.os.IBinder;
 import android.view.InputDevice;
 import android.view.InputEvent;
+import android.view.InputMonitor;
 import android.view.PointerIcon;
 
 /** @hide */
@@ -82,4 +84,7 @@
     void setCustomPointerIcon(in PointerIcon icon);
 
     void requestPointerCapture(IBinder windowToken, boolean enabled);
+
+    /** Create an input monitor for gestures. */
+    InputMonitor monitorGestureInput(String name, int displayId);
 }
diff --git a/core/java/android/hardware/input/InputManager.java b/core/java/android/hardware/input/InputManager.java
index fec5c34..2a59be2 100644
--- a/core/java/android/hardware/input/InputManager.java
+++ b/core/java/android/hardware/input/InputManager.java
@@ -41,6 +41,7 @@
 import android.util.SparseArray;
 import android.view.InputDevice;
 import android.view.InputEvent;
+import android.view.InputMonitor;
 import android.view.MotionEvent;
 import android.view.PointerIcon;
 
@@ -933,6 +934,19 @@
         }
     }
 
+    /**
+     * Monitor input on the specified display for gestures.
+     *
+     * @hide
+     */
+    public InputMonitor monitorGestureInput(String name, int displayId) {
+        try {
+            return mIm.monitorGestureInput(name, displayId);
+        } catch (RemoteException ex) {
+            throw ex.rethrowFromSystemServer();
+        }
+    }
+
     private void populateInputDevicesLocked() {
         if (mInputDevicesChangedListener == null) {
             final InputDevicesChangedListener listener = new InputDevicesChangedListener();
diff --git a/core/java/android/nfc/cardemulation/CardEmulation.java b/core/java/android/nfc/cardemulation/CardEmulation.java
index f23dc2d..c13f64e 100644
--- a/core/java/android/nfc/cardemulation/CardEmulation.java
+++ b/core/java/android/nfc/cardemulation/CardEmulation.java
@@ -34,6 +34,7 @@
 
 import java.util.HashMap;
 import java.util.List;
+import java.util.regex.Pattern;
 
 /**
  * This class can be used to query the state of
@@ -48,6 +49,7 @@
  * on the device.
  */
 public final class CardEmulation {
+    private static final Pattern AID_PATTERN = Pattern.compile("[0-9A-Fa-f]{10,32}\\*?\\#?");
     static final String TAG = "CardEmulation";
 
     /**
@@ -732,7 +734,7 @@
         }
 
         // Verify hex characters
-        if (!aid.matches("[0-9A-Fa-f]{10,32}\\*?\\#?")) {
+        if (!AID_PATTERN.matcher(aid).matches()) {
             Log.e(TAG, "AID " + aid + " is not a valid AID.");
             return false;
         }
diff --git a/core/java/android/os/Binder.java b/core/java/android/os/Binder.java
index eb91860..66ddf21 100644
--- a/core/java/android/os/Binder.java
+++ b/core/java/android/os/Binder.java
@@ -444,24 +444,20 @@
      *
      * @param workSource The original UID responsible for the binder call.
      * @return token to restore original work source.
-     * @hide
      **/
     @CriticalNative
-    @SystemApi
     public static final native long setCallingWorkSourceUid(int workSource);
 
     /**
      * Returns the work source set by the caller.
      *
      * Unlike {@link Binder#getCallingUid()}, this result of this method cannot be trusted. The
-     * caller can set the value to whatever he wants. Only use this value if you trust the calling
+     * caller can set the value to whatever they want. Only use this value if you trust the calling
      * uid.
      *
      * @return The original UID responsible for the binder transaction.
-     * @hide
      */
     @CriticalNative
-    @SystemApi
     public static final native int getCallingWorkSourceUid();
 
     /**
@@ -484,10 +480,8 @@
      * </pre>
      *
      * @return token to restore original work source.
-     * @hide
      **/
     @CriticalNative
-    @SystemApi
     public static final native long clearCallingWorkSource();
 
     /**
@@ -503,11 +497,8 @@
      *   Binder.restoreCallingWorkSource(token);
      * }
      * </pre>
-     *
-     * @hide
      **/
     @CriticalNative
-    @SystemApi
     public static final native void restoreCallingWorkSource(long token);
 
     /**
diff --git a/core/java/android/provider/CallLog.java b/core/java/android/provider/CallLog.java
index 44adc1c..ef28f07 100644
--- a/core/java/android/provider/CallLog.java
+++ b/core/java/android/provider/CallLog.java
@@ -35,7 +35,6 @@
 import android.provider.ContactsContract.CommonDataKinds.Phone;
 import android.provider.ContactsContract.Data;
 import android.provider.ContactsContract.DataUsageFeedback;
-import android.telecom.CallIdentification;
 import android.telecom.PhoneAccount;
 import android.telecom.PhoneAccountHandle;
 import android.telecom.TelecomManager;
@@ -605,69 +604,6 @@
         public static final String BLOCK_REASON = "block_reason";
 
         /**
-         * The package name of the {@link android.telecom.CallScreeningService} which provided
-         * {@link android.telecom.CallIdentification} for this call.
-         * <P>Type: TEXT</P>
-         */
-        public static final String CALL_ID_PACKAGE_NAME = "call_id_package_name";
-
-        /**
-         * The app name of the {@link android.telecom.CallScreeningService} which provided
-         * {@link android.telecom.CallIdentification} for this call.
-         * <P>Type: TEXT</P>
-         */
-        public static final String CALL_ID_APP_NAME = "call_id_app_name";
-
-        /**
-         * The {@link CallIdentification#getName() name} of a call, as provided by the
-         * {@link android.telecom.CallScreeningService}.
-         * <p>
-         * The name is provided by the app identified by {@link #CALL_ID_PACKAGE_NAME} and
-         * {@link #CALL_ID_APP_NAME}.
-         * <P>Type: TEXT</P>
-         */
-        public static final String CALL_ID_NAME = "call_id_name";
-
-        /**
-         * The {@link CallIdentification#getDescription() description} of a call, as provided by the
-         * {@link android.telecom.CallScreeningService}.
-         * <p>
-         * The description is provided by the app identified by {@link #CALL_ID_PACKAGE_NAME} and
-         * {@link #CALL_ID_APP_NAME}.
-         * <P>Type: TEXT</P>
-         */
-        public static final String CALL_ID_DESCRIPTION = "call_id_description";
-
-        /**
-         * The {@link CallIdentification#getDetails() details} of a call, as provided by the
-         * {@link android.telecom.CallScreeningService}.
-         * <p>
-         * The details field is provided by the app identified by {@link #CALL_ID_PACKAGE_NAME} and
-         * {@link #CALL_ID_APP_NAME}.
-         * <P>Type: TEXT</P>
-         */
-        public static final String CALL_ID_DETAILS = "call_id_details";
-
-        /**
-         * The {@link CallIdentification#getNuisanceConfidence() nuisance confidence} of a call, as
-         * provided by the {@link android.telecom.CallScreeningService}.
-         * <p>
-         * Valid values are defined in {@link CallIdentification}, and include:
-         * <ul>
-         *     <li>{@link CallIdentification#CONFIDENCE_NOT_NUISANCE}</li>
-         *     <li>{@link CallIdentification#CONFIDENCE_LIKELY_NOT_NUISANCE}</li>
-         *     <li>{@link CallIdentification#CONFIDENCE_UNKNOWN}</li>
-         *     <li>{@link CallIdentification#CONFIDENCE_LIKELY_NUISANCE}</li>
-         *     <li>{@link CallIdentification#CONFIDENCE_NUISANCE}</li>
-         * </ul>
-         * <p>
-         * The nuisance confidence is provided by the app identified by
-         * {@link #CALL_ID_PACKAGE_NAME} and {@link #CALL_ID_APP_NAME}.
-         * <P>Type: INTEGER</P>
-         */
-        public static final String CALL_ID_NUISANCE_CONFIDENCE = "call_id_nuisance_confidence";
-
-        /**
          * Adds a call to the call log.
          *
          * @param ci the CallerInfo object to get the target contact from.  Can be null
@@ -696,8 +632,7 @@
                 presentation, callType, features, accountHandle, start, duration,
                 dataUsage, false /* addForAllUsers */, null /* userToBeInsertedTo */,
                 false /* isRead */, Calls.BLOCK_REASON_NOT_BLOCKED /* callBlockReason */,
-                null /* callScreeningAppName */, null /* callScreeningComponentName */,
-                null /* callIdentification */);
+                null /* callScreeningAppName */, null /* callScreeningComponentName */);
         }
 
 
@@ -737,8 +672,7 @@
                 features, accountHandle, start, duration, dataUsage, addForAllUsers,
                 userToBeInsertedTo, false /* isRead */ , Calls.BLOCK_REASON_NOT_BLOCKED
                 /* callBlockReason */, null /* callScreeningAppName */,
-                null /* callScreeningComponentName */,
-                null /* callIdentification */);
+                null /* callScreeningComponentName */);
         }
 
         /**
@@ -784,7 +718,7 @@
                 int features, PhoneAccountHandle accountHandle, long start, int duration,
                 Long dataUsage, boolean addForAllUsers, UserHandle userToBeInsertedTo,
                 boolean isRead, int callBlockReason, CharSequence callScreeningAppName,
-                String callScreeningComponentName, CallIdentification callIdentification) {
+                String callScreeningComponentName) {
             if (VERBOSE_LOG) {
                 Log.v(LOG_TAG, String.format("Add call: number=%s, user=%s, for all=%s",
                         number, userToBeInsertedTo, addForAllUsers));
@@ -839,26 +773,6 @@
             values.put(CALL_SCREENING_APP_NAME, charSequenceToString(callScreeningAppName));
             values.put(CALL_SCREENING_COMPONENT_NAME, callScreeningComponentName);
 
-            if (callIdentification != null) {
-                values.put(CALL_ID_PACKAGE_NAME, callIdentification.getCallScreeningPackageName());
-                values.put(CALL_ID_APP_NAME,
-                        charSequenceToString(callIdentification.getCallScreeningAppName()));
-                values.put(CALL_ID_NAME,
-                        charSequenceToString(callIdentification.getName()));
-                values.put(CALL_ID_DESCRIPTION,
-                        charSequenceToString(callIdentification.getDescription()));
-                values.put(CALL_ID_DETAILS,
-                        charSequenceToString(callIdentification.getDetails()));
-                values.put(CALL_ID_NUISANCE_CONFIDENCE, callIdentification.getNuisanceConfidence());
-            } else {
-                values.putNull(CALL_ID_PACKAGE_NAME);
-                values.putNull(CALL_ID_APP_NAME);
-                values.putNull(CALL_ID_NAME);
-                values.putNull(CALL_ID_DESCRIPTION);
-                values.putNull(CALL_ID_DETAILS);
-                values.putNull(CALL_ID_NUISANCE_CONFIDENCE);
-            }
-
             if ((ci != null) && (ci.contactIdOrZero > 0)) {
                 // Update usage information for the number associated with the contact ID.
                 // We need to use both the number and the ID for obtaining a data ID since other
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 227c9d4..85feac8 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -8654,9 +8654,10 @@
                 "location_permissions_upgrade_to_q_mode";
 
         /**
-         * Comma separated list of enabled overlay packages for all android.theme.customization.*
-         * categories. If there is no corresponding package included for a category, then all
-         * overlay packages in that category must be disabled.
+         * Map of android.theme.customization.* categories to the enabled overlay package for that
+         * category, formatted as a serialized {@link org.json.JSONObject}. If there is no
+         * corresponding package included for a category, then all overlay packages in that
+         * category must be disabled.
          * @hide
          */
         @SystemApi
@@ -8664,7 +8665,7 @@
                 "theme_customization_overlay_packages";
 
         private static final Validator THEME_CUSTOMIZATION_OVERLAY_PACKAGES_VALIDATOR =
-                new SettingsValidators.PackageNameListValidator(",");
+                SettingsValidators.JSON_OBJECT_VALIDATOR;
 
         /**
          * Controls whether aware is enabled.
diff --git a/core/java/android/provider/SettingsValidators.java b/core/java/android/provider/SettingsValidators.java
index 25e77867..4051213 100644
--- a/core/java/android/provider/SettingsValidators.java
+++ b/core/java/android/provider/SettingsValidators.java
@@ -19,9 +19,13 @@
 import android.annotation.Nullable;
 import android.content.ComponentName;
 import android.net.Uri;
+import android.text.TextUtils;
 
 import com.android.internal.util.ArrayUtils;
 
+import org.json.JSONException;
+import org.json.JSONObject;
+
 import java.util.Locale;
 
 /**
@@ -162,6 +166,19 @@
         }
     };
 
+    /** {@link Validator} that checks whether a value is a valid {@link JSONObject}. */
+    public static final Validator JSON_OBJECT_VALIDATOR = (value) -> {
+        if (TextUtils.isEmpty(value)) {
+            return false;
+        }
+        try {
+            new JSONObject(value);
+            return true;
+        } catch (JSONException e) {
+            return false;
+        }
+    };
+
     public interface Validator {
         /**
          * Returns whether the input value is valid. Subclasses should handle the case where the
diff --git a/telecomm/java/android/telecom/CallIdentification.aidl b/core/java/android/view/IInputMonitorHost.aidl
similarity index 75%
rename from telecomm/java/android/telecom/CallIdentification.aidl
rename to core/java/android/view/IInputMonitorHost.aidl
index 532535c..bde737d 100644
--- a/telecomm/java/android/telecom/CallIdentification.aidl
+++ b/core/java/android/view/IInputMonitorHost.aidl
@@ -1,5 +1,5 @@
-/*
- * Copyright 2018, The Android Open Source Project
+/**
+ * Copyright (c) 2019, The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,9 +14,12 @@
  * limitations under the License.
  */
 
-package android.telecom;
+package android.view;
 
 /**
- * {@hide}
+ * @hide
  */
-parcelable CallIdentification;
+oneway interface IInputMonitorHost {
+    void pilferPointers();
+    void dispose();
+}
diff --git a/core/java/android/view/InputChannel.java b/core/java/android/view/InputChannel.java
index af2b992..ecb727c 100644
--- a/core/java/android/view/InputChannel.java
+++ b/core/java/android/view/InputChannel.java
@@ -17,8 +17,8 @@
 package android.view;
 
 import android.annotation.UnsupportedAppUsage;
-import android.os.Parcel;
 import android.os.IBinder;
+import android.os.Parcel;
 import android.os.Parcelable;
 import android.util.Slog;
 
@@ -31,9 +31,9 @@
  */
 public final class InputChannel implements Parcelable {
     private static final String TAG = "InputChannel";
-    
+
     private static final boolean DEBUG = false;
-    
+
     @UnsupportedAppUsage
     public static final @android.annotation.NonNull Parcelable.Creator<InputChannel> CREATOR
             = new Parcelable.Creator<InputChannel>() {
@@ -42,12 +42,12 @@
             result.readFromParcel(source);
             return result;
         }
-        
+
         public InputChannel[] newArray(int size) {
             return new InputChannel[size];
         }
     };
-    
+
     @SuppressWarnings("unused")
     @UnsupportedAppUsage
     private long mPtr; // used by native code
@@ -81,7 +81,7 @@
             super.finalize();
         }
     }
-    
+
     /**
      * Creates a new input channel pair.  One channel should be provided to the input
      * dispatcher and the other to the application's input queue.
@@ -100,7 +100,7 @@
         }
         return nativeOpenInputChannelPair(name);
     }
-    
+
     /**
      * Gets the name of the input channel.
      * @return The input channel name.
@@ -118,7 +118,7 @@
     public void dispose() {
         nativeDispose(false);
     }
-    
+
     /**
      * Transfers ownership of the internal state of the input channel to another
      * instance and invalidates this instance.  This is used to pass an input channel
@@ -129,7 +129,7 @@
         if (outParameter == null) {
             throw new IllegalArgumentException("outParameter must not be null");
         }
-        
+
         nativeTransferTo(outParameter);
     }
 
@@ -151,7 +151,7 @@
         if (in == null) {
             throw new IllegalArgumentException("in must not be null");
         }
-        
+
         nativeReadFromParcel(in);
     }
 
@@ -160,7 +160,7 @@
         if (out == null) {
             throw new IllegalArgumentException("out must not be null");
         }
-        
+
         nativeWriteToParcel(out);
 
         if ((flags & PARCELABLE_WRITE_RETURN_VALUE) != 0) {
diff --git a/telecomm/java/android/telecom/CallIdentification.aidl b/core/java/android/view/InputMonitor.aidl
similarity index 73%
copy from telecomm/java/android/telecom/CallIdentification.aidl
copy to core/java/android/view/InputMonitor.aidl
index 532535c..bdd14fe 100644
--- a/telecomm/java/android/telecom/CallIdentification.aidl
+++ b/core/java/android/view/InputMonitor.aidl
@@ -1,11 +1,11 @@
 /*
- * Copyright 2018, The Android Open Source Project
+ * Copyright (C) 2019 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
@@ -14,9 +14,6 @@
  * limitations under the License.
  */
 
-package android.telecom;
+package android.view;
 
-/**
- * {@hide}
- */
-parcelable CallIdentification;
+parcelable InputMonitor;
diff --git a/core/java/android/view/InputMonitor.java b/core/java/android/view/InputMonitor.java
new file mode 100644
index 0000000..693f287
--- /dev/null
+++ b/core/java/android/view/InputMonitor.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.view;
+
+import android.annotation.NonNull;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.os.RemoteException;
+
+/**
+ * @hide
+ */
+public final class InputMonitor implements Parcelable {
+    private static final String TAG = "InputMonitor";
+
+    private static final boolean DEBUG = false;
+
+    public static final Parcelable.Creator<InputMonitor> CREATOR =
+            new Parcelable.Creator<InputMonitor>() {
+
+            public InputMonitor createFromParcel(Parcel source) {
+                return new InputMonitor(source);
+            }
+
+            public InputMonitor[] newArray(int size) {
+                return new InputMonitor[size];
+            }
+    };
+
+    @NonNull
+    private final String mName;
+    @NonNull
+    private final InputChannel mChannel;
+    @NonNull
+    private final IInputMonitorHost mHost;
+
+    public InputMonitor(@NonNull String name, @NonNull InputChannel channel,
+            @NonNull IInputMonitorHost host) {
+        mName = name;
+        mChannel = channel;
+        mHost = host;
+    }
+
+    public InputMonitor(Parcel in) {
+        mName = in.readString();
+        mChannel = in.readParcelable(null);
+        mHost = IInputMonitorHost.Stub.asInterface(in.readStrongBinder());
+    }
+
+    /**
+     * Get the {@link InputChannel} corresponding to this InputMonitor
+     */
+    public InputChannel getInputChannel() {
+        return mChannel;
+    }
+
+    /**
+     * Get the name of this channel.
+     */
+    public String getName() {
+        return mName;
+    }
+
+
+    /**
+     * Takes all of the current pointer events streams that are currently being sent to this
+     * monitor and generates appropriate cancellations for the windows that would normally get
+     * them.
+     *
+     * This method should be used with caution as unexpected pilfering can break fundamental user
+     * interactions.
+     */
+    public void pilferPointers() {
+        try {
+            mHost.pilferPointers();
+        } catch (RemoteException e) {
+            e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Disposes the input monitor.
+     *
+     * Explicitly release all of the resources this monitor is holding on to (e.g. the
+     * InputChannel). Once this method is called, this monitor and any resources it's provided may
+     * no longer be used.
+     */
+    public void dispose() {
+        mChannel.dispose();
+        try {
+            mHost.dispose();
+        } catch (RemoteException e) {
+            e.rethrowFromSystemServer();
+        }
+    }
+
+    @Override
+    public void writeToParcel(Parcel out, int flags) {
+        out.writeString(mName);
+        out.writeParcelable(mChannel, flags);
+        out.writeStrongBinder(mHost.asBinder());
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public String toString() {
+        return "InputMonitor{mName=" + mName + ", mChannel=" + mChannel + ", mHost=" + mHost + "}";
+    }
+}
diff --git a/core/java/android/view/textclassifier/intent/ClassificationIntentFactory.java b/core/java/android/view/textclassifier/intent/ClassificationIntentFactory.java
index b034846..22e374f2 100644
--- a/core/java/android/view/textclassifier/intent/ClassificationIntentFactory.java
+++ b/core/java/android/view/textclassifier/intent/ClassificationIntentFactory.java
@@ -48,6 +48,7 @@
                 context.getString(com.android.internal.R.string.translate),
                 /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.translate_desc),
+                /* descriptionWithAppName */ null,
                 new Intent(Intent.ACTION_TRANSLATE)
                         // TODO: Probably better to introduce a "translate" scheme instead of
                         // using EXTRA_TEXT.
diff --git a/core/java/android/view/textclassifier/intent/LabeledIntent.java b/core/java/android/view/textclassifier/intent/LabeledIntent.java
index 11d64f1..b4bc8d3 100644
--- a/core/java/android/view/textclassifier/intent/LabeledIntent.java
+++ b/core/java/android/view/textclassifier/intent/LabeledIntent.java
@@ -56,6 +56,8 @@
     @Nullable
     public final String titleWithEntity;
     public final String description;
+    @Nullable
+    public final String descriptionWithAppName;
     // Do not update this intent.
     public final Intent intent;
     public final int requestCode;
@@ -75,6 +77,7 @@
             @Nullable String titleWithoutEntity,
             @Nullable String titleWithEntity,
             String description,
+            @Nullable String descriptionWithAppName,
             Intent intent,
             int requestCode) {
         if (TextUtils.isEmpty(titleWithEntity) && TextUtils.isEmpty(titleWithoutEntity)) {
@@ -84,6 +87,7 @@
         this.titleWithoutEntity = titleWithoutEntity;
         this.titleWithEntity = titleWithEntity;
         this.description = Preconditions.checkNotNull(description);
+        this.descriptionWithAppName = descriptionWithAppName;
         this.intent = Preconditions.checkNotNull(intent);
         this.requestCode = requestCode;
     }
@@ -141,11 +145,39 @@
             Log.w(TAG, "Custom titleChooser return null, fallback to the default titleChooser");
             title = DEFAULT_TITLE_CHOOSER.chooseTitle(this, resolveInfo);
         }
-        final RemoteAction action = new RemoteAction(icon, title, description, pendingIntent);
+        final RemoteAction action =
+                new RemoteAction(icon, title, resolveDescription(resolveInfo, pm), pendingIntent);
         action.setShouldShowIcon(shouldShowIcon);
         return new Result(resolvedIntent, action);
     }
 
+    private String resolveDescription(ResolveInfo resolveInfo, PackageManager packageManager) {
+        if (!TextUtils.isEmpty(descriptionWithAppName)) {
+            // Example string format of descriptionWithAppName: "Use %1$s to open map".
+            String applicationName = getApplicationName(resolveInfo, packageManager);
+            if (!TextUtils.isEmpty(applicationName)) {
+                return String.format(descriptionWithAppName, applicationName);
+            }
+        }
+        return description;
+    }
+
+    @Nullable
+    private String getApplicationName(
+            ResolveInfo resolveInfo, PackageManager packageManager) {
+        if (resolveInfo.activityInfo == null) {
+            return null;
+        }
+        if ("android".equals(resolveInfo.activityInfo.packageName)) {
+            return null;
+        }
+        if (resolveInfo.activityInfo.applicationInfo == null) {
+            return null;
+        }
+        return (String) packageManager.getApplicationLabel(
+                resolveInfo.activityInfo.applicationInfo);
+    }
+
     private Bundle getFromTextClassifierExtra(@Nullable Bundle textLanguagesBundle) {
         if (textLanguagesBundle != null) {
             final Bundle bundle = new Bundle();
diff --git a/core/java/android/view/textclassifier/intent/LegacyClassificationIntentFactory.java b/core/java/android/view/textclassifier/intent/LegacyClassificationIntentFactory.java
index 7916791..8d60ad8 100644
--- a/core/java/android/view/textclassifier/intent/LegacyClassificationIntentFactory.java
+++ b/core/java/android/view/textclassifier/intent/LegacyClassificationIntentFactory.java
@@ -46,6 +46,7 @@
  * Creates intents based on the classification type.
  * @hide
  */
+// TODO: Consider to support {@code descriptionWithAppName}.
 public final class LegacyClassificationIntentFactory implements ClassificationIntentFactory {
 
     private static final String TAG = "LegacyClassificationIntentFactory";
@@ -108,6 +109,7 @@
                 context.getString(com.android.internal.R.string.email),
                 /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.email_desc),
+                /* descriptionWithAppName */ null,
                 new Intent(Intent.ACTION_SENDTO)
                         .setData(Uri.parse(String.format("mailto:%s", text))),
                 LabeledIntent.DEFAULT_REQUEST_CODE));
@@ -115,6 +117,7 @@
                 context.getString(com.android.internal.R.string.add_contact),
                 /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.add_contact_desc),
+                /* descriptionWithAppName */ null,
                 new Intent(Intent.ACTION_INSERT_OR_EDIT)
                         .setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE)
                         .putExtra(ContactsContract.Intents.Insert.EMAIL, text),
@@ -133,6 +136,7 @@
                     context.getString(com.android.internal.R.string.dial),
                     /* titleWithEntity */ null,
                     context.getString(com.android.internal.R.string.dial_desc),
+                    /* descriptionWithAppName */ null,
                     new Intent(Intent.ACTION_DIAL).setData(
                             Uri.parse(String.format("tel:%s", text))),
                     LabeledIntent.DEFAULT_REQUEST_CODE));
@@ -141,6 +145,7 @@
                 context.getString(com.android.internal.R.string.add_contact),
                 /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.add_contact_desc),
+                /* descriptionWithAppName */ null,
                 new Intent(Intent.ACTION_INSERT_OR_EDIT)
                         .setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE)
                         .putExtra(ContactsContract.Intents.Insert.PHONE, text),
@@ -150,6 +155,7 @@
                     context.getString(com.android.internal.R.string.sms),
                     /* titleWithEntity */ null,
                     context.getString(com.android.internal.R.string.sms_desc),
+                    /* descriptionWithAppName */ null,
                     new Intent(Intent.ACTION_SENDTO)
                             .setData(Uri.parse(String.format("smsto:%s", text))),
                     LabeledIntent.DEFAULT_REQUEST_CODE));
@@ -166,6 +172,7 @@
                     context.getString(com.android.internal.R.string.map),
                     /* titleWithEntity */ null,
                     context.getString(com.android.internal.R.string.map_desc),
+                    /* descriptionWithAppName */ null,
                     new Intent(Intent.ACTION_VIEW)
                             .setData(Uri.parse(String.format("geo:0,0?q=%s", encText))),
                     LabeledIntent.DEFAULT_REQUEST_CODE));
@@ -185,6 +192,7 @@
                 context.getString(com.android.internal.R.string.browse),
                 /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.browse_desc),
+                /* descriptionWithAppName */ null,
                 new Intent(Intent.ACTION_VIEW)
                         .setDataAndNormalize(Uri.parse(text))
                         .putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName()),
@@ -216,6 +224,7 @@
                 context.getString(com.android.internal.R.string.view_flight),
                 /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.view_flight_desc),
+                /* descriptionWithAppName */ null,
                 new Intent(Intent.ACTION_WEB_SEARCH)
                         .putExtra(SearchManager.QUERY, text),
                 text.hashCode()));
@@ -231,6 +240,7 @@
                 context.getString(com.android.internal.R.string.view_calendar),
                 /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.view_calendar_desc),
+                /* descriptionWithAppName */ null,
                 new Intent(Intent.ACTION_VIEW).setData(builder.build()),
                 LabeledIntent.DEFAULT_REQUEST_CODE);
     }
@@ -243,6 +253,7 @@
                 context.getString(com.android.internal.R.string.add_calendar_event),
                 /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.add_calendar_event_desc),
+                /* descriptionWithAppName */ null,
                 new Intent(Intent.ACTION_INSERT)
                         .setData(CalendarContract.Events.CONTENT_URI)
                         .putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, isAllDay)
@@ -260,6 +271,7 @@
                 context.getString(com.android.internal.R.string.define),
                 /* titleWithEntity */ null,
                 context.getString(com.android.internal.R.string.define_desc),
+                /* descriptionWithAppName */ null,
                 new Intent(Intent.ACTION_DEFINE)
                         .putExtra(Intent.EXTRA_TEXT, text),
                 text.hashCode()));
diff --git a/core/java/android/view/textclassifier/intent/TemplateIntentFactory.java b/core/java/android/view/textclassifier/intent/TemplateIntentFactory.java
index 59cd7ab..7a39569 100644
--- a/core/java/android/view/textclassifier/intent/TemplateIntentFactory.java
+++ b/core/java/android/view/textclassifier/intent/TemplateIntentFactory.java
@@ -61,6 +61,7 @@
                             remoteActionTemplate.titleWithoutEntity,
                             remoteActionTemplate.titleWithEntity,
                             remoteActionTemplate.description,
+                            remoteActionTemplate.descriptionWithAppName,
                             createIntent(remoteActionTemplate),
                             remoteActionTemplate.requestCode == null
                                     ? LabeledIntent.DEFAULT_REQUEST_CODE
diff --git a/core/java/com/android/internal/os/KernelCpuThreadReader.java b/core/java/com/android/internal/os/KernelCpuThreadReader.java
index 3686048..d92f725b 100644
--- a/core/java/com/android/internal/os/KernelCpuThreadReader.java
+++ b/core/java/com/android/internal/os/KernelCpuThreadReader.java
@@ -21,6 +21,7 @@
 import android.util.Slog;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.Preconditions;
 
 import java.io.IOException;
@@ -29,6 +30,7 @@
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.function.Predicate;
 
 /**
@@ -233,7 +235,7 @@
         mFrequencyBucketCreator =
                 new FrequencyBucketCreator(mProcTimeInStateReader.getFrequenciesKhz(), numBuckets);
         mFrequenciesKhz =
-                mFrequencyBucketCreator.getBucketMinFrequencies(
+                mFrequencyBucketCreator.bucketFrequencies(
                         mProcTimeInStateReader.getFrequenciesKhz());
     }
 
@@ -317,7 +319,7 @@
         if (cpuUsagesLong == null) {
             return null;
         }
-        int[] cpuUsages = mFrequencyBucketCreator.getBucketedValues(cpuUsagesLong);
+        int[] cpuUsages = mFrequencyBucketCreator.bucketValues(cpuUsagesLong);
 
         return new ThreadCpuUsage(threadId, threadName, cpuUsages);
     }
@@ -359,89 +361,46 @@
         }
     }
 
-    /** Puts frequencies and usage times into buckets */
+    /**
+     * Quantizes a list of N frequencies into a list of M frequencies (where M<=N)
+     *
+     * <p>In order to reduce data sent from the device, we discard precise frequency information for
+     * an approximation. This is done by putting groups of adjacent frequencies into the same
+     * bucket, and then reporting that bucket under the minimum frequency in that bucket.
+     *
+     * <p>Many devices have multiple core clusters. We do not want to report frequencies from
+     * different clusters under the same bucket, so some complication arises.
+     *
+     * <p>Buckets are allocated evenly across all core clusters, i.e. they all have the same number
+     * of buckets regardless of how many frequencies they contain. This is done to reduce code
+     * complexity, and in practice the number of frequencies doesn't vary too much between core
+     * clusters.
+     *
+     * <p>If the number of buckets is not a factor of the number of frequencies, the remainder of
+     * the frequencies are placed into the last bucket.
+     *
+     * <p>It is possible to have less buckets than asked for, so any calling code can't assume that
+     * initializing with N buckets will use return N values. This happens in two scenarios:
+     *
+     * <ul>
+     *   <li>There are less frequencies available than buckets asked for.
+     *   <li>There are less frequencies in a core cluster than buckets allocated to that core
+     *       cluster.
+     * </ul>
+     */
     @VisibleForTesting
     public static class FrequencyBucketCreator {
-        private final int mNumBuckets;
         private final int mNumFrequencies;
-        private final int mBigFrequenciesStartIndex;
-        private final int mLittleNumBuckets;
-        private final int mBigNumBuckets;
-        private final int mLittleBucketSize;
-        private final int mBigBucketSize;
+        private final int mNumBuckets;
+        private final int[] mBucketStartIndices;
 
-        /**
-         * Buckets based of a list of frequencies
-         *
-         * @param frequencies the frequencies to base buckets off
-         * @param numBuckets how many buckets to create
-         */
         @VisibleForTesting
-        public FrequencyBucketCreator(long[] frequencies, int numBuckets) {
-            Preconditions.checkArgument(numBuckets > 0);
-
+        public FrequencyBucketCreator(long[] frequencies, int targetNumBuckets) {
             mNumFrequencies = frequencies.length;
-            mBigFrequenciesStartIndex = getBigFrequenciesStartIndex(frequencies);
-
-            final int littleNumBuckets;
-            final int bigNumBuckets;
-            if (mBigFrequenciesStartIndex < frequencies.length) {
-                littleNumBuckets = numBuckets / 2;
-                bigNumBuckets = numBuckets - littleNumBuckets;
-            } else {
-                // If we've got no big frequencies, set all buckets to little frequencies
-                littleNumBuckets = numBuckets;
-                bigNumBuckets = 0;
-            }
-
-            // Ensure that we don't have more buckets than frequencies
-            mLittleNumBuckets = Math.min(littleNumBuckets, mBigFrequenciesStartIndex);
-            mBigNumBuckets =
-                    Math.min(bigNumBuckets, frequencies.length - mBigFrequenciesStartIndex);
-            mNumBuckets = mLittleNumBuckets + mBigNumBuckets;
-
-            // Set the size of each little and big bucket. If they have no buckets, the size is zero
-            mLittleBucketSize =
-                    mLittleNumBuckets == 0 ? 0 : mBigFrequenciesStartIndex / mLittleNumBuckets;
-            mBigBucketSize =
-                    mBigNumBuckets == 0
-                            ? 0
-                            : (frequencies.length - mBigFrequenciesStartIndex) / mBigNumBuckets;
-        }
-
-        /** Find the index where frequencies change from little core to big core */
-        @VisibleForTesting
-        public static int getBigFrequenciesStartIndex(long[] frequenciesKhz) {
-            for (int i = 0; i < frequenciesKhz.length - 1; i++) {
-                if (frequenciesKhz[i] > frequenciesKhz[i + 1]) {
-                    return i + 1;
-                }
-            }
-
-            return frequenciesKhz.length;
-        }
-
-        /** Get the minimum frequency in each bucket */
-        @VisibleForTesting
-        public int[] getBucketMinFrequencies(long[] frequenciesKhz) {
-            Preconditions.checkArgument(frequenciesKhz.length == mNumFrequencies);
-            // If there's only one bucket, we bucket everything together so the first bucket is the
-            // min frequency
-            if (mNumBuckets == 1) {
-                return new int[] {(int) frequenciesKhz[0]};
-            }
-
-            final int[] bucketMinFrequencies = new int[mNumBuckets];
-            // Initialize little buckets min frequencies
-            for (int i = 0; i < mLittleNumBuckets; i++) {
-                bucketMinFrequencies[i] = (int) frequenciesKhz[i * mLittleBucketSize];
-            }
-            // Initialize big buckets min frequencies
-            for (int i = 0; i < mBigNumBuckets; i++) {
-                final int frequencyIndex = mBigFrequenciesStartIndex + i * mBigBucketSize;
-                bucketMinFrequencies[mLittleNumBuckets + i] = (int) frequenciesKhz[frequencyIndex];
-            }
-            return bucketMinFrequencies;
+            int[] clusterStartIndices = getClusterStartIndices(frequencies);
+            mBucketStartIndices =
+                    getBucketStartIndices(clusterStartIndices, targetNumBuckets, mNumFrequencies);
+            mNumBuckets = mBucketStartIndices.length;
         }
 
         /**
@@ -453,34 +412,105 @@
          * @return the bucketed usage times
          */
         @VisibleForTesting
-        @SuppressWarnings("ForLoopReplaceableByForEach")
-        public int[] getBucketedValues(long[] values) {
+        public int[] bucketValues(long[] values) {
             Preconditions.checkArgument(values.length == mNumFrequencies);
-            final int[] bucketed = new int[mNumBuckets];
-
-            // If there's only one bucket, add all frequencies in
-            if (mNumBuckets == 1) {
-                for (int i = 0; i < values.length; i++) {
-                    bucketed[0] += values[i];
+            int[] buckets = new int[mNumBuckets];
+            for (int bucketIdx = 0; bucketIdx < mNumBuckets; bucketIdx++) {
+                final int bucketStartIdx = getLowerBound(bucketIdx, mBucketStartIndices);
+                final int bucketEndIdx =
+                        getUpperBound(bucketIdx, mBucketStartIndices, values.length);
+                for (int valuesIdx = bucketStartIdx; valuesIdx < bucketEndIdx; valuesIdx++) {
+                    buckets[bucketIdx] += values[valuesIdx];
                 }
-                return bucketed;
+            }
+            return buckets;
+        }
+
+        /** Get the minimum frequency in each bucket */
+        @VisibleForTesting
+        public int[] bucketFrequencies(long[] frequencies) {
+            Preconditions.checkArgument(frequencies.length == mNumFrequencies);
+            int[] buckets = new int[mNumBuckets];
+            for (int i = 0; i < buckets.length; i++) {
+                buckets[i] = (int) frequencies[mBucketStartIndices[i]];
+            }
+            return buckets;
+        }
+
+        /**
+         * Get the index in frequencies where each core cluster starts
+         *
+         * <p>The frequencies for each cluster are given in ascending order, appended to each other.
+         * This means that every time there is a decrease in frequencies (instead of increase) a new
+         * cluster has started.
+         */
+        private static int[] getClusterStartIndices(long[] frequencies) {
+            ArrayList<Integer> indices = new ArrayList<>();
+            indices.add(0);
+            for (int i = 0; i < frequencies.length - 1; i++) {
+                if (frequencies[i] >= frequencies[i + 1]) {
+                    indices.add(i + 1);
+                }
+            }
+            return ArrayUtils.convertToIntArray(indices);
+        }
+
+        /** Get the index in frequencies where each bucket starts */
+        private static int[] getBucketStartIndices(
+                int[] clusterStartIndices, int targetNumBuckets, int numFrequencies) {
+            int numClusters = clusterStartIndices.length;
+
+            // If we haven't got enough buckets for every cluster, we instead have one bucket per
+            // cluster, with the last bucket containing the remaining clusters
+            if (numClusters > targetNumBuckets) {
+                return Arrays.copyOfRange(clusterStartIndices, 0, targetNumBuckets);
             }
 
-            // Initialize the little buckets
-            for (int i = 0; i < mBigFrequenciesStartIndex; i++) {
-                final int bucketIndex = Math.min(i / mLittleBucketSize, mLittleNumBuckets - 1);
-                bucketed[bucketIndex] += values[i];
+            ArrayList<Integer> bucketStartIndices = new ArrayList<>();
+            for (int clusterIdx = 0; clusterIdx < numClusters; clusterIdx++) {
+                final int clusterStartIdx = getLowerBound(clusterIdx, clusterStartIndices);
+                final int clusterEndIdx =
+                        getUpperBound(clusterIdx, clusterStartIndices, numFrequencies);
+
+                final int numBucketsInCluster;
+                if (clusterIdx != numClusters - 1) {
+                    numBucketsInCluster = targetNumBuckets / numClusters;
+                } else {
+                    // If we're in the last cluster, the bucket will contain the remainder of the
+                    // frequencies
+                    int previousBucketsInCluster = targetNumBuckets / numClusters;
+                    numBucketsInCluster =
+                            targetNumBuckets - (previousBucketsInCluster * (numClusters - 1));
+                }
+
+                final int numFrequenciesInCluster = clusterEndIdx - clusterStartIdx;
+                // If there are less frequencies than buckets in a cluster, we have one bucket per
+                // frequency, and do not use the remaining buckets
+                final int numFrequenciesInBucket =
+                        Math.max(1, numFrequenciesInCluster / numBucketsInCluster);
+                for (int bucketIdx = 0; bucketIdx < numBucketsInCluster; bucketIdx++) {
+                    int bucketStartIdx = clusterStartIdx + bucketIdx * numFrequenciesInBucket;
+                    // If we've gone over the end index, ignore the rest of the buckets for this
+                    // cluster
+                    if (bucketStartIdx >= clusterEndIdx) {
+                        break;
+                    }
+                    bucketStartIndices.add(bucketStartIdx);
+                }
             }
-            // Initialize the big buckets
-            for (int i = mBigFrequenciesStartIndex; i < values.length; i++) {
-                final int bucketIndex =
-                        Math.min(
-                                mLittleNumBuckets
-                                        + (i - mBigFrequenciesStartIndex) / mBigBucketSize,
-                                mNumBuckets - 1);
-                bucketed[bucketIndex] += values[i];
+            return ArrayUtils.convertToIntArray(bucketStartIndices);
+        }
+
+        private static int getLowerBound(int index, int[] startIndices) {
+            return startIndices[index];
+        }
+
+        private static int getUpperBound(int index, int[] startIndices, int max) {
+            if (index != startIndices.length - 1) {
+                return startIndices[index + 1];
+            } else {
+                return max;
             }
-            return bucketed;
         }
     }
 
diff --git a/core/java/com/android/internal/policy/DecorView.java b/core/java/com/android/internal/policy/DecorView.java
index ca5db94..625814d 100644
--- a/core/java/com/android/internal/policy/DecorView.java
+++ b/core/java/com/android/internal/policy/DecorView.java
@@ -1143,7 +1143,6 @@
         // If we didn't request fullscreen layout, but we still got it because of the
         // mForceWindowDrawsStatusBarBackground flag, also consume top inset.
         boolean consumingStatusBar = (sysUiVisibility & SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) == 0
-                && (sysUiVisibility & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0
                 && (attrs.flags & FLAG_LAYOUT_IN_SCREEN) == 0
                 && (attrs.flags & FLAG_LAYOUT_INSET_DECOR) == 0
                 && mForceWindowDrawsStatusBarBackground
diff --git a/core/jni/android_database_CursorWindow.cpp b/core/jni/android_database_CursorWindow.cpp
index 86cda44..5e4d6e3 100644
--- a/core/jni/android_database_CursorWindow.cpp
+++ b/core/jni/android_database_CursorWindow.cpp
@@ -92,7 +92,9 @@
     CursorWindow* window;
     status_t status = CursorWindow::create(name, cursorWindowSize, &window);
     if (status || !window) {
-        ALOGE("Could not allocate CursorWindow '%s' of size %d due to error %d.",
+        jniThrowExceptionFmt(env,
+                "android/database/CursorWindowAllocationException",
+                "Could not allocate CursorWindow '%s' of size %d due to error %d.",
                 name.string(), cursorWindowSize, status);
         return 0;
     }
@@ -107,7 +109,9 @@
     CursorWindow* window;
     status_t status = CursorWindow::createFromParcel(parcel, &window);
     if (status || !window) {
-        ALOGE("Could not create CursorWindow from Parcel due to error %d, process fd count=%d",
+        jniThrowExceptionFmt(env,
+                "android/database/CursorWindowAllocationException",
+                "Could not create CursorWindow from Parcel due to error %d, process fd count=%d",
                 status, getFdCount());
         return 0;
     }
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 3788f47..fb92fbf 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -4506,6 +4506,10 @@
     <permission android:name="android.permission.ACCESS_SHARED_LIBRARIES"
                 android:protectionLevel="signature|installer" />
 
+    <!-- Allows input events to be monitored. Very dangerous!  @hide -->
+    <permission android:name="android.permission.MONITOR_INPUT"
+                android:protectionLevel="signature" />
+
     <application android:process="system"
                  android:persistent="true"
                  android:hasCode="false"
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index b92033e..4b8a96c 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -1567,7 +1567,7 @@
     <string name="face_error_lockout_permanent">Too many attempts. Face authentication disabled.</string>
     <!-- Generic error message shown when the face hardware can't recognize the face. [CHAR LIMIT=50] -->
     <string name="face_error_unable_to_process">Can\u2019t verify face. Try again.</string>
-    <!-- Generic error message shown when the user has no enrolled face. [CHAR LIMIT=50] -->
+    <!-- Generic error message shown when the user has no enrolled face. [CHAR LIMIT=52] -->
     <string name="face_error_not_enrolled">You haven\u2019t set up face authentication</string>
     <!-- Generic error message shown when the app requests face authentication on a device without a sensor. [CHAR LIMIT=60] -->
     <string name="face_error_hw_not_present">Face authentication is not supported on this device</string>
diff --git a/core/tests/coretests/src/android/provider/SettingsValidatorsTest.java b/core/tests/coretests/src/android/provider/SettingsValidatorsTest.java
index 08f9de6..8081e9e 100644
--- a/core/tests/coretests/src/android/provider/SettingsValidatorsTest.java
+++ b/core/tests/coretests/src/android/provider/SettingsValidatorsTest.java
@@ -16,6 +16,8 @@
 
 package android.provider;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -26,6 +28,8 @@
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
 
+import org.json.JSONException;
+import org.json.JSONObject;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -218,6 +222,31 @@
     }
 
     @Test
+    public void testJSONObjectValidator() throws JSONException {
+        Validator v = SettingsValidators.JSON_OBJECT_VALIDATOR;
+
+        assertThat(v.validate(new JSONObject().toString())).isTrue();
+        assertThat(v.validate("{}")).isTrue();
+        assertThat(v.validate(new JSONObject().put("foo", "bar").toString()))
+                .isTrue();
+        assertThat(v.validate("{\"foo\": \"bar\"}")).isTrue();
+
+        assertThat(v.validate("random string")).isFalse();
+        assertThat(v.validate("random: string")).isFalse();
+        assertThat(v.validate("{random: }")).isFalse();
+    }
+
+    @Test
+    public void testJSONObjectValidator_onNullValue_returnsFalse() {
+        assertThat(SettingsValidators.JSON_OBJECT_VALIDATOR.validate(null)).isFalse();
+    }
+
+    @Test
+    public void testJSONObjectValidator_onEmptyString_returnsFalse() {
+        assertThat(SettingsValidators.JSON_OBJECT_VALIDATOR.validate("")).isFalse();
+    }
+
+    @Test
     public void ensureAllBackedUpSystemSettingsHaveValidators() {
         String offenders = getOffenders(concat(Settings.System.SETTINGS_TO_BACKUP,
                 Settings.System.LEGACY_RESTORE_SETTINGS), Settings.System.VALIDATORS);
diff --git a/core/tests/coretests/src/android/view/textclassifier/ActionsSuggestionsHelperTest.java b/core/tests/coretests/src/android/view/textclassifier/ActionsSuggestionsHelperTest.java
index 67423c8..db5f82a 100644
--- a/core/tests/coretests/src/android/view/textclassifier/ActionsSuggestionsHelperTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/ActionsSuggestionsHelperTest.java
@@ -263,6 +263,7 @@
                                         "title",
                                         null,
                                         "description",
+                                        null,
                                         Intent.ACTION_VIEW,
                                         Uri.parse("http://www.android.com").toString(),
                                         null,
diff --git a/core/tests/coretests/src/android/view/textclassifier/FakeContextBuilder.java b/core/tests/coretests/src/android/view/textclassifier/FakeContextBuilder.java
index 2674e37..11bea0c 100644
--- a/core/tests/coretests/src/android/view/textclassifier/FakeContextBuilder.java
+++ b/core/tests/coretests/src/android/view/textclassifier/FakeContextBuilder.java
@@ -54,6 +54,7 @@
     private final PackageManager mPackageManager;
     private final ContextWrapper mContext;
     private final Map<String, ComponentName> mComponents = new HashMap<>();
+    private final Map<String, CharSequence> mAppLabels = new HashMap<>();
     private @Nullable ComponentName mAllIntentComponent;
 
     public FakeContextBuilder() {
@@ -79,6 +80,14 @@
         return this;
     }
 
+    /**
+     * Sets the app label res for a specified package.
+     */
+    public FakeContextBuilder setAppLabel(String packageName, @Nullable CharSequence appLabel) {
+        Preconditions.checkNotNull(packageName);
+        mAppLabels.put(packageName, appLabel);
+        return this;
+    }
 
     /**
      * Sets the component name of an activity to handle all intents.
@@ -102,6 +111,11 @@
                             : mAllIntentComponent;
                     return getResolveInfo(component);
                 });
+        when(mPackageManager.getApplicationLabel(any(ApplicationInfo.class))).thenAnswer(
+                (Answer<CharSequence>) invocation -> {
+                    ApplicationInfo applicationInfo = invocation.getArgument(0);
+                    return mAppLabels.get(applicationInfo.packageName);
+                });
         return mContext;
     }
 
@@ -125,6 +139,7 @@
             info.activityInfo.name = component.getClassName();
             info.activityInfo.exported = true;
             info.activityInfo.applicationInfo = new ApplicationInfo();
+            info.activityInfo.applicationInfo.packageName = component.getPackageName();
             info.activityInfo.applicationInfo.icon = 0;
         }
         return info;
diff --git a/core/tests/coretests/src/android/view/textclassifier/intent/LabeledIntentTest.java b/core/tests/coretests/src/android/view/textclassifier/intent/LabeledIntentTest.java
index 857408f..3ad26f5 100644
--- a/core/tests/coretests/src/android/view/textclassifier/intent/LabeledIntentTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/intent/LabeledIntentTest.java
@@ -20,6 +20,7 @@
 
 import static org.testng.Assert.assertThrows;
 
+import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
 import android.net.Uri;
@@ -40,17 +41,21 @@
     private static final String TITLE_WITHOUT_ENTITY = "Map";
     private static final String TITLE_WITH_ENTITY = "Map NW14D1";
     private static final String DESCRIPTION = "Check the map";
+    private static final String DESCRIPTION_WITH_APP_NAME = "Use %1$s to open map";
     private static final Intent INTENT =
             new Intent(Intent.ACTION_VIEW).setDataAndNormalize(Uri.parse("http://www.android.com"));
     private static final int REQUEST_CODE = 42;
     private static final Bundle TEXT_LANGUAGES_BUNDLE = Bundle.EMPTY;
+    private static final String APP_LABEL = "fake";
 
     private Context mContext;
 
     @Before
     public void setup() {
+        final ComponentName component = FakeContextBuilder.DEFAULT_COMPONENT;
         mContext = new FakeContextBuilder()
-                .setIntentComponent(Intent.ACTION_VIEW, FakeContextBuilder.DEFAULT_COMPONENT)
+                .setIntentComponent(Intent.ACTION_VIEW, component)
+                .setAppLabel(component.getPackageName(), APP_LABEL)
                 .build();
     }
 
@@ -60,6 +65,7 @@
                 TITLE_WITHOUT_ENTITY,
                 TITLE_WITH_ENTITY,
                 DESCRIPTION,
+                null,
                 INTENT,
                 REQUEST_CODE
         );
@@ -82,6 +88,7 @@
                 TITLE_WITHOUT_ENTITY,
                 null,
                 DESCRIPTION,
+                null,
                 INTENT,
                 REQUEST_CODE
         );
@@ -103,6 +110,7 @@
                 TITLE_WITHOUT_ENTITY,
                 null,
                 DESCRIPTION,
+                null,
                 INTENT,
                 REQUEST_CODE
         );
@@ -124,6 +132,7 @@
                 TITLE_WITHOUT_ENTITY,
                 null,
                 DESCRIPTION,
+                null,
                 INTENT,
                 REQUEST_CODE
         );
@@ -148,6 +157,7 @@
                                 null,
                                 null,
                                 DESCRIPTION,
+                                null,
                                 INTENT,
                                 REQUEST_CODE
                         ));
@@ -161,6 +171,7 @@
                 TITLE_WITHOUT_ENTITY,
                 null,
                 DESCRIPTION,
+                null,
                 unresolvableIntent,
                 REQUEST_CODE);
 
@@ -168,4 +179,22 @@
 
         assertThat(result).isNull();
     }
+
+    @Test
+    public void resolve_descriptionWithAppName() {
+        LabeledIntent labeledIntent = new LabeledIntent(
+                TITLE_WITHOUT_ENTITY,
+                TITLE_WITH_ENTITY,
+                DESCRIPTION,
+                DESCRIPTION_WITH_APP_NAME,
+                INTENT,
+                REQUEST_CODE
+        );
+
+        LabeledIntent.Result result = labeledIntent.resolve(
+                mContext, /*titleChooser*/ null, TEXT_LANGUAGES_BUNDLE);
+
+        assertThat(result).isNotNull();
+        assertThat(result.remoteAction.getContentDescription()).isEqualTo("Use fake to open map");
+    }
 }
diff --git a/core/tests/coretests/src/android/view/textclassifier/intent/TemplateClassificationIntentFactoryTest.java b/core/tests/coretests/src/android/view/textclassifier/intent/TemplateClassificationIntentFactoryTest.java
index 2e97e63..b9a1a8c 100644
--- a/core/tests/coretests/src/android/view/textclassifier/intent/TemplateClassificationIntentFactoryTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/intent/TemplateClassificationIntentFactoryTest.java
@@ -50,6 +50,7 @@
     private static final String TEXT = "text";
     private static final String TITLE_WITHOUT_ENTITY = "Map";
     private static final String DESCRIPTION = "Opens in Maps";
+    private static final String DESCRIPTION_WITH_APP_NAME = "Use %1$s to open Map";
     private static final String ACTION = Intent.ACTION_VIEW;
 
     @Mock
@@ -219,6 +220,7 @@
                         TITLE_WITHOUT_ENTITY,
                         null,
                         DESCRIPTION,
+                        DESCRIPTION_WITH_APP_NAME,
                         ACTION,
                         null,
                         null,
diff --git a/core/tests/coretests/src/android/view/textclassifier/intent/TemplateIntentFactoryTest.java b/core/tests/coretests/src/android/view/textclassifier/intent/TemplateIntentFactoryTest.java
index 6e3de2d..a33c358 100644
--- a/core/tests/coretests/src/android/view/textclassifier/intent/TemplateIntentFactoryTest.java
+++ b/core/tests/coretests/src/android/view/textclassifier/intent/TemplateIntentFactoryTest.java
@@ -41,6 +41,7 @@
     private static final String TITLE_WITHOUT_ENTITY = "Map";
     private static final String TITLE_WITH_ENTITY = "Map NW14D1";
     private static final String DESCRIPTION = "Check the map";
+    private static final String DESCRIPTION_WITH_APP_NAME = "Use %1$s to open map";
     private static final String ACTION = Intent.ACTION_VIEW;
     private static final String DATA = Uri.parse("http://www.android.com").toString();
     private static final String TYPE = "text/html";
@@ -73,6 +74,7 @@
                 TITLE_WITHOUT_ENTITY,
                 TITLE_WITH_ENTITY,
                 DESCRIPTION,
+                DESCRIPTION_WITH_APP_NAME,
                 ACTION,
                 DATA,
                 TYPE,
@@ -91,6 +93,7 @@
         assertThat(labeledIntent.titleWithoutEntity).isEqualTo(TITLE_WITHOUT_ENTITY);
         assertThat(labeledIntent.titleWithEntity).isEqualTo(TITLE_WITH_ENTITY);
         assertThat(labeledIntent.description).isEqualTo(DESCRIPTION);
+        assertThat(labeledIntent.descriptionWithAppName).isEqualTo(DESCRIPTION_WITH_APP_NAME);
         assertThat(labeledIntent.requestCode).isEqualTo(REQUEST_CODE);
         Intent intent = labeledIntent.intent;
         assertThat(intent.getAction()).isEqualTo(ACTION);
@@ -109,6 +112,7 @@
                 TITLE_WITHOUT_ENTITY,
                 TITLE_WITH_ENTITY,
                 DESCRIPTION,
+                DESCRIPTION_WITH_APP_NAME,
                 ACTION,
                 "HTTp://www.android.com",
                 TYPE,
@@ -132,6 +136,7 @@
                 TITLE_WITHOUT_ENTITY,
                 null,
                 DESCRIPTION,
+                null,
                 ACTION,
                 null,
                 null,
@@ -177,6 +182,7 @@
                 TITLE_WITHOUT_ENTITY,
                 TITLE_WITH_ENTITY,
                 DESCRIPTION,
+                DESCRIPTION_WITH_APP_NAME,
                 ACTION,
                 DATA,
                 TYPE,
@@ -199,6 +205,7 @@
                 null,
                 null,
                 DESCRIPTION,
+                DESCRIPTION_WITH_APP_NAME,
                 ACTION,
                 null,
                 null,
@@ -221,6 +228,7 @@
                 TITLE_WITHOUT_ENTITY,
                 TITLE_WITH_ENTITY,
                 null,
+                null,
                 ACTION,
                 null,
                 null,
@@ -243,6 +251,7 @@
                 TITLE_WITHOUT_ENTITY,
                 TITLE_WITH_ENTITY,
                 DESCRIPTION,
+                DESCRIPTION_WITH_APP_NAME,
                 null,
                 null,
                 null,
diff --git a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
index ae847c1..c3e4014 100644
--- a/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/KernelCpuThreadReaderTest.java
@@ -176,10 +176,10 @@
                 frequencies, 4);
         assertArrayEquals(
                 new int[]{1, 3, 1, 3},
-                frequencyBucketCreator.getBucketMinFrequencies(frequencies));
+                frequencyBucketCreator.bucketFrequencies(frequencies));
         assertArrayEquals(
                 new int[]{2, 2, 2, 2},
-                frequencyBucketCreator.getBucketedValues(new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
+                frequencyBucketCreator.bucketValues(new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
     }
 
     @Test
@@ -190,10 +190,10 @@
                 frequencies, 4);
         assertArrayEquals(
                 new int[]{1, 3, 5, 7},
-                frequencyBucketCreator.getBucketMinFrequencies(frequencies));
+                frequencyBucketCreator.bucketFrequencies(frequencies));
         assertArrayEquals(
                 new int[]{2, 2, 2, 2},
-                frequencyBucketCreator.getBucketedValues(new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
+                frequencyBucketCreator.bucketValues(new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
     }
 
     @Test
@@ -204,10 +204,10 @@
                 frequencies, 4);
         assertArrayEquals(
                 new int[]{1, 3, 1, 2},
-                frequencyBucketCreator.getBucketMinFrequencies(frequencies));
+                frequencyBucketCreator.bucketFrequencies(frequencies));
         assertArrayEquals(
                 new int[]{2, 3, 1, 2},
-                frequencyBucketCreator.getBucketedValues(new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
+                frequencyBucketCreator.bucketValues(new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
     }
 
     @Test
@@ -218,10 +218,10 @@
                 frequencies, 4);
         assertArrayEquals(
                 new int[]{1, 2, 1, 3},
-                frequencyBucketCreator.getBucketMinFrequencies(frequencies));
+                frequencyBucketCreator.bucketFrequencies(frequencies));
         assertArrayEquals(
                 new int[]{1, 2, 2, 3},
-                frequencyBucketCreator.getBucketedValues(new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
+                frequencyBucketCreator.bucketValues(new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
     }
 
     @Test
@@ -232,10 +232,10 @@
                 frequencies, 8);
         assertArrayEquals(
                 new int[]{1, 2, 3, 4, 1, 2, 3, 4},
-                frequencyBucketCreator.getBucketMinFrequencies(frequencies));
+                frequencyBucketCreator.bucketFrequencies(frequencies));
         assertArrayEquals(
                 new int[]{1, 1, 1, 1, 1, 1, 1, 1},
-                frequencyBucketCreator.getBucketedValues(new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
+                frequencyBucketCreator.bucketValues(new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
     }
 
     @Test
@@ -246,10 +246,10 @@
                 frequencies, 8);
         assertArrayEquals(
                 new int[]{1, 3, 5, 7, 1, 2, 3},
-                frequencyBucketCreator.getBucketMinFrequencies(frequencies));
+                frequencyBucketCreator.bucketFrequencies(frequencies));
         assertArrayEquals(
                 new int[]{2, 2, 2, 3, 1, 1, 1},
-                frequencyBucketCreator.getBucketedValues(
+                frequencyBucketCreator.bucketValues(
                         new long[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}));
     }
 
@@ -261,39 +261,37 @@
                 frequencies, 1);
         assertArrayEquals(
                 new int[]{1},
-                frequencyBucketCreator.getBucketMinFrequencies(frequencies));
+                frequencyBucketCreator.bucketFrequencies(frequencies));
         assertArrayEquals(
                 new int[]{8},
-                frequencyBucketCreator.getBucketedValues(
+                frequencyBucketCreator.bucketValues(
                         new long[]{1, 1, 1, 1, 1, 1, 1, 1}));
     }
 
     @Test
-    public void testGetBigFrequenciesStartIndex_simple() {
-        assertEquals(
-                3, KernelCpuThreadReader.FrequencyBucketCreator.getBigFrequenciesStartIndex(
-                        new long[]{1, 2, 3, 1, 2, 3}));
+    public void testBucketSetup_threeClusters() {
+        long[] frequencies = {1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6};
+        KernelCpuThreadReader.FrequencyBucketCreator frequencyBucketCreator =
+                new KernelCpuThreadReader.FrequencyBucketCreator(frequencies, 6);
+        assertArrayEquals(
+                new int[] {1, 3, 2, 4, 3, 5},
+                frequencyBucketCreator.bucketFrequencies(frequencies));
+        assertArrayEquals(
+                new int[] {2, 2, 2, 2, 2, 2},
+                frequencyBucketCreator.bucketValues(
+                        new long[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}));
     }
 
     @Test
-    public void testGetBigFrequenciesStartIndex_moreLittle() {
-        assertEquals(
-                4, KernelCpuThreadReader.FrequencyBucketCreator.getBigFrequenciesStartIndex(
-                        new long[]{1, 2, 3, 4, 1, 2}));
-    }
-
-    @Test
-    public void testGetBigFrequenciesStartIndex_moreBig() {
-        assertEquals(
-                2, KernelCpuThreadReader.FrequencyBucketCreator.getBigFrequenciesStartIndex(
-                        new long[]{1, 2, 1, 2, 3, 4}));
-    }
-
-    @Test
-    public void testGetBigFrequenciesStartIndex_noBig() {
-        assertEquals(
-                4, KernelCpuThreadReader.FrequencyBucketCreator.getBigFrequenciesStartIndex(
-                        new long[]{1, 2, 3, 4}));
+    public void testBucketSetup_moreClustersThanBuckets() {
+        long[] frequencies = {1, 1, 1, 1, 1, 1, 1, 1};
+        KernelCpuThreadReader.FrequencyBucketCreator frequencyBucketCreator =
+                new KernelCpuThreadReader.FrequencyBucketCreator(frequencies, 4);
+        assertArrayEquals(
+                new int[] {1, 1, 1, 1}, frequencyBucketCreator.bucketFrequencies(frequencies));
+        assertArrayEquals(
+                new int[] {1, 1, 1, 5},
+                frequencyBucketCreator.bucketValues(new long[] {1, 1, 1, 1, 1, 1, 1, 1}));
     }
 
     @Test
diff --git a/core/tests/overlaytests/host/src/com/android/server/om/hosttest/InstallOverlayTests.java b/core/tests/overlaytests/host/src/com/android/server/om/hosttest/InstallOverlayTests.java
index f9672d2..c133469 100644
--- a/core/tests/overlaytests/host/src/com/android/server/om/hosttest/InstallOverlayTests.java
+++ b/core/tests/overlaytests/host/src/com/android/server/om/hosttest/InstallOverlayTests.java
@@ -155,6 +155,14 @@
         }
     }
 
+    @Test
+    public void instantAppsNotVisibleToOMS() throws Exception {
+        installInstantPackage("OverlayHostTests_AppOverlayV1.apk");
+        assertFalse(overlayManagerContainsPackage(APP_OVERLAY_PACKAGE_NAME));
+        installConvertExistingInstantPackageToFull(APP_OVERLAY_PACKAGE_NAME);
+        assertTrue(overlayManagerContainsPackage(APP_OVERLAY_PACKAGE_NAME));
+    }
+
     private void delay() {
         try {
             Thread.sleep(100);
@@ -167,6 +175,15 @@
         delay();
     }
 
+    private void installInstantPackage(String pkg) throws Exception {
+        super.installPackage(pkg, "--instant");
+        delay();
+    }
+
+    private void installConvertExistingInstantPackageToFull(String pkg) throws Exception {
+        getDevice().executeShellCommand("cmd package install-existing --wait --full " + pkg);
+    }
+
     private void setPackageEnabled(String pkg, boolean enabled) throws Exception {
         getDevice().executeShellCommand("cmd package " + (enabled ? "enable " : "disable ") + pkg);
         delay();
diff --git a/libs/androidfw/CursorWindow.cpp b/libs/androidfw/CursorWindow.cpp
index a99e77f..e1067fc 100644
--- a/libs/androidfw/CursorWindow.cpp
+++ b/libs/androidfw/CursorWindow.cpp
@@ -49,15 +49,21 @@
     int ashmemFd = ashmem_create_region(ashmemName.string(), size);
     if (ashmemFd < 0) {
         result = -errno;
+        ALOGE("CursorWindow: ashmem_create_region() failed: errno=%d.", errno);
     } else {
         result = ashmem_set_prot_region(ashmemFd, PROT_READ | PROT_WRITE);
-        if (result >= 0) {
+        if (result < 0) {
+            ALOGE("CursorWindow: ashmem_set_prot_region() failed: errno=%d",errno);
+        } else {
             void* data = ::mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, ashmemFd, 0);
             if (data == MAP_FAILED) {
                 result = -errno;
+                ALOGE("CursorWindow: mmap() failed: errno=%d.", errno);
             } else {
                 result = ashmem_set_prot_region(ashmemFd, PROT_READ);
-                if (result >= 0) {
+                if (result < 0) {
+                    ALOGE("CursorWindow: ashmem_set_prot_region() failed: errno=%d.", errno);
+                } else {
                     CursorWindow* window = new CursorWindow(name, ashmemFd,
                             data, size, false /*readOnly*/);
                     result = window->clear();
@@ -86,26 +92,34 @@
     String8 name = parcel->readString8();
 
     status_t result;
+    int actualSize;
     int ashmemFd = parcel->readFileDescriptor();
     if (ashmemFd == int(BAD_TYPE)) {
         result = BAD_TYPE;
+        ALOGE("CursorWindow: readFileDescriptor() failed");
     } else {
         ssize_t size = ashmem_get_size_region(ashmemFd);
         if (size < 0) {
             result = UNKNOWN_ERROR;
+            ALOGE("CursorWindow: ashmem_get_size_region() failed: errno=%d.", errno);
         } else {
             int dupAshmemFd = ::fcntl(ashmemFd, F_DUPFD_CLOEXEC, 0);
             if (dupAshmemFd < 0) {
                 result = -errno;
+                ALOGE("CursorWindow: fcntl() failed: errno=%d.", errno);
             } else {
                 // the size of the ashmem descriptor can be modified between ashmem_get_size_region
                 // call and mmap, so we'll check again immediately after memory is mapped
                 void* data = ::mmap(NULL, size, PROT_READ, MAP_SHARED, dupAshmemFd, 0);
                 if (data == MAP_FAILED) {
                     result = -errno;
-                } else if (ashmem_get_size_region(dupAshmemFd) != size) {
+                    ALOGE("CursorWindow: mmap() failed: errno=%d.", errno);
+                } else if ((actualSize = ashmem_get_size_region(dupAshmemFd)) != size) {
                     ::munmap(data, size);
                     result = BAD_VALUE;
+                    ALOGE("CursorWindow: ashmem_get_size_region() returned %d, expected %d"
+                            " errno=%d",
+                            actualSize, (int) size, errno);
                 } else {
                     CursorWindow* window = new CursorWindow(name, dupAshmemFd,
                             data, size, true /*readOnly*/);
diff --git a/media/java/android/media/AudioAttributes.java b/media/java/android/media/AudioAttributes.java
index bf1063d..a3eee0a 100644
--- a/media/java/android/media/AudioAttributes.java
+++ b/media/java/android/media/AudioAttributes.java
@@ -557,7 +557,7 @@
         private int mContentType = CONTENT_TYPE_UNKNOWN;
         private int mSource = MediaRecorder.AudioSource.AUDIO_SOURCE_INVALID;
         private int mFlags = 0x0;
-        private boolean mMuteHapticChannels = true;
+        private boolean mMuteHapticChannels = false;
         private HashSet<String> mTags = new HashSet<String>();
         private Bundle mBundle;
 
@@ -888,7 +888,7 @@
 
         /**
          * Specifying if haptic should be muted or not when playing audio-haptic coupled data.
-         * By default, haptic channels are disabled.
+         * By default, haptic channels are enabled.
          * @param muted true to force muting haptic channels.
          * @return the same Builder instance.
          */
diff --git a/media/jni/Android.bp b/media/jni/Android.bp
index 65b58ab..5c3d780 100644
--- a/media/jni/Android.bp
+++ b/media/jni/Android.bp
@@ -129,6 +129,7 @@
         // NDK or LLNDK or NDK-compliant
         "libandroid",
         "libbinder_ndk",
+        "libcgrouprc",
         "libmediandk",
         "libmediametrics",
         "libnativehelper_compat_libc++",
diff --git a/packages/SettingsLib/BarChartPreference/res/layout/settings_bar_chart.xml b/packages/SettingsLib/BarChartPreference/res/layout/settings_bar_chart.xml
index 25246d6..0a336bf 100644
--- a/packages/SettingsLib/BarChartPreference/res/layout/settings_bar_chart.xml
+++ b/packages/SettingsLib/BarChartPreference/res/layout/settings_bar_chart.xml
@@ -36,6 +36,7 @@
         <LinearLayout
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
+            android:layout_marginBottom="20dp"
             android:gravity="center|bottom">
 
             <com.android.settingslib.widget.BarView
diff --git a/packages/SettingsLib/BarChartPreference/res/values/dimens.xml b/packages/SettingsLib/BarChartPreference/res/values/dimens.xml
index 7148afa..5f741a0 100644
--- a/packages/SettingsLib/BarChartPreference/res/values/dimens.xml
+++ b/packages/SettingsLib/BarChartPreference/res/values/dimens.xml
@@ -16,6 +16,6 @@
   -->
 
 <resources>
-    <dimen name="settings_bar_view_max_height">106dp</dimen>
+    <dimen name="settings_bar_view_max_height">72dp</dimen>
     <dimen name="settings_bar_view_icon_size">24dp</dimen>
 </resources>
\ No newline at end of file
diff --git a/packages/SettingsLib/BarChartPreference/res/values/styles.xml b/packages/SettingsLib/BarChartPreference/res/values/styles.xml
index 8302c01..7a3fb7d 100644
--- a/packages/SettingsLib/BarChartPreference/res/values/styles.xml
+++ b/packages/SettingsLib/BarChartPreference/res/values/styles.xml
@@ -40,7 +40,7 @@
 
     <style name="SettingsBarViewStyle">
         <item name="android:layout_width">0dp</item>
-        <item name="android:layout_height">250dp</item>
+        <item name="android:layout_height">168dp</item>
         <item name="android:layout_weight">1</item>
         <item name="android:layout_marginStart">8dp</item>
         <item name="android:layout_marginEnd">8dp</item>
@@ -63,6 +63,7 @@
         <item name="android:layout_height">@dimen/settings_bar_view_icon_size</item>
         <item name="android:scaleType">fitCenter</item>
         <item name="android:layout_marginTop">12dp</item>
+        <item name="android:tint">?android:attr/textColorPrimary</item>
     </style>
 
     <style name="SettingsBarChartBarTitle">
@@ -78,7 +79,6 @@
         <item name="android:layout_width">wrap_content</item>
         <item name="android:layout_height">wrap_content</item>
         <item name="android:layout_marginTop">4dp</item>
-        <item name="android:layout_marginBottom">12dp</item>
         <item name="android:singleLine">true</item>
         <item name="android:ellipsize">marquee</item>
         <item name="android:textAppearance">@style/BarChart.Text.Summary</item>
diff --git a/packages/SettingsLib/src/com/android/settingslib/notification/ZenDurationDialog.java b/packages/SettingsLib/src/com/android/settingslib/notification/ZenDurationDialog.java
index b9197fe..66ee802 100644
--- a/packages/SettingsLib/src/com/android/settingslib/notification/ZenDurationDialog.java
+++ b/packages/SettingsLib/src/com/android/settingslib/notification/ZenDurationDialog.java
@@ -210,7 +210,6 @@
     private void setupUi(ConditionTag tag, View row) {
         if (tag.lines == null) {
             tag.lines = row.findViewById(android.R.id.content);
-            tag.lines.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE);
         }
 
         if (tag.line1 == null) {
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl
index ce615b6..0075327 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/recents/IOverviewProxy.aidl
@@ -119,4 +119,8 @@
      */
     void onAssistantAvailable(boolean available) = 13;
 
+    /**
+     * Sent when the assistant changes how visible it is to the user.
+     */
+    void onAssistantVisibilityChanged(float visibility) = 14;
 }
diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
index 3aa9f73..a5aed87 100644
--- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
+++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleController.java
@@ -395,7 +395,6 @@
             }
             if (shouldAutoBubbleForFlags(mContext, entry) || shouldBubble(entry)) {
                 // TODO: handle group summaries
-                entry.setIsBubble(true);
                 boolean suppressNotification = entry.getBubbleMetadata() != null
                         && entry.getBubbleMetadata().getSuppressInitialNotification()
                         && isForegroundApp(entry.notification.getPackageName());
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java b/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
index 10eacba..644664e 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
@@ -22,7 +22,6 @@
 
 import android.content.Context;
 import android.content.Intent;
-import android.content.pm.UserInfo;
 import android.content.res.Configuration;
 import android.database.ContentObserver;
 import android.graphics.PorterDuff.Mode;
@@ -320,29 +319,13 @@
         mSettingsContainer.findViewById(R.id.tuner_icon).setVisibility(
                 TunerService.isTunerEnabled(mContext) ? View.VISIBLE : View.INVISIBLE);
         final boolean isDemo = UserManager.isDeviceInDemoMode(mContext);
-        mMultiUserSwitch.setVisibility(showUserSwitcher(isDemo) ? View.VISIBLE : View.INVISIBLE);
+        mMultiUserSwitch.setVisibility(showUserSwitcher() ? View.VISIBLE : View.INVISIBLE);
         mEditContainer.setVisibility(isDemo || !mExpanded ? View.INVISIBLE : View.VISIBLE);
         mSettingsButton.setVisibility(isDemo || !mExpanded ? View.INVISIBLE : View.VISIBLE);
     }
 
-    private boolean showUserSwitcher(boolean isDemo) {
-        if (!mExpanded || isDemo || !UserManager.supportsMultipleUsers()) {
-            return false;
-        }
-        UserManager userManager = UserManager.get(mContext);
-        if (userManager.hasUserRestriction(UserManager.DISALLOW_USER_SWITCH)) {
-            return false;
-        }
-        int switchableUserCount = 0;
-        for (UserInfo user : userManager.getUsers(true)) {
-            if (user.supportsSwitchToByUser()) {
-                ++switchableUserCount;
-                if (switchableUserCount > 1) {
-                    return true;
-                }
-            }
-        }
-        return getResources().getBoolean(R.bool.qs_show_user_switcher_for_single_user);
+    private boolean showUserSwitcher() {
+        return mExpanded && mMultiUserSwitch.isMultiUserEnabled();
     }
 
     private void updateListeners() {
diff --git a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
index ead39c69..144c309 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java
@@ -633,6 +633,14 @@
         }
     }
 
+    public void notifyAssistantVisibilityChanged(float visibility) {
+        try {
+            mOverviewProxy.onAssistantVisibilityChanged(visibility);
+        } catch (RemoteException e) {
+            Log.e(TAG_OPS, "Failed to call onAssistantVisibilityChanged()", e);
+        }
+    }
+
     private void updateEnabledState() {
         mIsEnabled = mContext.getPackageManager().resolveServiceAsUser(mQuickStepIntent,
                 MATCH_SYSTEM_ONLY,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationRemoteInputManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationRemoteInputManager.java
index a630e49..2793b2a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationRemoteInputManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationRemoteInputManager.java
@@ -63,6 +63,7 @@
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.util.ArrayList;
+import java.util.Objects;
 import java.util.Set;
 
 import javax.inject.Inject;
@@ -142,7 +143,7 @@
             if (DEBUG) {
                 Log.v(TAG, "Notification click handler invoked for intent: " + pendingIntent);
             }
-            logActionClick(view);
+            logActionClick(view, pendingIntent);
             // The intent we are sending is for the application, which
             // won't have permission to immediately start an activity after
             // the user switches to home.  We know it is safe to do at this
@@ -159,11 +160,11 @@
             });
         }
 
-        private void logActionClick(View view) {
+        private void logActionClick(View view, PendingIntent actionIntent) {
             Integer actionIndex = (Integer)
                     view.getTag(com.android.internal.R.id.notification_action_index_tag);
             if (actionIndex == null) {
-                Log.e(TAG, "Couldn't retrieve the actionIndex from the clicked button");
+                // Custom action button, not logging.
                 return;
             }
             ViewParent parent = view.getParent();
@@ -182,8 +183,20 @@
             }
             final int count = mEntryManager.getNotificationData().getActiveNotifications().size();
             final int rank = mEntryManager.getNotificationData().getRank(key);
+
+            // Notification may be updated before this function is executed, and thus play safe
+            // here and verify that the action object is still the one that where the click happens.
+            Notification.Action[] actions = statusBarNotification.getNotification().actions;
+            if (actions == null || actionIndex >= actions.length) {
+                Log.w(TAG, "statusBarNotification.getNotification().actions is null or invalid");
+                return;
+            }
             final Notification.Action action =
                     statusBarNotification.getNotification().actions[actionIndex];
+            if (Objects.equals(action.actionIntent, actionIntent)) {
+                Log.w(TAG, "actionIntent does not match");
+                return;
+            }
             NotificationVisibility.NotificationLocation location =
                     NotificationLogger.getNotificationLocation(
                             mEntryManager.getNotificationData().get(key));
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
index f1373d1..4f4dcbc 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationEntry.java
@@ -21,6 +21,7 @@
 import static android.app.Notification.CATEGORY_EVENT;
 import static android.app.Notification.CATEGORY_MESSAGE;
 import static android.app.Notification.CATEGORY_REMINDER;
+import static android.app.Notification.FLAG_BUBBLE;
 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_AMBIENT;
 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_NOTIFICATION_LIST;
@@ -146,11 +147,6 @@
     private boolean hasSentReply;
 
     /**
-     * Whether this notification should be displayed as a bubble.
-     */
-    private boolean mIsBubble;
-
-    /**
      * Whether this notification has been approved globally, at the app level, and at the channel
      * level for bubbling.
      */
@@ -222,12 +218,8 @@
         this.mHighPriority = highPriority;
     }
 
-    public void setIsBubble(boolean bubbleable) {
-        mIsBubble = bubbleable;
-    }
-
     public boolean isBubble() {
-        return mIsBubble;
+        return (notification.getNotification().flags & FLAG_BUBBLE) != 0;
     }
 
     public void setBubbleDismissed(boolean userDismissed) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
index 2bd8d41..6ee031a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
@@ -187,9 +187,9 @@
         }
         if (mKeyguardUserSwitcher == null) {
             // If we have no keyguard switcher, the screen width is under 600dp. In this case,
-            // we don't show the multi-user avatar unless there is more than 1 user on the device.
-            if (mUserSwitcherController != null
-                    && mUserSwitcherController.getSwitchableUserCount() > 1) {
+            // we only show the multi-user switch if it's enabled through UserManager as well as
+            // by the user.
+            if (mMultiUserSwitch.isMultiUserEnabled()) {
                 mMultiUserSwitch.setVisibility(View.VISIBLE);
             } else {
                 mMultiUserSwitch.setVisibility(View.GONE);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/MultiUserSwitch.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/MultiUserSwitch.java
index f393dcd..1d87a8b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/MultiUserSwitch.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/MultiUserSwitch.java
@@ -16,10 +16,10 @@
 
 package com.android.systemui.statusbar.phone;
 
+import android.app.admin.DevicePolicyManager;
 import android.content.Context;
-import android.content.Intent;
 import android.os.UserManager;
-import android.provider.ContactsContract;
+import android.provider.Settings;
 import android.text.TextUtils;
 import android.util.AttributeSet;
 import android.view.View;
@@ -33,7 +33,6 @@
 import com.android.systemui.Prefs;
 import com.android.systemui.Prefs.Key;
 import com.android.systemui.R;
-import com.android.systemui.plugins.ActivityStarter;
 import com.android.systemui.plugins.qs.DetailAdapter;
 import com.android.systemui.qs.QSPanel;
 import com.android.systemui.statusbar.policy.KeyguardUserSwitcher;
@@ -95,6 +94,26 @@
         registerListener();
     }
 
+    public boolean isMultiUserEnabled() {
+        // Short-circuiting from UserManager. Needs to be extracted because of SystemUI boolean flag
+        // qs_show_user_switcher_for_single_user
+
+        final boolean userSwitcherEnabled = Settings.Global.getInt(mContext.getContentResolver(),
+                Settings.Global.USER_SWITCHER_ENABLED, 1) != 0;
+
+        if (!UserManager.supportsMultipleUsers()
+                || mUserManager.hasUserRestriction(UserManager.DISALLOW_USER_SWITCH)
+                || UserManager.isDeviceInDemoMode(mContext)
+                || !userSwitcherEnabled) {
+            return false;
+        }
+
+        final boolean guestEnabled = !mContext.getSystemService(DevicePolicyManager.class)
+                .getGuestUserDisabled(null);
+        return mUserSwitcherController.getSwitchableUserCount() > 1 || guestEnabled
+                || mContext.getResources().getBoolean(R.bool.qs_show_user_switcher_for_single_user);
+    }
+
     private void registerListener() {
         if (mUserManager.isUserSwitcherEnabled() && mUserListener == null) {
 
@@ -118,29 +137,20 @@
 
     @Override
     public void onClick(View v) {
-        if (mUserManager.isUserSwitcherEnabled()) {
-            if (mKeyguardMode) {
-                if (mKeyguardUserSwitcher != null) {
-                    mKeyguardUserSwitcher.show(true /* animate */);
-                }
-            } else if (mQsPanel != null && mUserSwitcherController != null) {
-                View center = getChildCount() > 0 ? getChildAt(0) : this;
-
-                center.getLocationInWindow(mTmpInt2);
-                mTmpInt2[0] += center.getWidth() / 2;
-                mTmpInt2[1] += center.getHeight() / 2;
-
-                mQsPanel.showDetailAdapter(true,
-                        getUserDetailAdapter(),
-                        mTmpInt2);
+        if (mKeyguardMode) {
+            if (mKeyguardUserSwitcher != null) {
+                mKeyguardUserSwitcher.show(true /* animate */);
             }
-        } else {
-            if (mQsPanel != null) {
-                Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent(
-                        getContext(), v, ContactsContract.Profile.CONTENT_URI,
-                        ContactsContract.QuickContact.MODE_LARGE, null);
-                Dependency.get(ActivityStarter.class).postStartActivityDismissingKeyguard(intent, 0);
-            }
+        } else if (mQsPanel != null && mUserSwitcherController != null) {
+            View center = getChildCount() > 0 ? getChildAt(0) : this;
+
+            center.getLocationInWindow(mTmpInt2);
+            mTmpInt2[0] += center.getWidth() / 2;
+            mTmpInt2[1] += center.getHeight() / 2;
+
+            mQsPanel.showDetailAdapter(true,
+                    getUserDetailAdapter(),
+                    mTmpInt2);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
index 9343bf1..f726321 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
@@ -403,7 +403,7 @@
         final int N = mUsers.size();
         for (int i = 0; i < N; ++i) {
             UserRecord record = mUsers.get(i);
-            if (record.info != null && record.info.supportsSwitchTo()) {
+            if (record.info != null && record.info.supportsSwitchToByUser()) {
                 count++;
             }
         }
diff --git a/packages/SystemUI/src/com/android/systemui/volume/CaptionsToggleImageButton.java b/packages/SystemUI/src/com/android/systemui/volume/CaptionsToggleImageButton.java
index 8ec66e4..45fc756 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/CaptionsToggleImageButton.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/CaptionsToggleImageButton.java
@@ -17,7 +17,10 @@
 package com.android.systemui.volume;
 
 import android.content.Context;
+import android.os.Handler;
 import android.util.AttributeSet;
+import android.view.GestureDetector;
+import android.view.MotionEvent;
 
 import com.android.keyguard.AlphaOptimizedImageButton;
 import com.android.systemui.R;
@@ -27,14 +30,34 @@
 
     private static final int[] OPTED_OUT_STATE = new int[] { R.attr.optedOut };
 
+    private ConfirmedTapListener mConfirmedTapListener;
     private boolean mComponentEnabled = false;
     private boolean mOptedOut = false;
 
+    private GestureDetector mGestureDetector;
+    private GestureDetector.SimpleOnGestureListener mGestureListener =
+            new GestureDetector.SimpleOnGestureListener() {
+        @Override
+        public boolean onSingleTapConfirmed(MotionEvent e) {
+            if (mConfirmedTapListener != null) {
+                mConfirmedTapListener.onConfirmedTap();
+                return true;
+            }
+            return false;
+        }
+    };
+
     public CaptionsToggleImageButton(Context context, AttributeSet attrs) {
         super(context, attrs);
     }
 
     @Override
+    public boolean onTouchEvent(MotionEvent event) {
+        if (mGestureDetector != null) mGestureDetector.onTouchEvent(event);
+        return super.onTouchEvent(event);
+    }
+
+    @Override
     public int[] onCreateDrawableState(int extraSpace) {
         int[] state = super.onCreateDrawableState(extraSpace + 1);
         if (mOptedOut) {
@@ -64,4 +87,17 @@
     boolean getOptedOut() {
         return this.mOptedOut;
     }
+
+    void setOnConfirmedTapListener(ConfirmedTapListener listener, Handler handler) {
+        mConfirmedTapListener = listener;
+
+        if (mGestureDetector == null) {
+            this.mGestureDetector = new GestureDetector(getContext(), mGestureListener, handler);
+        }
+    }
+
+    /** Listener for confirmed taps rather than normal on click listener. */
+    interface ConfirmedTapListener {
+        void onConfirmedTap();
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
index 35a2450..2094b36 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
@@ -419,8 +419,9 @@
             row.header.setFilters(new InputFilter[] {new InputFilter.LengthFilter(13)});
         }
         row.dndIcon = row.view.findViewById(R.id.dnd_icon);
-        row.slider =  row.view.findViewById(R.id.volume_row_slider);
+        row.slider = row.view.findViewById(R.id.volume_row_slider);
         row.slider.setOnSeekBarChangeListener(new VolumeSeekBarChangeListener(row));
+
         row.anim = null;
 
         row.icon = row.view.findViewById(R.id.volume_row_icon);
@@ -515,11 +516,11 @@
 
     private void initODICaptionsH() {
         if (mODICaptionsIcon != null) {
-            mODICaptionsIcon.setOnClickListener(v -> {
+            mODICaptionsIcon.setOnConfirmedTapListener(() -> {
                 onCaptionIconClicked();
                 Events.writeEvent(mContext, Events.EVENT_ODI_CAPTIONS_CLICK);
                 dismissH(DISMISS_REASON_ODI_CAPTIONS_CLICKED);
-            });
+            }, mHandler);
         }
 
         mController.getCaptionsComponentState(false);
@@ -1393,6 +1394,7 @@
             if (mRow.ss.level != userLevel || mRow.ss.muted && userLevel > 0) {
                 mRow.userAttempt = SystemClock.uptimeMillis();
                 if (mRow.requestedLevel != userLevel) {
+                    mController.setActiveStream(mRow.stream);
                     mController.setStreamVolume(mRow.stream, userLevel);
                     mRow.requestedLevel = userLevel;
                     Events.writeEvent(mContext, Events.EVENT_TOUCH_LEVEL_CHANGED, mRow.stream,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
index 9fa85d3..5e16721 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java
@@ -18,9 +18,12 @@
 
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.times;
@@ -42,7 +45,6 @@
 
 import androidx.test.filters.SmallTest;
 
-import com.android.internal.statusbar.NotificationVisibility;
 import com.android.systemui.R;
 import com.android.systemui.SysuiTestCase;
 import com.android.systemui.statusbar.NotificationTestHelper;
@@ -96,9 +98,9 @@
     private NotificationTestHelper mNotificationTestHelper;
     private ExpandableNotificationRow mRow;
     private ExpandableNotificationRow mRow2;
-    private ExpandableNotificationRow mNoChannelRow;
     private ExpandableNotificationRow mAutoExpandRow;
     private ExpandableNotificationRow mSuppressNotifRow;
+    private ExpandableNotificationRow mNonBubbleNotifRow;
 
     @Mock
     private NotificationData mNotificationData;
@@ -107,9 +109,6 @@
     @Mock
     private BubbleController.BubbleExpandListener mBubbleExpandListener;
     @Mock
-    NotificationVisibility mNotificationVisibility;
-
-    @Mock
     private PendingIntent mDeleteIntent;
 
     private BubbleData mBubbleData;
@@ -129,7 +128,7 @@
         mNotificationTestHelper = new NotificationTestHelper(mContext);
         mRow = mNotificationTestHelper.createBubble(mDeleteIntent);
         mRow2 = mNotificationTestHelper.createBubble(mDeleteIntent);
-        mNoChannelRow = mNotificationTestHelper.createBubble(mDeleteIntent);
+        mNonBubbleNotifRow = mNotificationTestHelper.createRow();
 
         // Some bubbles want to auto expand
         Notification.BubbleMetadata autoExpandMetadata =
@@ -146,7 +145,6 @@
         // Return non-null notification data from the NEM
         when(mNotificationEntryManager.getNotificationData()).thenReturn(mNotificationData);
         when(mNotificationData.getChannel(mRow.getEntry().key)).thenReturn(mRow.getEntry().channel);
-        when(mNotificationData.getChannel(mNoChannelRow.getEntry().key)).thenReturn(null);
 
         mBubbleData = new BubbleData();
         mBubbleController = new TestableBubbleController(mContext, mStatusBarWindowController,
@@ -391,8 +389,7 @@
         mEntryListener.onPendingEntryAdded(mSuppressNotifRow.getEntry());
         mBubbleController.updateBubble(mSuppressNotifRow.getEntry(), true /* updatePosition */);
 
-        // Should be a bubble & should show in shade because we weren't forground
-        assertTrue(mSuppressNotifRow.getEntry().isBubble());
+        // Should show in shade because we weren't forground
         assertTrue(mSuppressNotifRow.getEntry().showInShadeWhenBubble());
 
         // # of bubbles should change
@@ -428,8 +425,7 @@
         mEntryListener.onPendingEntryAdded(mSuppressNotifRow.getEntry());
         mBubbleController.updateBubble(mSuppressNotifRow.getEntry(), true /* updatePosition */);
 
-        // Should be a bubble & should NOT show in shade because we were foreground
-        assertTrue(mSuppressNotifRow.getEntry().isBubble());
+        // Should NOT show in shade because we were foreground
         assertFalse(mSuppressNotifRow.getEntry().showInShadeWhenBubble());
 
         // # of bubbles should change
@@ -444,8 +440,6 @@
         mEntryListener.onPendingEntryAdded(mRow.getEntry());
         mBubbleController.updateBubble(mRow.getEntry(), true /* updatePosition */);
 
-        assertTrue(mRow.getEntry().isBubble());
-
         // Simulate notification cancellation.
         mEntryListener.onEntryRemoved(mRow.getEntry(), null /* notificationVisibility (unused) */,
                 false /* removedbyUser */);
@@ -454,18 +448,21 @@
     }
 
     @Test
-    public void testMarkNewNotificationAsBubble() {
-        mEntryListener.onPendingEntryAdded(mRow.getEntry());
-        assertTrue(mRow.getEntry().isBubble());
-    }
-
-    @Test
     public void testMarkNewNotificationAsShowInShade() {
         mEntryListener.onPendingEntryAdded(mRow.getEntry());
         assertTrue(mRow.getEntry().showInShadeWhenBubble());
     }
 
     @Test
+    public void testAddNotif_notBubble() {
+        mEntryListener.onPendingEntryAdded(mNonBubbleNotifRow.getEntry());
+        mEntryListener.onPreEntryUpdated(mNonBubbleNotifRow.getEntry());
+
+        verify(mBubbleStateChangeListener, never()).onHasBubblesChanged(anyBoolean());
+        assertThat(mBubbleController.hasBubbles()).isFalse();
+    }
+
+    @Test
     public void testDeleteIntent_removeBubble_aged() throws PendingIntent.CanceledException {
         mBubbleController.updateBubble(mRow.getEntry(), true /* updatePosition */);
         mBubbleController.removeBubble(mRow.getEntry().key, BubbleController.DISMISS_AGED);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
index 50fadef..910cee3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/animation/StackAnimationControllerTest.java
@@ -57,6 +57,7 @@
      * direction is correct.
      */
     @Test
+    @Ignore("Flaking")
     public void testMoveFirstBubbleWithStackFollowing() throws InterruptedException {
         mStackController.moveFirstBubbleWithStackFollowing(200, 100);
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
index 7e089a6..8cc1571 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
@@ -16,6 +16,7 @@
 
 package com.android.systemui.statusbar;
 
+import static android.app.Notification.FLAG_BUBBLE;
 import static android.app.NotificationManager.IMPORTANCE_DEFAULT;
 import static android.app.NotificationManager.IMPORTANCE_HIGH;
 
@@ -154,9 +155,7 @@
      */
     public ExpandableNotificationRow createBubble()
             throws Exception {
-        Notification n = createNotification(false /* isGroupSummary */,
-                null /* groupKey */, makeBubbleMetadata(null));
-        return generateRow(n, PKG, UID, USER_HANDLE, 0 /* extraInflationFlags */, IMPORTANCE_HIGH);
+        return createBubble(makeBubbleMetadata(null), PKG);
     }
 
     /**
@@ -166,21 +165,7 @@
      */
     public ExpandableNotificationRow createBubble(@Nullable PendingIntent deleteIntent)
             throws Exception {
-        Notification n = createNotification(false /* isGroupSummary */,
-                null /* groupKey */, makeBubbleMetadata(deleteIntent));
-        return generateRow(n, PKG, UID, USER_HANDLE, 0 /* extraInflationFlags */, IMPORTANCE_HIGH);
-    }
-
-    /**
-     * Returns an {@link ExpandableNotificationRow} that should be shown as a bubble.
-     *
-     * @param bubbleMetadata the {@link BubbleMetadata} to use
-     */
-    public ExpandableNotificationRow createBubble(BubbleMetadata bubbleMetadata)
-            throws Exception {
-        Notification n = createNotification(false /* isGroupSummary */,
-                null /* groupKey */, bubbleMetadata);
-        return generateRow(n, PKG, UID, USER_HANDLE, 0 /* extraInflationFlags */, IMPORTANCE_HIGH);
+        return createBubble(makeBubbleMetadata(deleteIntent), PKG);
     }
 
     /**
@@ -192,6 +177,7 @@
             throws Exception {
         Notification n = createNotification(false /* isGroupSummary */,
                 null /* groupKey */, bubbleMetadata);
+        n.flags |= FLAG_BUBBLE;
         return generateRow(n, pkg, UID, USER_HANDLE, 0 /* extraInflationFlags */, IMPORTANCE_HIGH);
     }
 
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
index 41e82cb..51fb47b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java
@@ -152,7 +152,6 @@
         bubbleSbn.getNotification().contentIntent = mContentIntent;
         bubbleSbn.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
         // Do what BubbleController's NotificationEntryListener#onPendingEntryAdded does:
-        mBubbleNotificationRow.getEntry().setIsBubble(true);
         mBubbleNotificationRow.getEntry().setShowInShadeWhenBubble(true);
 
         mActiveNotifications = new ArrayList<>();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java
index cd9069a..3edfb56 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/SmartReplyConstantsTest.java
@@ -95,7 +95,7 @@
         triggerConstantsOnChange();
         assertEquals(false, mConstants.requiresTargetingP());
 
-        overrideSetting(SystemUiDeviceConfigFlags.SSIN_REQUIRES_TARGETING_P, "");
+        overrideSetting(SystemUiDeviceConfigFlags.SSIN_REQUIRES_TARGETING_P, null);
         triggerConstantsOnChange();
         assertEquals(true, mConstants.requiresTargetingP());
     }
@@ -223,21 +223,21 @@
 
     private void resetAllDeviceConfigFlags() {
         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
-                SystemUiDeviceConfigFlags.SSIN_ENABLED, "", false /* makeDefault */);
+                SystemUiDeviceConfigFlags.SSIN_ENABLED, null, false /* makeDefault */);
         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
-                SystemUiDeviceConfigFlags.SSIN_REQUIRES_TARGETING_P, "", false /* makeDefault */);
+                SystemUiDeviceConfigFlags.SSIN_REQUIRES_TARGETING_P, null, false /* makeDefault */);
         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
-                SystemUiDeviceConfigFlags.SSIN_MAX_SQUEEZE_REMEASURE_ATTEMPTS, "",
+                SystemUiDeviceConfigFlags.SSIN_MAX_SQUEEZE_REMEASURE_ATTEMPTS, null,
                 false /* makeDefault */);
         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
-                SystemUiDeviceConfigFlags.SSIN_EDIT_CHOICES_BEFORE_SENDING, "",
+                SystemUiDeviceConfigFlags.SSIN_EDIT_CHOICES_BEFORE_SENDING, null,
                 false /* makeDefault */);
         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
-                SystemUiDeviceConfigFlags.SSIN_SHOW_IN_HEADS_UP, "", false /* makeDefault */);
+                SystemUiDeviceConfigFlags.SSIN_SHOW_IN_HEADS_UP, null, false /* makeDefault */);
         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
-                SystemUiDeviceConfigFlags.SSIN_MIN_NUM_SYSTEM_GENERATED_REPLIES, "",
+                SystemUiDeviceConfigFlags.SSIN_MIN_NUM_SYSTEM_GENERATED_REPLIES, null,
                 false /* makeDefault */);
         DeviceConfig.setProperty(DeviceConfig.NAMESPACE_SYSTEMUI,
-                SystemUiDeviceConfigFlags.SSIN_MAX_NUM_ACTIONS, "", false /* makeDefault */);
+                SystemUiDeviceConfigFlags.SSIN_MAX_NUM_ACTIONS, null, false /* makeDefault */);
     }
 }
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index 7106664..79afe8e 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -31,11 +31,14 @@
 import android.app.job.JobParameters;
 import android.app.job.JobScheduler;
 import android.app.job.JobService;
+import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.os.Binder;
+import android.os.FileUtils;
 import android.os.HandlerThread;
 import android.os.IBinder;
 import android.os.ParcelFileDescriptor;
@@ -49,6 +52,7 @@
 import com.android.server.SystemConfig;
 import com.android.server.SystemService;
 
+import java.io.File;
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.util.Collections;
@@ -86,6 +90,18 @@
 
     private Set<ComponentName> mTransportWhitelist;
 
+    private final BroadcastReceiver mUserRemovedReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (Intent.ACTION_USER_REMOVED.equals(intent.getAction())) {
+                int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
+                if (userId > 0) { // for only non system users
+                    onRemovedNonSystemUser(userId);
+                }
+            }
+        }
+    };
+
     /** Instantiate a new instance of {@link BackupManagerService}. */
     public BackupManagerService(
             Context context, Trampoline trampoline, HandlerThread backupThread) {
@@ -99,6 +115,23 @@
         if (mTransportWhitelist == null) {
             mTransportWhitelist = Collections.emptySet();
         }
+
+        mContext.registerReceiver(mUserRemovedReceiver,
+                new IntentFilter(Intent.ACTION_USER_REMOVED));
+    }
+
+    /**
+     * Remove backup state for non system {@code userId} when the user is removed from the device.
+     * For non system users, backup state is stored in both the user's own dir and the system dir.
+     * When the user is removed, the user's own dir gets removed by the OS. This method ensures that
+     * the part of the user backup state which is in the system dir also gets removed.
+     */
+    private void onRemovedNonSystemUser(int userId) {
+        Slog.i(TAG, "Removing state for non system user " + userId);
+        File dir = UserBackupManagerFiles.getStateDirInSystemDir(userId);
+        if (!FileUtils.deleteContentsAndDir(dir)) {
+            Slog.w(TAG, "Failed to delete state dir for removed user: " + userId);
+        }
     }
 
     /**
diff --git a/services/backup/java/com/android/server/backup/Trampoline.java b/services/backup/java/com/android/server/backup/Trampoline.java
index bb0aba0..a9b292b3 100644
--- a/services/backup/java/com/android/server/backup/Trampoline.java
+++ b/services/backup/java/com/android/server/backup/Trampoline.java
@@ -47,7 +47,6 @@
 
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.util.DumpUtils;
-import com.android.server.backup.utils.FileUtils;
 import com.android.server.backup.utils.RandomAccessFileUtils;
 
 import java.io.File;
@@ -95,7 +94,7 @@
      * Name of file for non-system users that remembers whether backup was explicitly activated or
      * deactivated with a call to setBackupServiceActive.
      */
-    private static final String REMEMBER_ACTIVATED_FILENAME_PREFIX = "backup-remember-activated";
+    private static final String REMEMBER_ACTIVATED_FILENAME = "backup-remember-activated";
 
     // Product-level suppression of backup/restore.
     private static final String BACKUP_DISABLE_PROPERTY = "ro.backup.disable";
@@ -143,8 +142,7 @@
 
     /** Stored in the system user's directory and the file is indexed by the user it refers to. */
     protected File getRememberActivatedFileForNonSystemUser(int userId) {
-        return FileUtils.createNewFile(UserBackupManagerFiles.getStateFileInSystemDir(
-                REMEMBER_ACTIVATED_FILENAME_PREFIX, userId));
+        return UserBackupManagerFiles.getStateFileInSystemDir(REMEMBER_ACTIVATED_FILENAME, userId);
     }
 
     /** Stored in the system user's directory and the file is indexed by the user it refers to. */
@@ -336,8 +334,13 @@
         // action since we need to remember that a permissioned call was made irrespective of
         // whether the call changes the state or not.
         if (userId != UserHandle.USER_SYSTEM) {
-            RandomAccessFileUtils.writeBoolean(getRememberActivatedFileForNonSystemUser(userId),
-                    makeActive);
+            try {
+                File rememberFile = getRememberActivatedFileForNonSystemUser(userId);
+                createFile(rememberFile);
+                RandomAccessFileUtils.writeBoolean(rememberFile, makeActive);
+            } catch (IOException e) {
+                Slog.e(TAG, "Unable to persist backup service activity", e);
+            }
         }
 
         if (mGlobalDisable) {
diff --git a/services/backup/java/com/android/server/backup/UserBackupManagerFiles.java b/services/backup/java/com/android/server/backup/UserBackupManagerFiles.java
index 4638ac6..8e60542 100644
--- a/services/backup/java/com/android/server/backup/UserBackupManagerFiles.java
+++ b/services/backup/java/com/android/server/backup/UserBackupManagerFiles.java
@@ -49,8 +49,13 @@
         return new File(Environment.getDownloadCacheDirectory(), BACKUP_STAGING_DIR);
     }
 
-    /** Stored in the system user's directory and the file is indexed by the user it refers to. */
-    static File getStateFileInSystemDir(String prefix, int userId) {
-        return new File(getBaseStateDir(UserHandle.USER_SYSTEM), prefix + "-" + userId);
+    /** A user specific dir within the system user's directory. */
+    static File getStateDirInSystemDir(int userId) {
+        return new File(getBaseStateDir(UserHandle.USER_SYSTEM), "" + userId);
+    }
+
+    /** Stored in a user specific dir within the system user's directory. */
+    static File getStateFileInSystemDir(String filename, int userId) {
+        return new File(getStateDirInSystemDir(userId), filename);
     }
 }
diff --git a/services/core/java/com/android/server/am/AppCompactor.java b/services/core/java/com/android/server/am/AppCompactor.java
index f58fb95..ac10026 100644
--- a/services/core/java/com/android/server/am/AppCompactor.java
+++ b/services/core/java/com/android/server/am/AppCompactor.java
@@ -485,9 +485,10 @@
                         long zramFreeKbAfter = Debug.getZramFreeKb();
                         EventLog.writeEvent(EventLogTags.AM_COMPACT, pid, name, action,
                                 rssBefore[0], rssBefore[1], rssBefore[2], rssBefore[3],
-                                rssAfter[0], rssAfter[1], rssAfter[2], rssAfter[3], time,
+                                rssAfter[0] - rssBefore[0], rssAfter[1] - rssBefore[1],
+                                rssAfter[2] - rssBefore[2], rssAfter[3] - rssBefore[3], time,
                                 lastCompactAction, lastCompactTime, msg.arg1, msg.arg2,
-                                zramFreeKbBefore, zramFreeKbAfter);
+                                zramFreeKbBefore, zramFreeKbAfter - zramFreeKbBefore);
                         // Note that as above not taking mPhenoTypeFlagLock here to avoid locking
                         // on every single compaction for a flag that will seldom change and the
                         // impact of reading the wrong value here is low.
diff --git a/services/core/java/com/android/server/am/EventLogTags.logtags b/services/core/java/com/android/server/am/EventLogTags.logtags
index 4b12e43..e65a4e5 100644
--- a/services/core/java/com/android/server/am/EventLogTags.logtags
+++ b/services/core/java/com/android/server/am/EventLogTags.logtags
@@ -138,4 +138,4 @@
 30061 am_remove_task (Task ID|1|5), (Stack ID|1|5)
 
 # The task is being compacted
-30063 am_compact (Pid|1|5),(Process Name|3),(Action|3),(BeforeRssTotal|2|2),(BeforeRssFile|2|2),(BeforeRssAnon|2|2),(BeforeRssSwap|2|2),(AfterRssTotal|2|2),(AfterRssFile|2|2),(AfterRssAnon|2|2),(AfterRssSwap|2|2),(Time|2|3),(LastAction|1|2),(LastActionTimestamp|2|3),(setAdj|1|2),(procState|1|2),(BeforeZRAMFree|2|2),(AfterZRAMFree|2|2)
+30063 am_compact (Pid|1|5),(Process Name|3),(Action|3),(BeforeRssTotal|2|2),(BeforeRssFile|2|2),(BeforeRssAnon|2|2),(BeforeRssSwap|2|2),(DeltaRssTotal|2|2),(DeltaRssFile|2|2),(DeltaRssAnon|2|2),(DeltaRssSwap|2|2),(Time|2|3),(LastAction|1|2),(LastActionTimestamp|2|3),(setAdj|1|2),(procState|1|2),(BeforeZRAMFree|2|2),(DeltaZRAMFree|2|2)
diff --git a/services/core/java/com/android/server/connectivity/PermissionMonitor.java b/services/core/java/com/android/server/connectivity/PermissionMonitor.java
index 31b96ca..da1360d 100644
--- a/services/core/java/com/android/server/connectivity/PermissionMonitor.java
+++ b/services/core/java/com/android/server/connectivity/PermissionMonitor.java
@@ -100,6 +100,9 @@
                               app.requestedPermissionsFlags);
                     }
                 }
+            } else {
+                // The last package of this uid is removed from device. Clean the package up.
+                permission = INetd.PERMISSION_UNINSTALLED;
             }
             return permission;
         }
@@ -470,6 +473,7 @@
         ArrayList<Integer> allPermissionAppIds = new ArrayList<>();
         ArrayList<Integer> internetPermissionAppIds = new ArrayList<>();
         ArrayList<Integer> updateStatsPermissionAppIds = new ArrayList<>();
+        ArrayList<Integer> noPermissionAppIds = new ArrayList<>();
         ArrayList<Integer> uninstalledAppIds = new ArrayList<>();
         for (int i = 0; i < netdPermissionsAppIds.size(); i++) {
             int permissions = netdPermissionsAppIds.valueAt(i);
@@ -484,8 +488,10 @@
                     updateStatsPermissionAppIds.add(netdPermissionsAppIds.keyAt(i));
                     break;
                 case INetd.NO_PERMISSIONS:
-                    uninstalledAppIds.add(netdPermissionsAppIds.keyAt(i));
+                    noPermissionAppIds.add(netdPermissionsAppIds.keyAt(i));
                     break;
+                case INetd.PERMISSION_UNINSTALLED:
+                    uninstalledAppIds.add(netdPermissionsAppIds.keyAt(i));
                 default:
                     Log.e(TAG, "unknown permission type: " + permissions + "for uid: "
                             + netdPermissionsAppIds.keyAt(i));
@@ -506,8 +512,12 @@
                 mNetd.trafficSetNetPermForUids(INetd.PERMISSION_UPDATE_DEVICE_STATS,
                         ArrayUtils.convertToIntArray(updateStatsPermissionAppIds));
             }
-            if (uninstalledAppIds.size() != 0) {
+            if (noPermissionAppIds.size() != 0) {
                 mNetd.trafficSetNetPermForUids(INetd.NO_PERMISSIONS,
+                        ArrayUtils.convertToIntArray(noPermissionAppIds));
+            }
+            if (uninstalledAppIds.size() != 0) {
+                mNetd.trafficSetNetPermForUids(INetd.PERMISSION_UNINSTALLED,
                         ArrayUtils.convertToIntArray(uninstalledAppIds));
             }
         } catch (RemoteException e) {
diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java
index 5abc73e..2a91b4f 100644
--- a/services/core/java/com/android/server/input/InputManagerService.java
+++ b/services/core/java/com/android/server/input/InputManagerService.java
@@ -69,11 +69,13 @@
 import android.view.Display;
 import android.view.IInputFilter;
 import android.view.IInputFilterHost;
+import android.view.IInputMonitorHost;
 import android.view.IWindow;
 import android.view.InputApplicationHandle;
 import android.view.InputChannel;
 import android.view.InputDevice;
 import android.view.InputEvent;
+import android.view.InputMonitor;
 import android.view.InputWindowHandle;
 import android.view.KeyEvent;
 import android.view.PointerIcon;
@@ -202,7 +204,10 @@
             int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
     private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
             int displayId);
+    private static native void nativeRegisterInputMonitor(long ptr, InputChannel inputChannel,
+            int displayId, boolean isGestureMonitor);
     private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
+    private static native void nativePilferPointers(long ptr, IBinder token);
     private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
     private static native int nativeInjectInputEvent(long ptr, InputEvent event,
             int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
@@ -489,12 +494,43 @@
         }
 
         InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
-        nativeRegisterInputChannel(mPtr, inputChannels[0], displayId);
+        // Give the output channel a token just for identity purposes.
+        inputChannels[0].setToken(new Binder());
+        nativeRegisterInputMonitor(mPtr, inputChannels[0], displayId, false /*isGestureMonitor*/);
         inputChannels[0].dispose(); // don't need to retain the Java object reference
         return inputChannels[1];
     }
 
     /**
+     * Creates an input monitor that will receive pointer events for the purposes of system-wide
+     * gesture interpretation.
+     *
+     * @param inputChannelName The input channel name.
+     * @param displayId Target display id.
+     * @return The input channel.
+     */
+    @Override // Binder call
+    public InputMonitor monitorGestureInput(String inputChannelName, int displayId) {
+        if (!checkCallingPermission(android.Manifest.permission.MONITOR_INPUT,
+                "monitorInputRegion()")) {
+            throw new SecurityException("Requires MONITOR_INPUT permission");
+        }
+
+        Objects.requireNonNull(inputChannelName, "inputChannelName must not be null.");
+
+        if (displayId < Display.DEFAULT_DISPLAY) {
+            throw new IllegalArgumentException("displayId must >= 0.");
+        }
+
+
+        InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
+        InputMonitorHost host = new InputMonitorHost(inputChannels[0]);
+        inputChannels[0].setToken(host.asBinder());
+        nativeRegisterInputMonitor(mPtr, inputChannels[0], displayId, true /*isGestureMonitor*/);
+        return new InputMonitor(inputChannelName, inputChannels[1], host);
+    }
+
+    /**
      * Registers an input channel so that it can be used as an input event target.
      * @param inputChannel The input channel to register.
      * @param inputWindowHandle The handle of the input window associated with the
@@ -2096,6 +2132,28 @@
         }
     }
 
+    /**
+     * Interface for the system to handle request from InputMonitors.
+     */
+    private final class InputMonitorHost extends IInputMonitorHost.Stub {
+        private final InputChannel mInputChannel;
+
+        InputMonitorHost(InputChannel channel) {
+            mInputChannel = channel;
+        }
+
+        @Override
+        public void pilferPointers() {
+            nativePilferPointers(mPtr, asBinder());
+        }
+
+        @Override
+        public void dispose() {
+            nativeUnregisterInputChannel(mPtr, mInputChannel);
+            mInputChannel.dispose();
+        }
+    }
+
     private static final class KeyboardLayoutDescriptor {
         public String packageName;
         public String receiverName;
diff --git a/services/core/java/com/android/server/locksettings/LockSettingsService.java b/services/core/java/com/android/server/locksettings/LockSettingsService.java
index 3e134b2..da836c2 100644
--- a/services/core/java/com/android/server/locksettings/LockSettingsService.java
+++ b/services/core/java/com/android/server/locksettings/LockSettingsService.java
@@ -94,6 +94,7 @@
 import android.service.gatekeeper.IGateKeeperService;
 import android.text.TextUtils;
 import android.util.ArrayMap;
+import android.util.ArraySet;
 import android.util.EventLog;
 import android.util.Log;
 import android.util.Slog;
@@ -141,6 +142,7 @@
 import java.util.List;
 import java.util.Map;
 import java.util.NoSuchElementException;
+import java.util.Set;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
@@ -324,7 +326,7 @@
             Arrays.fill(newPasswordChars, '\u0000');
             final int quality = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
             setLockCredentialInternal(newPassword, CREDENTIAL_TYPE_PASSWORD, managedUserPassword,
-                    quality, managedUserId, false);
+                    quality, managedUserId, false, /* isLockTiedToParent= */ true);
             // We store a private credential for the managed user that's unlocked by the primary
             // account holder's credential. As such, the user will never be prompted to enter this
             // password directly, so we always store a password.
@@ -1303,13 +1305,13 @@
                         setLockCredentialInternal(null, CREDENTIAL_TYPE_NONE,
                                 profilePasswordMap.get(managedUserId),
                                 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId,
-                                false);
+                                false, /* isLockTiedToParent= */ true);
                     } else {
                         Slog.wtf(TAG, "clear tied profile challenges, but no password supplied.");
                         // Supplying null here would lead to untrusted credential change
                         setLockCredentialInternal(null, CREDENTIAL_TYPE_NONE, null,
                                 DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, managedUserId,
-                                true);
+                                true, /* isLockTiedToParent= */ true);
                     }
                     mStorage.removeChildProfileLock(managedUserId);
                     removeKeystoreProfileKey(managedUserId);
@@ -1328,6 +1330,67 @@
                 && mLockPatternUtils.isSeparateProfileChallengeEnabled(userId);
     }
 
+    /**
+     * Send credentials for user {@code userId} to {@link RecoverableKeyStoreManager} during an
+     * unlock operation.
+     */
+    private void sendCredentialsOnUnlockIfRequired(
+            int credentialType, @NonNull byte[] credential, int userId) {
+        // Don't send credentials during the factory reset protection flow.
+        if (userId == USER_FRP) {
+            return;
+        }
+
+        // A profile with a unified lock screen stores a randomly generated credential, so skip it.
+        // Its parent will send credentials for the profile, as it stores the unified lock
+        // credential.
+        if (isManagedProfileWithUnifiedLock(userId)) {
+            return;
+        }
+
+        // Send credentials for the user and any child profiles that share its lock screen.
+        for (int profileId : getProfilesWithSameLockScreen(userId)) {
+            mRecoverableKeyStoreManager.lockScreenSecretAvailable(
+                    credentialType, credential, profileId);
+        }
+    }
+
+    /**
+     * Send credentials for user {@code userId} to {@link RecoverableKeyStoreManager} when its
+     * credentials are set/changed.
+     */
+    private void sendCredentialsOnChangeIfRequired(
+            int credentialType, byte[] credential, int userId, boolean isLockTiedToParent) {
+        // A profile whose lock screen is being tied to its parent's will either have a randomly
+        // generated credential (creation) or null (removal). We rely on the parent to send its
+        // credentials for the profile in both cases as it stores the unified lock credential.
+        if (isLockTiedToParent) {
+            return;
+        }
+
+        // Send credentials for the user and any child profiles that share its lock screen.
+        for (int profileId : getProfilesWithSameLockScreen(userId)) {
+            mRecoverableKeyStoreManager.lockScreenSecretChanged(
+                    credentialType, credential, profileId);
+        }
+    }
+
+    /**
+     * Returns all profiles of {@code userId}, including itself, that have the same lock screen
+     * challenge.
+     */
+    private Set<Integer> getProfilesWithSameLockScreen(int userId) {
+        Set<Integer> profiles = new ArraySet<>();
+        for (UserInfo profile : mUserManager.getProfiles(userId)) {
+            if (profile.id == userId
+                    || (profile.profileGroupId == userId
+                            && isManagedProfileWithUnifiedLock(profile.id))) {
+                profiles.add(profile.id);
+            }
+        }
+        return profiles;
+    }
+
     // This method should be called by LockPatternUtil only, all internal methods in this class
     // should call setLockCredentialInternal.
     @Override
@@ -1342,16 +1405,24 @@
         checkWritePermission(userId);
         synchronized (mSeparateChallengeLock) {
             setLockCredentialInternal(credential, type, savedCredential, requestedQuality, userId,
-                    allowUntrustedChange);
+                    allowUntrustedChange, /* isLockTiedToParent= */ false);
             setSeparateProfileChallengeEnabledLocked(userId, true, null);
             notifyPasswordChanged(userId);
         }
+        if (mUserManager.getUserInfo(userId).isManagedProfile()) {
+            // Make sure the profile doesn't get locked straight after setting work challenge.
+            setDeviceUnlockedForUser(userId);
+        }
         notifySeparateProfileChallengeChanged(userId);
     }
 
+    /**
+     * @param isLockTiedToParent is {@code true} if {@code userId} is a profile and its new
+     *     credentials are being tied to its parent's credentials.
+     */
     private void setLockCredentialInternal(byte[] credential, @CredentialType int credentialType,
-            byte[] savedCredential, int requestedQuality, int userId,
-            boolean allowUntrustedChange) throws RemoteException {
+            byte[] savedCredential, int requestedQuality, int userId, boolean allowUntrustedChange,
+            boolean isLockTiedToParent) throws RemoteException {
         // Normalize savedCredential and credential such that empty string is always represented
         // as null.
         if (savedCredential == null || savedCredential.length == 0) {
@@ -1363,7 +1434,7 @@
         synchronized (mSpManager) {
             if (isSyntheticPasswordBasedCredentialLocked(userId)) {
                 spBasedSetLockCredentialInternalLocked(credential, credentialType, savedCredential,
-                        requestedQuality, userId, allowUntrustedChange);
+                        requestedQuality, userId, allowUntrustedChange, isLockTiedToParent);
                 return;
             }
         }
@@ -1379,7 +1450,8 @@
             fixateNewestUserKeyAuth(userId);
             synchronizeUnifiedWorkChallengeForProfiles(userId, null);
             notifyActivePasswordMetricsAvailable(CREDENTIAL_TYPE_NONE, null, userId);
-            mRecoverableKeyStoreManager.lockScreenSecretChanged(credentialType, credential, userId);
+            sendCredentialsOnChangeIfRequired(
+                    credentialType, credential, userId, isLockTiedToParent);
             return;
         }
         if (credential == null) {
@@ -1414,7 +1486,7 @@
                 initializeSyntheticPasswordLocked(currentHandle.hash, savedCredential,
                         currentHandle.type, requestedQuality, userId);
                 spBasedSetLockCredentialInternalLocked(credential, credentialType, savedCredential,
-                        requestedQuality, userId, allowUntrustedChange);
+                        requestedQuality, userId, allowUntrustedChange, isLockTiedToParent);
                 return;
             }
         }
@@ -1432,8 +1504,8 @@
             // Refresh the auth token
             doVerifyCredential(credential, credentialType, true, 0, userId, null /* progressCallback */);
             synchronizeUnifiedWorkChallengeForProfiles(userId, null);
-            mRecoverableKeyStoreManager.lockScreenSecretChanged(credentialType, credential,
-                userId);
+            sendCredentialsOnChangeIfRequired(
+                    credentialType, credential, userId, isLockTiedToParent);
         } else {
             throw new RemoteException("Failed to enroll " +
                     (credentialType == CREDENTIAL_TYPE_PASSWORD ? "password" : "pattern"));
@@ -1674,8 +1746,7 @@
         // The user employs synthetic password based credential.
         if (response != null) {
             if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
-                mRecoverableKeyStoreManager.lockScreenSecretAvailable(credentialType, credential,
-                        userId);
+                sendCredentialsOnUnlockIfRequired(credentialType, credential, userId);
             }
             return response;
         }
@@ -1709,7 +1780,8 @@
             mStrongAuth.reportSuccessfulStrongAuthUnlock(userId);
             if (shouldReEnrollBaseZero) {
                 setLockCredentialInternal(credential, storedHash.type, credentialToVerify,
-                        DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, userId, false);
+                        DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, userId, false,
+                        /* isLockTiedToParent= */ false);
             }
         }
 
@@ -1800,12 +1872,12 @@
                         storedHash.type == CREDENTIAL_TYPE_PATTERN
                                 ? DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
                                 : DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC
-                                /* TODO(roosa): keep the same password quality */, userId, false);
+                                /* TODO(roosa): keep the same password quality */,
+                        userId, false, /* isLockTiedToParent= */ false);
                 if (!hasChallenge) {
                     notifyActivePasswordMetricsAvailable(storedHash.type, credential, userId);
                     // Use credentials to create recoverable keystore snapshot.
-                    mRecoverableKeyStoreManager.lockScreenSecretAvailable(
-                            storedHash.type, credential, userId);
+                    sendCredentialsOnUnlockIfRequired(storedHash.type, credential, userId);
                     return VerifyCredentialResponse.OK;
                 }
                 // Fall through to get the auth token. Technically this should never happen,
@@ -1835,9 +1907,7 @@
             unlockUser(userId, response.getPayload(), secretFromCredential(credential));
 
             if (isManagedProfileWithSeparatedLock(userId)) {
-                TrustManager trustManager =
-                        (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
-                trustManager.setDeviceLockedForUser(userId, false);
+                setDeviceUnlockedForUser(userId);
             }
             int reEnrollQuality = storedHash.type == CREDENTIAL_TYPE_PATTERN
                     ? DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
@@ -1845,7 +1915,7 @@
                     /* TODO(roosa): keep the same password quality */;
             if (shouldReEnroll) {
                 setLockCredentialInternal(credential, storedHash.type, credential,
-                        reEnrollQuality, userId, false);
+                        reEnrollQuality, userId, false, /* isLockTiedToParent= */ false);
             } else {
                 // Now that we've cleared of all required GK migration, let's do the final
                 // migration to synthetic password.
@@ -1859,8 +1929,7 @@
                 }
             }
             // Use credentials to create recoverable keystore snapshot.
-            mRecoverableKeyStoreManager.lockScreenSecretAvailable(storedHash.type, credential,
-                userId);
+            sendCredentialsOnUnlockIfRequired(storedHash.type, credential, userId);
 
         } else if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_RETRY) {
             if (response.getTimeout() > 0) {
@@ -2465,9 +2534,7 @@
             activateEscrowTokens(authResult.authToken, userId);
 
             if (isManagedProfileWithSeparatedLock(userId)) {
-                TrustManager trustManager =
-                        (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
-                trustManager.setDeviceLockedForUser(userId, false);
+                setDeviceUnlockedForUser(userId);
             }
             mStrongAuth.reportSuccessfulStrongAuthUnlock(userId);
 
@@ -2481,6 +2548,11 @@
         return response;
     }
 
+    private void setDeviceUnlockedForUser(int userId) {
+        final TrustManager trustManager = mContext.getSystemService(TrustManager.class);
+        trustManager.setDeviceLockedForUser(userId, false);
+    }
+
     /**
      * Change the user's lockscreen password by creating a new SP blob and update the handle, based
      * on an existing authentication token. Even though a new SP blob is created, the underlying
@@ -2549,7 +2621,7 @@
     @GuardedBy("mSpManager")
     private void spBasedSetLockCredentialInternalLocked(byte[] credential, int credentialType,
             byte[] savedCredential, int requestedQuality, int userId,
-            boolean allowUntrustedChange) throws RemoteException {
+            boolean allowUntrustedChange, boolean isLockTiedToParent) throws RemoteException {
         if (DEBUG) Slog.d(TAG, "spBasedSetLockCredentialInternalLocked: user=" + userId);
         if (isManagedProfileWithUnifiedLock(userId)) {
             // get credential from keystore when managed profile has unified lock
@@ -2615,7 +2687,7 @@
             // requestedQuality, userId) instead if we still allow untrusted reset that changes
             // synthetic password. That would invalidate existing escrow tokens though.
         }
-        mRecoverableKeyStoreManager.lockScreenSecretChanged(credentialType, credential, userId);
+        sendCredentialsOnChangeIfRequired(credentialType, credential, userId, isLockTiedToParent);
     }
 
     /**
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index bfab85b..f2e56b5 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -17,6 +17,7 @@
 package com.android.server.notification;
 
 import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
+import static android.app.Notification.CATEGORY_CALL;
 import static android.app.Notification.FLAG_AUTOGROUP_SUMMARY;
 import static android.app.Notification.FLAG_BUBBLE;
 import static android.app.Notification.FLAG_FOREGROUND_SERVICE;
@@ -107,6 +108,7 @@
 import android.app.NotificationManager;
 import android.app.NotificationManager.Policy;
 import android.app.PendingIntent;
+import android.app.Person;
 import android.app.StatusBarManager;
 import android.app.UriGrantsManager;
 import android.app.admin.DeviceAdminInfo;
@@ -4762,11 +4764,36 @@
     /**
      * Updates the flags for this notification to reflect whether it is a bubble or not.
      */
-    private void flagNotificationForBubbles(NotificationRecord r, String pkg, int userId) {
+    private void flagNotificationForBubbles(NotificationRecord r, String pkg, int userId,
+            NotificationRecord oldRecord) {
         Notification notification = r.getNotification();
-        boolean canBubble = mPreferencesHelper.areBubblesAllowed(pkg, userId)
+
+        // Does the app want to bubble & have permission to bubble?
+        boolean canBubble = notification.getBubbleMetadata() != null
+                && mPreferencesHelper.areBubblesAllowed(pkg, userId)
                 && r.getChannel().canBubble();
-        if (notification.getBubbleMetadata() != null && canBubble) {
+
+        // Is the app in the foreground?
+        final boolean appIsForeground =
+                mActivityManager.getPackageImportance(pkg) == IMPORTANCE_FOREGROUND;
+
+        // Is the notification something we'd allow to bubble?
+        // A call with a foreground service + person
+        ArrayList<Person> peopleList = notification.extras != null
+                ? notification.extras.getParcelableArrayList(Notification.EXTRA_PEOPLE_LIST)
+                : null;
+        boolean isForegroundCall = CATEGORY_CALL.equals(notification.category)
+                && (notification.flags & FLAG_FOREGROUND_SERVICE) != 0;
+        // OR message style (which always has a person)
+        Class<? extends Notification.Style> style = notification.getNotificationStyle();
+        boolean isMessageStyle = Notification.MessagingStyle.class.equals(style);
+        boolean notificationAppropriateToBubble = isMessageStyle
+                || (peopleList != null && !peopleList.isEmpty() && isForegroundCall);
+        // OR something that was previously a bubble & still exists
+        boolean bubbleUpdate = oldRecord != null
+                && (oldRecord.getNotification().flags & FLAG_BUBBLE) != 0;
+
+        if (canBubble && (notificationAppropriateToBubble || appIsForeground || bubbleUpdate)) {
             notification.flags |= FLAG_BUBBLE;
         } else {
             notification.flags &= ~FLAG_BUBBLE;
@@ -5129,7 +5156,7 @@
                 final String tag = n.getTag();
 
                 // We need to fix the notification up a little for bubbles
-                flagNotificationForBubbles(r, pkg, callingUid);
+                flagNotificationForBubbles(r, pkg, callingUid, old);
 
                 // Handle grouped notifications and bail out early if we
                 // can to avoid extracting signals.
diff --git a/services/core/java/com/android/server/om/OverlayManagerService.java b/services/core/java/com/android/server/om/OverlayManagerService.java
index 6e98d6e..51d5acc 100644
--- a/services/core/java/com/android/server/om/OverlayManagerService.java
+++ b/services/core/java/com/android/server/om/OverlayManagerService.java
@@ -374,7 +374,7 @@
                     synchronized (mLock) {
                         final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId,
                                 false);
-                        if (pi != null) {
+                        if (pi != null && !pi.applicationInfo.isInstantApp()) {
                             mPackageManager.cachePackageInfo(packageName, userId, pi);
                             if (pi.isOverlayPackage()) {
                                 mImpl.onOverlayPackageAdded(packageName, userId);
@@ -397,7 +397,7 @@
                     synchronized (mLock) {
                         final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId,
                                 false);
-                        if (pi != null) {
+                        if (pi != null && pi.applicationInfo.isInstantApp()) {
                             mPackageManager.cachePackageInfo(packageName, userId, pi);
                             if (pi.isOverlayPackage()) {
                                 mImpl.onOverlayPackageChanged(packageName, userId);
@@ -438,7 +438,7 @@
                     synchronized (mLock) {
                         final PackageInfo pi = mPackageManager.getPackageInfo(packageName, userId,
                                 false);
-                        if (pi != null) {
+                        if (pi != null && !pi.applicationInfo.isInstantApp()) {
                             mPackageManager.cachePackageInfo(packageName, userId, pi);
                             if (pi.isOverlayPackage()) {
                                 mImpl.onOverlayPackageReplaced(packageName, userId);
diff --git a/services/core/java/com/android/server/testharness/TestHarnessModeService.java b/services/core/java/com/android/server/testharness/TestHarnessModeService.java
index 9f9b797..4f11887 100644
--- a/services/core/java/com/android/server/testharness/TestHarnessModeService.java
+++ b/services/core/java/com/android/server/testharness/TestHarnessModeService.java
@@ -71,7 +71,6 @@
     private static final String TEST_HARNESS_MODE_PROPERTY = "persist.sys.test_harness";
 
     private PersistentDataBlockManagerInternal mPersistentDataBlockManagerInternal;
-    private boolean mShouldSetUpTestHarnessMode;
 
     public TestHarnessModeService(Context context) {
         super(context);
@@ -89,9 +88,8 @@
                 setUpTestHarnessMode();
                 break;
             case PHASE_BOOT_COMPLETED:
-                disableAutoSync();
-                configureSettings();
-                showNotification();
+                completeTestHarnessModeSetup();
+                showNotificationIfEnabled();
                 break;
         }
         super.onBootPhase(phase);
@@ -104,47 +102,45 @@
             // There's no data to apply, so leave it as-is.
             return;
         }
-        PersistentData persistentData;
-        try {
-            persistentData = PersistentData.fromBytes(testHarnessModeData);
-        } catch (SetUpTestHarnessModeException e) {
-            Slog.e(TAG, "Failed to set up Test Harness Mode. Bad data.", e);
-            return;
-        } finally {
-            // Clear out the Test Harness Mode data. It's now in memory if successful or we should
-            // skip setting up.
-            getPersistentDataBlock().clearTestHarnessModeData();
-        }
-        mShouldSetUpTestHarnessMode = true;
-        setUpAdb(persistentData);
+        // If there is data, we should set the device as provisioned, so that we skip the setup
+        // wizard.
         setDeviceProvisioned();
+        SystemProperties.set(TEST_HARNESS_MODE_PROPERTY, "1");
     }
 
-    private void setUpAdb(PersistentData persistentData) {
-        ContentResolver cr = getContext().getContentResolver();
-
-        // Disable the TTL for ADB keys before enabling ADB
-        Settings.Global.putLong(cr, Settings.Global.ADB_ALLOWED_CONNECTION_TIME, 0);
-
-        SystemProperties.set(TEST_HARNESS_MODE_PROPERTY, "1");
-        writeAdbKeysFile(persistentData);
+    private void completeTestHarnessModeSetup() {
+        Slog.d(TAG, "Completing Test Harness Mode setup.");
+        byte[] testHarnessModeData = getPersistentDataBlock().getTestHarnessModeData();
+        if (testHarnessModeData == null || testHarnessModeData.length == 0) {
+            // There's no data to apply, so leave it as-is.
+            return;
+        }
+        try {
+            setUpAdbFiles(PersistentData.fromBytes(testHarnessModeData));
+            disableAutoSync();
+            configureSettings();
+        } catch (SetUpTestHarnessModeException e) {
+            Slog.e(TAG, "Failed to set up Test Harness Mode. Bad data.", e);
+        } finally {
+            // Clear out the Test Harness Mode data so that we don't repeat the setup. If it failed
+            // to set up, then retrying without enabling Test Harness Mode should allow it to boot.
+            // If we succeeded setting up, we shouldn't be re-applying the THM steps every boot
+            // anyway.
+            getPersistentDataBlock().clearTestHarnessModeData();
+        }
     }
 
     private void disableAutoSync() {
-        if (!mShouldSetUpTestHarnessMode) {
-            return;
-        }
         UserInfo primaryUser = UserManager.get(getContext()).getPrimaryUser();
         ContentResolver
             .setMasterSyncAutomaticallyAsUser(false, primaryUser.getUserHandle().getIdentifier());
     }
 
     private void configureSettings() {
-        if (!mShouldSetUpTestHarnessMode) {
-            return;
-        }
         ContentResolver cr = getContext().getContentResolver();
 
+        // Disable the TTL for ADB keys before enabling ADB
+        Settings.Global.putLong(cr, Settings.Global.ADB_ALLOWED_CONNECTION_TIME, 0);
         Settings.Global.putInt(cr, Settings.Global.ADB_ENABLED, 1);
         Settings.Global.putInt(cr, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 1);
         Settings.Global.putInt(cr, Settings.Global.PACKAGE_VERIFIER_ENABLE, 0);
@@ -155,7 +151,7 @@
         Settings.Global.putInt(cr, Settings.Global.OTA_DISABLE_AUTOMATIC_UPDATE, 1);
     }
 
-    private void writeAdbKeysFile(PersistentData persistentData) {
+    private void setUpAdbFiles(PersistentData persistentData) {
         AdbManagerInternal adbManager = LocalServices.getService(AdbManagerInternal.class);
 
         writeBytesToFile(persistentData.mAdbKeys, adbManager.getAdbKeysFile().toPath());
@@ -189,7 +185,7 @@
                 UserHandle.USER_CURRENT);
     }
 
-    private void showNotification() {
+    private void showNotificationIfEnabled() {
         if (!SystemProperties.getBoolean(TEST_HARNESS_MODE_PROPERTY, false)) {
             return;
         }
diff --git a/services/core/jni/com_android_server_input_InputManagerService.cpp b/services/core/jni/com_android_server_input_InputManagerService.cpp
index 3d6c868..204a1ea 100644
--- a/services/core/jni/com_android_server_input_InputManagerService.cpp
+++ b/services/core/jni/com_android_server_input_InputManagerService.cpp
@@ -47,6 +47,7 @@
 
 #include <input/PointerController.h>
 #include <input/SpriteController.h>
+#include <ui/Region.h>
 
 #include <inputflinger/InputManager.h>
 
@@ -137,8 +138,6 @@
     jmethodID getAffineTransform;
 } gTouchCalibrationClassInfo;
 
-
-
 // --- Global functions ---
 
 template<typename T>
@@ -188,7 +187,6 @@
     return result;
 }
 
-
 // --- NativeInputManager ---
 
 class NativeInputManager : public virtual RefBase,
@@ -207,8 +205,12 @@
 
     void setDisplayViewports(JNIEnv* env, jobjectArray viewportObjArray);
 
-    status_t registerInputChannel(JNIEnv* env, const sp<InputChannel>& inputChannel, int32_t displayId);
+    status_t registerInputChannel(JNIEnv* env, const sp<InputChannel>& inputChannel,
+            int32_t displayId);
+    status_t registerInputMonitor(JNIEnv* env, const sp<InputChannel>& inputChannel,
+            int32_t displayId, bool isGestureMonitor);
     status_t unregisterInputChannel(JNIEnv* env, const sp<InputChannel>& inputChannel);
+    status_t pilferPointers(const sp<IBinder>& token);
 
     void setInputWindows(JNIEnv* env, jobjectArray windowHandleObjArray, int32_t displayId);
     void setFocusedApplication(JNIEnv* env, int32_t displayId, jobject applicationHandleObj);
@@ -443,12 +445,24 @@
             inputChannel, displayId);
 }
 
+status_t NativeInputManager::registerInputMonitor(JNIEnv* /* env */,
+        const sp<InputChannel>& inputChannel, int32_t displayId, bool isGestureMonitor) {
+    ATRACE_CALL();
+    return mInputManager->getDispatcher()->registerInputMonitor(
+            inputChannel, displayId, isGestureMonitor);
+}
+
 status_t NativeInputManager::unregisterInputChannel(JNIEnv* /* env */,
         const sp<InputChannel>& inputChannel) {
     ATRACE_CALL();
     return mInputManager->getDispatcher()->unregisterInputChannel(inputChannel);
 }
 
+status_t NativeInputManager::pilferPointers(const sp<IBinder>& token) {
+    ATRACE_CALL();
+    return mInputManager->getDispatcher()->pilferPointers(token);
+}
+
 void NativeInputManager::getReaderConfiguration(InputReaderConfiguration* outConfig) {
     ATRACE_CALL();
     JNIEnv* env = jniEnv();
@@ -1396,7 +1410,6 @@
         throwInputChannelNotInitialized(env);
         return;
     }
-    bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
 
     status_t status = im->registerInputChannel(env, inputChannel, displayId);
 
@@ -1407,10 +1420,33 @@
         return;
     }
 
-    // If inputWindowHandle is null and displayId >= 0, treat inputChannel as monitor.
-    if (!monitor) {
-        android_view_InputChannel_setDisposeCallback(env, inputChannelObj,
-                handleInputChannelDisposed, im);
+    android_view_InputChannel_setDisposeCallback(env, inputChannelObj,
+            handleInputChannelDisposed, im);
+}
+
+static void nativeRegisterInputMonitor(JNIEnv* env, jclass /* clazz */,
+        jlong ptr, jobject inputChannelObj, jint displayId, jboolean isGestureMonitor) {
+    NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
+
+    sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,
+            inputChannelObj);
+    if (inputChannel == nullptr) {
+        throwInputChannelNotInitialized(env);
+        return;
+    }
+
+    if (displayId == ADISPLAY_ID_NONE) {
+        std::string message = "InputChannel used as a monitor must be associated with a display";
+        jniThrowRuntimeException(env, message.c_str());
+        return;
+    }
+
+    status_t status = im->registerInputMonitor(env, inputChannel, displayId, isGestureMonitor);
+
+    if (status) {
+        std::string message = StringPrintf("Failed to register input channel.  status=%d", status);
+        jniThrowRuntimeException(env, message.c_str());
+        return;
     }
 }
 
@@ -1435,6 +1471,13 @@
     }
 }
 
+static void nativePilferPointers(JNIEnv* env, jclass /* clazz */, jlong ptr, jobject tokenObj) {
+    NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
+    sp<IBinder> token = ibinderForJavaObject(env, tokenObj);
+    im->pilferPointers(token);
+}
+
+
 static void nativeSetInputFilterEnabled(JNIEnv* /* env */, jclass /* clazz */,
         jlong ptr, jboolean enabled) {
     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
@@ -1697,8 +1740,13 @@
     { "nativeRegisterInputChannel",
             "(JLandroid/view/InputChannel;I)V",
             (void*) nativeRegisterInputChannel },
+    { "nativeRegisterInputMonitor",
+            "(JLandroid/view/InputChannel;IZ)V",
+            (void*) nativeRegisterInputMonitor},
     { "nativeUnregisterInputChannel", "(JLandroid/view/InputChannel;)V",
             (void*) nativeUnregisterInputChannel },
+    { "nativePilferPointers", "(JLandroid/os/IBinder;)V",
+            (void*) nativePilferPointers },
     { "nativeSetInputFilterEnabled", "(JZ)V",
             (void*) nativeSetInputFilterEnabled },
     { "nativeInjectInputEvent", "(JLandroid/view/InputEvent;IIIII)I",
@@ -1792,7 +1840,7 @@
 
     GET_METHOD_ID(gServiceClassInfo.notifyInputChannelBroken, clazz,
             "notifyInputChannelBroken", "(Landroid/os/IBinder;)V");
-    
+
     GET_METHOD_ID(gServiceClassInfo.notifyFocusChanged, clazz,
             "notifyFocusChanged", "(Landroid/os/IBinder;Landroid/os/IBinder;)V");
 
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java b/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java
index 2fbeebd..09e20e0 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/BaseLockSettingsServiceTests.java
@@ -46,6 +46,7 @@
 import com.android.internal.widget.LockPatternUtils;
 import com.android.internal.widget.LockSettingsInternal;
 import com.android.server.LocalServices;
+import com.android.server.locksettings.recoverablekeystore.RecoverableKeyStoreManager;
 import com.android.server.wm.WindowManagerInternal;
 
 import org.mockito.invocation.InvocationOnMock;
@@ -89,6 +90,7 @@
     WindowManagerInternal mMockWindowManager;
     FakeGsiService mGsiService;
     PasswordSlotManagerTestable mPasswordSlotManager;
+    RecoverableKeyStoreManager mRecoverableKeyStoreManager;
     protected boolean mHasSecureLockScreen;
 
     @Override
@@ -105,6 +107,7 @@
         mMockWindowManager = mock(WindowManagerInternal.class);
         mGsiService = new FakeGsiService();
         mPasswordSlotManager = new PasswordSlotManagerTestable();
+        mRecoverableKeyStoreManager = mock(RecoverableKeyStoreManager.class);
 
         LocalServices.removeServiceForTest(LockSettingsInternal.class);
         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
@@ -141,12 +144,14 @@
         mAuthSecretService = mock(IAuthSecret.class);
         mService = new LockSettingsServiceTestable(mContext, mLockPatternUtils, mStorage,
                 mGateKeeperService, mKeyStore, setUpStorageManagerMock(), mActivityManager,
-                mSpManager, mAuthSecretService, mGsiService);
+                mSpManager, mAuthSecretService, mGsiService, mRecoverableKeyStoreManager);
         when(mUserManager.getUserInfo(eq(PRIMARY_USER_ID))).thenReturn(PRIMARY_USER_INFO);
         mPrimaryUserProfiles.add(PRIMARY_USER_INFO);
         installChildProfile(MANAGED_PROFILE_USER_ID);
         installAndTurnOffChildProfile(TURNED_OFF_PROFILE_USER_ID);
-        when(mUserManager.getProfiles(eq(PRIMARY_USER_ID))).thenReturn(mPrimaryUserProfiles);
+        for (UserInfo profile : mPrimaryUserProfiles) {
+            when(mUserManager.getProfiles(eq(profile.id))).thenReturn(mPrimaryUserProfiles);
+        }
         when(mUserManager.getUserInfo(eq(SECONDARY_USER_ID))).thenReturn(SECONDARY_USER_INFO);
 
         final ArrayList<UserInfo> allUsers = new ArrayList<>(mPrimaryUserProfiles);
@@ -173,6 +178,7 @@
     private UserInfo installChildProfile(int profileId) {
         final UserInfo userInfo = new UserInfo(
             profileId, null, null, UserInfo.FLAG_INITIALIZED | UserInfo.FLAG_MANAGED_PROFILE);
+        userInfo.profileGroupId = PRIMARY_USER_ID;
         mPrimaryUserProfiles.add(userInfo);
         when(mUserManager.getUserInfo(eq(profileId))).thenReturn(userInfo);
         when(mUserManager.getProfileParent(eq(profileId))).thenReturn(PRIMARY_USER_INFO);
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
index f4632db..10fb3ba 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTestable.java
@@ -30,6 +30,7 @@
 import android.security.keystore.KeyPermanentlyInvalidatedException;
 
 import com.android.internal.widget.LockPatternUtils;
+import com.android.server.locksettings.recoverablekeystore.RecoverableKeyStoreManager;
 
 import java.io.FileNotFoundException;
 
@@ -45,11 +46,13 @@
         private SyntheticPasswordManager mSpManager;
         private IAuthSecret mAuthSecretService;
         private FakeGsiService mGsiService;
+        private RecoverableKeyStoreManager mRecoverableKeyStoreManager;
 
         public MockInjector(Context context, LockSettingsStorage storage, KeyStore keyStore,
                 IActivityManager activityManager, LockPatternUtils lockPatternUtils,
                 IStorageManager storageManager, SyntheticPasswordManager spManager,
-                IAuthSecret authSecretService, FakeGsiService gsiService) {
+                IAuthSecret authSecretService, FakeGsiService gsiService,
+                RecoverableKeyStoreManager recoverableKeyStoreManager) {
             super(context);
             mLockSettingsStorage = storage;
             mKeyStore = keyStore;
@@ -58,6 +61,7 @@
             mStorageManager = storageManager;
             mSpManager = spManager;
             mGsiService = gsiService;
+            mRecoverableKeyStoreManager = recoverableKeyStoreManager;
         }
 
         @Override
@@ -119,15 +123,21 @@
         public boolean isGsiRunning() {
             return mGsiService.isGsiRunning();
         }
+
+        @Override
+        public RecoverableKeyStoreManager getRecoverableKeyStoreManager(KeyStore keyStore) {
+            return mRecoverableKeyStoreManager;
+        }
     }
 
     protected LockSettingsServiceTestable(Context context, LockPatternUtils lockPatternUtils,
             LockSettingsStorage storage, FakeGateKeeperService gatekeeper, KeyStore keystore,
             IStorageManager storageManager, IActivityManager mActivityManager,
             SyntheticPasswordManager spManager, IAuthSecret authSecretService,
-            FakeGsiService gsiService) {
+            FakeGsiService gsiService, RecoverableKeyStoreManager recoverableKeyStoreManager) {
         super(new MockInjector(context, storage, keystore, mActivityManager, lockPatternUtils,
-                storageManager, spManager, authSecretService, gsiService));
+                storageManager, spManager, authSecretService, gsiService,
+                recoverableKeyStoreManager));
         mGateKeeperService = gatekeeper;
         mAuthSecretService = authSecretService;
     }
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
index 7ebc745..67d6eda 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/LockSettingsServiceTests.java
@@ -25,6 +25,13 @@
 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PASSWORD;
 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PATTERN;
 
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+
 import android.os.RemoteException;
 import android.platform.test.annotations.Presubmit;
 import android.service.gatekeeper.GateKeeperResponse;
@@ -211,6 +218,222 @@
         assertEquals(profileSid, mGateKeeperService.getSecureUserId(MANAGED_PROFILE_USER_ID));
     }
 
+    public void testSetLockCredential_forPrimaryUser_sendsCredentials() throws Exception {
+        final byte[] password = "password".getBytes();
+
+        mService.setLockCredential(
+                password,
+                CREDENTIAL_TYPE_PASSWORD,
+                null,
+                PASSWORD_QUALITY_ALPHABETIC,
+                PRIMARY_USER_ID,
+                false);
+
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretChanged(CREDENTIAL_TYPE_PASSWORD, password, PRIMARY_USER_ID);
+    }
+
+    public void testSetLockCredential_forProfileWithSeparateChallenge_sendsCredentials()
+            throws Exception {
+        final byte[] pattern = "12345".getBytes();
+
+        mService.setLockCredential(
+                pattern,
+                CREDENTIAL_TYPE_PATTERN,
+                null,
+                PASSWORD_QUALITY_SOMETHING,
+                MANAGED_PROFILE_USER_ID,
+                false);
+
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretChanged(CREDENTIAL_TYPE_PATTERN, pattern, MANAGED_PROFILE_USER_ID);
+    }
+
+    public void testSetLockCredential_forProfileWithSeparateChallenge_updatesCredentials()
+            throws Exception {
+        final String oldCredential = "12345";
+        final byte[] newCredential = "newPassword".getBytes();
+        initializeStorageWithCredential(
+                MANAGED_PROFILE_USER_ID,
+                oldCredential,
+                CREDENTIAL_TYPE_PATTERN,
+                PASSWORD_QUALITY_SOMETHING);
+
+        mService.setLockCredential(
+                newCredential,
+                CREDENTIAL_TYPE_PASSWORD,
+                oldCredential.getBytes(),
+                PASSWORD_QUALITY_ALPHABETIC,
+                MANAGED_PROFILE_USER_ID,
+                false);
+
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretChanged(
+                        CREDENTIAL_TYPE_PASSWORD, newCredential, MANAGED_PROFILE_USER_ID);
+    }
+
+    public void testSetLockCredential_forProfileWithUnifiedChallenge_doesNotSendRandomCredential()
+            throws Exception {
+        mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
+
+        mService.setLockCredential(
+                "12345".getBytes(),
+                CREDENTIAL_TYPE_PATTERN,
+                null,
+                PASSWORD_QUALITY_SOMETHING,
+                PRIMARY_USER_ID,
+                false);
+
+        verify(mRecoverableKeyStoreManager, never())
+                .lockScreenSecretChanged(
+                        eq(CREDENTIAL_TYPE_PASSWORD), any(), eq(MANAGED_PROFILE_USER_ID));
+    }
+
+    public void
+            testSetLockCredential_forPrimaryUserWithUnifiedChallengeProfile_updatesBothCredentials()
+                    throws Exception {
+        final String oldCredential = "oldPassword";
+        final byte[] newCredential = "newPassword".getBytes();
+        initializeStorageWithCredential(
+                PRIMARY_USER_ID, oldCredential, CREDENTIAL_TYPE_PASSWORD, 1234);
+        mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
+
+        mService.setLockCredential(
+                newCredential,
+                CREDENTIAL_TYPE_PASSWORD,
+                oldCredential.getBytes(),
+                PASSWORD_QUALITY_ALPHABETIC,
+                PRIMARY_USER_ID,
+                false);
+
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretChanged(CREDENTIAL_TYPE_PASSWORD, newCredential, PRIMARY_USER_ID);
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretChanged(
+                        CREDENTIAL_TYPE_PASSWORD, newCredential, MANAGED_PROFILE_USER_ID);
+    }
+
+    public void
+            testSetLockCredential_forPrimaryUserWithUnifiedChallengeProfile_removesBothCredentials()
+                    throws Exception {
+        final String oldCredential = "oldPassword";
+        initializeStorageWithCredential(
+                PRIMARY_USER_ID, oldCredential, CREDENTIAL_TYPE_PASSWORD, 1234);
+        mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
+
+        mService.setLockCredential(
+                null,
+                CREDENTIAL_TYPE_NONE,
+                oldCredential.getBytes(),
+                PASSWORD_QUALITY_UNSPECIFIED,
+                PRIMARY_USER_ID,
+                false);
+
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretChanged(CREDENTIAL_TYPE_NONE, null, PRIMARY_USER_ID);
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretChanged(CREDENTIAL_TYPE_NONE, null, MANAGED_PROFILE_USER_ID);
+    }
+
+    public void testSetLockCredential_forUnifiedToSeparateChallengeProfile_sendsNewCredentials()
+            throws Exception {
+        final String parentPassword = "parentPassword";
+        final byte[] profilePassword = "profilePassword".getBytes();
+        initializeStorageWithCredential(
+                PRIMARY_USER_ID, parentPassword, CREDENTIAL_TYPE_PASSWORD, 1234);
+        mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
+
+        mService.setLockCredential(
+                profilePassword,
+                CREDENTIAL_TYPE_PASSWORD,
+                null,
+                PASSWORD_QUALITY_ALPHABETIC,
+                MANAGED_PROFILE_USER_ID,
+                false);
+
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretChanged(
+                        CREDENTIAL_TYPE_PASSWORD, profilePassword, MANAGED_PROFILE_USER_ID);
+    }
+
+    public void
+            testSetLockCredential_forSeparateToUnifiedChallengeProfile_doesNotSendRandomCredential()
+                    throws Exception {
+        final String parentPassword = "parentPassword";
+        final String profilePassword = "12345";
+        initializeStorageWithCredential(
+                PRIMARY_USER_ID, parentPassword, CREDENTIAL_TYPE_PASSWORD, 1234);
+        // Create and verify separate profile credentials.
+        testCreateCredential(
+                MANAGED_PROFILE_USER_ID,
+                profilePassword,
+                CREDENTIAL_TYPE_PATTERN,
+                PASSWORD_QUALITY_SOMETHING);
+
+        mService.setSeparateProfileChallengeEnabled(
+                MANAGED_PROFILE_USER_ID, false, profilePassword.getBytes());
+
+        // Called once for setting the initial separate profile credentials and not again during
+        // unification.
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretChanged(anyInt(), any(), eq(MANAGED_PROFILE_USER_ID));
+    }
+
+    public void testVerifyCredential_forPrimaryUser_sendsCredentials() throws Exception {
+        final String password = "password";
+        initializeStorageWithCredential(PRIMARY_USER_ID, password, CREDENTIAL_TYPE_PASSWORD, 1234);
+        reset(mRecoverableKeyStoreManager);
+
+        mService.verifyCredential(
+                password.getBytes(), CREDENTIAL_TYPE_PASSWORD, 1, PRIMARY_USER_ID);
+
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretAvailable(
+                        CREDENTIAL_TYPE_PASSWORD, password.getBytes(), PRIMARY_USER_ID);
+    }
+
+    public void testVerifyCredential_forProfileWithSeparateChallenge_sendsCredentials()
+            throws Exception {
+        final byte[] pattern = "12345".getBytes();
+        mService.setLockCredential(
+                pattern,
+                CREDENTIAL_TYPE_PATTERN,
+                null,
+                PASSWORD_QUALITY_SOMETHING,
+                MANAGED_PROFILE_USER_ID,
+                false);
+        reset(mRecoverableKeyStoreManager);
+
+        mService.verifyCredential(pattern, CREDENTIAL_TYPE_PATTERN, 1, MANAGED_PROFILE_USER_ID);
+
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretAvailable(
+                        CREDENTIAL_TYPE_PATTERN, pattern, MANAGED_PROFILE_USER_ID);
+    }
+
+    public void
+            testVerifyCredential_forPrimaryUserWithUnifiedChallengeProfile_sendsCredentialsForBoth()
+                    throws Exception {
+        final String pattern = "12345";
+        initializeStorageWithCredential(PRIMARY_USER_ID, pattern, CREDENTIAL_TYPE_PATTERN, 1234);
+        mService.setSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID, false, null);
+        reset(mRecoverableKeyStoreManager);
+
+        mService.verifyCredential(pattern.getBytes(), CREDENTIAL_TYPE_PATTERN, 1, PRIMARY_USER_ID);
+
+        // Parent sends its credentials for both the parent and profile.
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretAvailable(
+                        CREDENTIAL_TYPE_PATTERN, pattern.getBytes(), PRIMARY_USER_ID);
+        verify(mRecoverableKeyStoreManager)
+                .lockScreenSecretAvailable(
+                        CREDENTIAL_TYPE_PATTERN, pattern.getBytes(), MANAGED_PROFILE_USER_ID);
+        // Profile doesn't send its own random credentials.
+        verify(mRecoverableKeyStoreManager, never())
+                .lockScreenSecretAvailable(
+                        eq(CREDENTIAL_TYPE_PASSWORD), any(), eq(MANAGED_PROFILE_USER_ID));
+    }
+
     private void testCreateCredential(int userId, String credential, int type, int quality)
             throws RemoteException {
         mService.setLockCredential(credential.getBytes(), type, null, quality,
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/RecoverableKeyStoreManagerTest.java b/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/RecoverableKeyStoreManagerTest.java
index 5bab65c..6890017 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/RecoverableKeyStoreManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/recoverablekeystore/RecoverableKeyStoreManagerTest.java
@@ -58,6 +58,7 @@
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
 
+import com.android.internal.widget.LockPatternUtils;
 import com.android.server.locksettings.recoverablekeystore.storage.ApplicationKeyStorage;
 import com.android.server.locksettings.recoverablekeystore.storage.CleanupManager;
 import com.android.server.locksettings.recoverablekeystore.storage.RecoverableKeyStoreDb;
@@ -83,7 +84,7 @@
 import java.util.ArrayList;
 import java.util.Map;
 import java.util.Random;
-import java.util.concurrent.Executors;
+import java.util.concurrent.ExecutorService;
 
 import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
@@ -156,6 +157,7 @@
     @Mock private PlatformKeyManager mPlatformKeyManager;
     @Mock private ApplicationKeyStorage mApplicationKeyStorage;
     @Mock private CleanupManager mCleanupManager;
+    @Mock private ExecutorService mExecutorService;
     @Spy private TestOnlyInsecureCertificateHelper mTestOnlyInsecureCertificateHelper;
 
     private RecoverableKeyStoreDb mRecoverableKeyStoreDb;
@@ -188,7 +190,7 @@
                 mMockContext,
                 mRecoverableKeyStoreDb,
                 mRecoverySessionStorage,
-                Executors.newSingleThreadExecutor(),
+                mExecutorService,
                 mRecoverySnapshotStorage,
                 mMockListenersStorage,
                 mPlatformKeyManager,
@@ -1246,6 +1248,24 @@
         }
     }
 
+    @Test
+    public void lockScreenSecretAvailable_syncsKeysForUser() throws Exception {
+        mRecoverableKeyStoreManager.lockScreenSecretAvailable(
+                LockPatternUtils.CREDENTIAL_TYPE_PATTERN, "password".getBytes(), 11);
+
+        verify(mExecutorService).execute(any());
+    }
+
+    @Test
+    public void lockScreenSecretChanged_syncsKeysForUser() throws Exception {
+        mRecoverableKeyStoreManager.lockScreenSecretChanged(
+                LockPatternUtils.CREDENTIAL_TYPE_PATTERN,
+                "password".getBytes(),
+                11);
+
+        verify(mExecutorService).execute(any());
+    }
+
     private static byte[] encryptedApplicationKey(
             SecretKey recoveryKey, byte[] applicationKey) throws Exception {
         return KeySyncUtils.encryptKeysWithRecoveryKey(recoveryKey, ImmutableMap.of(
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
index 6f1bd87..ca7a71e 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -18,6 +18,8 @@
 
 import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
 import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_GONE;
+import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
+import static android.app.Notification.CATEGORY_CALL;
 import static android.app.Notification.FLAG_BUBBLE;
 import static android.app.Notification.FLAG_FOREGROUND_SERVICE;
 import static android.app.NotificationManager.EXTRA_BLOCKED_STATE;
@@ -81,6 +83,7 @@
 import android.app.NotificationChannelGroup;
 import android.app.NotificationManager;
 import android.app.PendingIntent;
+import android.app.Person;
 import android.app.admin.DevicePolicyManagerInternal;
 import android.app.usage.UsageStatsManagerInternal;
 import android.companion.ICompanionDeviceManager;
@@ -103,6 +106,7 @@
 import android.os.IBinder;
 import android.os.Process;
 import android.os.RemoteException;
+import android.os.SystemClock;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.provider.DeviceConfig;
@@ -433,6 +437,11 @@
 
     private NotificationRecord generateNotificationRecord(NotificationChannel channel,
             Notification.TvExtender extender) {
+        return generateNotificationRecord(channel, extender, false /* isBubble */);
+    }
+
+    private NotificationRecord generateNotificationRecord(NotificationChannel channel,
+            Notification.TvExtender extender, boolean isBubble) {
         if (channel == null) {
             channel = mTestNotificationChannel;
         }
@@ -442,6 +451,9 @@
         if (extender != null) {
             nb.extend(extender);
         }
+        if (isBubble) {
+            nb.setBubbleMetadata(getBasicBubbleMetadataBuilder().build());
+        }
         StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, "tag", mUid, 0,
                 nb.build(), new UserHandle(mUid), null, 0);
         return new NotificationRecord(mContext, sbn, channel);
@@ -4293,7 +4305,7 @@
     }
 
     @Test
-    public void testFlagBubbleNotifs_flagIfAllowed() throws RemoteException {
+    public void testFlagBubbleNotifs_flag_appForeground() throws RemoteException {
         // Bubbles are allowed!
         mService.setPreferencesHelper(mPreferencesHelper);
         when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(true);
@@ -4303,12 +4315,260 @@
         when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
                 mTestNotificationChannel.getImportance());
 
-        // Notif with bubble metadata
+        // Notif with bubble metadata but not our other misc requirements
+        NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
+                null /* tvExtender */, true /* isBubble */);
+
+        // Say we're foreground
+        when(mActivityManager.getPackageImportance(nr.sbn.getPackageName())).thenReturn(
+                IMPORTANCE_FOREGROUND);
+
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
+                nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
+        waitForIdle();
+
+        // yes allowed, yes foreground, yes bubble
+        assertTrue(mService.getNotificationRecord(
+                nr.sbn.getKey()).getNotification().isBubbleNotification());
+    }
+
+    @Test
+    public void testFlagBubbleNotifs_noFlag_appNotForeground() throws RemoteException {
+        // Bubbles are allowed!
+        mService.setPreferencesHelper(mPreferencesHelper);
+        when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(true);
+        when(mPreferencesHelper.getNotificationChannel(
+                anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
+                mTestNotificationChannel);
+        when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
+                mTestNotificationChannel.getImportance());
+
+        // Notif with bubble metadata but not our other misc requirements
+        NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel,
+                null /* tvExtender */, true /* isBubble */);
+
+        // Make sure we're NOT foreground
+        when(mActivityManager.getPackageImportance(nr.sbn.getPackageName())).thenReturn(
+                IMPORTANCE_VISIBLE);
+
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
+                nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
+        waitForIdle();
+
+        // yes allowed but NOT foreground, no bubble
+        assertFalse(mService.getNotificationRecord(
+                nr.sbn.getKey()).getNotification().isBubbleNotification());
+    }
+
+    @Test
+    public void testFlagBubbleNotifs_flag_previousForegroundFlag() throws RemoteException {
+        // Bubbles are allowed!
+        mService.setPreferencesHelper(mPreferencesHelper);
+        when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(true);
+        when(mPreferencesHelper.getNotificationChannel(
+                anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
+                mTestNotificationChannel);
+        when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
+                mTestNotificationChannel.getImportance());
+
+        // Notif with bubble metadata but not our other misc requirements
+        NotificationRecord nr1 = generateNotificationRecord(mTestNotificationChannel,
+                null /* tvExtender */, true /* isBubble */);
+
+        // Send notif when we're foreground
+        when(mActivityManager.getPackageImportance(nr1.sbn.getPackageName())).thenReturn(
+                IMPORTANCE_FOREGROUND);
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
+                nr1.sbn.getId(), nr1.sbn.getNotification(), nr1.sbn.getUserId());
+        waitForIdle();
+
+        // yes allowed, yes foreground, yes bubble
+        assertTrue(mService.getNotificationRecord(
+                nr1.sbn.getKey()).getNotification().isBubbleNotification());
+
+        // Send a new update when we're not foreground
+        NotificationRecord nr2 = generateNotificationRecord(mTestNotificationChannel,
+                null /* tvExtender */, true /* isBubble */);
+
+        when(mActivityManager.getPackageImportance(nr2.sbn.getPackageName())).thenReturn(
+                IMPORTANCE_VISIBLE);
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
+                nr2.sbn.getId(), nr2.sbn.getNotification(), nr2.sbn.getUserId());
+        waitForIdle();
+
+        // yes allowed, previously foreground / flagged, yes bubble
+        assertTrue(mService.getNotificationRecord(
+                nr2.sbn.getKey()).getNotification().isBubbleNotification());
+
+        StatusBarNotification[] notifs2 = mBinderService.getActiveNotifications(PKG);
+        assertEquals(1, notifs2.length);
+        assertEquals(1, mService.getNotificationRecordCount());
+    }
+
+    @Test
+    public void testFlagBubbleNotifs_noFlag_previousForegroundFlag_afterRemoval()
+            throws RemoteException {
+        // Bubbles are allowed!
+        mService.setPreferencesHelper(mPreferencesHelper);
+        when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(true);
+        when(mPreferencesHelper.getNotificationChannel(
+                anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
+                mTestNotificationChannel);
+        when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
+                mTestNotificationChannel.getImportance());
+
+        // Notif with bubble metadata but not our other misc requirements
+        NotificationRecord nr1 = generateNotificationRecord(mTestNotificationChannel,
+                null /* tvExtender */, true /* isBubble */);
+
+        // Send notif when we're foreground
+        when(mActivityManager.getPackageImportance(nr1.sbn.getPackageName())).thenReturn(
+                IMPORTANCE_FOREGROUND);
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
+                nr1.sbn.getId(), nr1.sbn.getNotification(), nr1.sbn.getUserId());
+        waitForIdle();
+
+        // yes allowed, yes foreground, yes bubble
+        assertTrue(mService.getNotificationRecord(
+                nr1.sbn.getKey()).getNotification().isBubbleNotification());
+
+        // Remove the bubble
+        mBinderService.cancelNotificationWithTag(PKG, "tag", nr1.sbn.getId(),
+                nr1.sbn.getUserId());
+        waitForIdle();
+
+        StatusBarNotification[] notifs = mBinderService.getActiveNotifications(PKG);
+        assertEquals(0, notifs.length);
+        assertEquals(0, mService.getNotificationRecordCount());
+
+        // Send a new update when we're not foreground
+        NotificationRecord nr2 = generateNotificationRecord(mTestNotificationChannel,
+                null /* tvExtender */, true /* isBubble */);
+
+        when(mActivityManager.getPackageImportance(nr2.sbn.getPackageName())).thenReturn(
+                IMPORTANCE_VISIBLE);
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
+                nr2.sbn.getId(), nr2.sbn.getNotification(), nr2.sbn.getUserId());
+        waitForIdle();
+
+        // yes allowed, but was removed & no foreground, so no bubble
+        assertFalse(mService.getNotificationRecord(
+                nr2.sbn.getKey()).getNotification().isBubbleNotification());
+
+        StatusBarNotification[] notifs2 = mBinderService.getActiveNotifications(PKG);
+        assertEquals(1, notifs2.length);
+        assertEquals(1, mService.getNotificationRecordCount());
+    }
+
+    @Test
+    public void testFlagBubbleNotifs_flag_messaging() throws RemoteException {
+        // Bubbles are allowed!
+        mService.setPreferencesHelper(mPreferencesHelper);
+        when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(true);
+        when(mPreferencesHelper.getNotificationChannel(
+                anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
+                mTestNotificationChannel);
+        when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
+                mTestNotificationChannel.getImportance());
+
+        // Give it bubble metadata
         Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
+        // Give it a person
+        Person person = new Person.Builder()
+                .setName("bubblebot")
+                .build();
+        // Make it messaging style
         Notification.Builder nb = new Notification.Builder(mContext,
                 mTestNotificationChannel.getId())
                 .setContentTitle("foo")
                 .setBubbleMetadata(data)
+                .setStyle(new Notification.MessagingStyle(person)
+                        .setConversationTitle("Bubble Chat")
+                        .addMessage("Hello?",
+                                SystemClock.currentThreadTimeMillis() - 300000, person)
+                        .addMessage("Is it me you're looking for?",
+                                SystemClock.currentThreadTimeMillis(), person)
+                )
+                .setSmallIcon(android.R.drawable.sym_def_app_icon);
+
+        StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
+                nb.build(), new UserHandle(mUid), null, 0);
+        NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
+
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
+                nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
+        waitForIdle();
+
+        // yes allowed, yes messaging, yes bubble
+        assertTrue(mService.getNotificationRecord(
+                sbn.getKey()).getNotification().isBubbleNotification());
+    }
+
+    @Test
+    public void testFlagBubbleNotifs_flag_phonecall() throws RemoteException {
+        // Bubbles are allowed!
+        mService.setPreferencesHelper(mPreferencesHelper);
+        when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(true);
+        when(mPreferencesHelper.getNotificationChannel(
+                anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
+                mTestNotificationChannel);
+        when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
+                mTestNotificationChannel.getImportance());
+
+        // Give it bubble metadata
+        Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
+        // Give it a person
+        Person person = new Person.Builder()
+                .setName("bubblebot")
+                .build();
+        // Make it a phone call
+        Notification.Builder nb = new Notification.Builder(mContext,
+                mTestNotificationChannel.getId())
+                .setCategory(CATEGORY_CALL)
+                .addPerson(person)
+                .setContentTitle("foo")
+                .setBubbleMetadata(data)
+                .setSmallIcon(android.R.drawable.sym_def_app_icon);
+
+        StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
+                nb.build(), new UserHandle(mUid), null, 0);
+        // Make sure it has foreground service
+        sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
+        NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
+
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
+                nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
+        waitForIdle();
+
+        // yes phone call, yes person, yes foreground service, yes bubble
+        assertTrue(mService.getNotificationRecord(
+                sbn.getKey()).getNotification().isBubbleNotification());
+    }
+
+    @Test
+    public void testFlagBubbleNotifs_noFlag_phonecall_noForegroundService() throws RemoteException {
+        // Bubbles are allowed!
+        mService.setPreferencesHelper(mPreferencesHelper);
+        when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(true);
+        when(mPreferencesHelper.getNotificationChannel(
+                anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
+                mTestNotificationChannel);
+        when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
+                mTestNotificationChannel.getImportance());
+
+        // Give it bubble metadata
+        Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
+        // Give it a person
+        Person person = new Person.Builder()
+                .setName("bubblebot")
+                .build();
+        // Make it a phone call
+        Notification.Builder nb = new Notification.Builder(mContext,
+                mTestNotificationChannel.getId())
+                .setCategory(CATEGORY_CALL)
+                .addPerson(person)
+                .setContentTitle("foo")
+                .setBubbleMetadata(data)
                 .setSmallIcon(android.R.drawable.sym_def_app_icon);
 
         StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
@@ -4319,13 +4579,89 @@
                 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
         waitForIdle();
 
-        // yes allowed, yes bubble
-        assertTrue(mService.getNotificationRecord(
+        // yes phone call, yes person, NO foreground service, no bubble
+        assertFalse(mService.getNotificationRecord(
                 sbn.getKey()).getNotification().isBubbleNotification());
     }
 
     @Test
-    public void testFlagBubbleNotifs_noFlagIfNotAllowed() throws RemoteException {
+    public void testFlagBubbleNotifs_noFlag_phonecall_noPerson() throws RemoteException {
+        // Bubbles are allowed!
+        mService.setPreferencesHelper(mPreferencesHelper);
+        when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(true);
+        when(mPreferencesHelper.getNotificationChannel(
+                anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
+                mTestNotificationChannel);
+        when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
+                mTestNotificationChannel.getImportance());
+
+        // Give it bubble metadata
+        Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
+        // Make it a phone call
+        Notification.Builder nb = new Notification.Builder(mContext,
+                mTestNotificationChannel.getId())
+                .setCategory(CATEGORY_CALL)
+                .setContentTitle("foo")
+                .setBubbleMetadata(data)
+                .setSmallIcon(android.R.drawable.sym_def_app_icon);
+
+        StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
+                nb.build(), new UserHandle(mUid), null, 0);
+        // Make sure it has foreground service
+        sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
+        NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
+
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
+                nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
+        waitForIdle();
+
+        // yes phone call, yes foreground service, BUT NO person, no bubble
+        assertFalse(mService.getNotificationRecord(
+                sbn.getKey()).getNotification().isBubbleNotification());
+    }
+
+    @Test
+    public void testFlagBubbleNotifs_noFlag_phonecall_noCategory() throws RemoteException {
+        // Bubbles are allowed!
+        mService.setPreferencesHelper(mPreferencesHelper);
+        when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(true);
+        when(mPreferencesHelper.getNotificationChannel(
+                anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
+                mTestNotificationChannel);
+        when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
+                mTestNotificationChannel.getImportance());
+
+        // Give it bubble metadata
+        Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
+        // Give it a person
+        Person person = new Person.Builder()
+                .setName("bubblebot")
+                .build();
+        // No category
+        Notification.Builder nb = new Notification.Builder(mContext,
+                mTestNotificationChannel.getId())
+                .addPerson(person)
+                .setContentTitle("foo")
+                .setBubbleMetadata(data)
+                .setSmallIcon(android.R.drawable.sym_def_app_icon);
+
+        StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
+                nb.build(), new UserHandle(mUid), null, 0);
+        // Make sure it has foreground service
+        sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
+        NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
+
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
+                nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
+        waitForIdle();
+
+        // yes person, yes foreground service, BUT NO call, no bubble
+        assertFalse(mService.getNotificationRecord(
+                sbn.getKey()).getNotification().isBubbleNotification());
+    }
+
+    @Test
+    public void testFlagBubbleNotifs_noFlag_messaging_appNotAllowed() throws RemoteException {
         // Bubbles are NOT allowed!
         mService.setPreferencesHelper(mPreferencesHelper);
         when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(false);
@@ -4335,12 +4671,24 @@
         when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
                 mTestNotificationChannel.getImportance());
 
-        // Notif with bubble metadata
+        // Give it bubble metadata
         Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
+        // Give it a person
+        Person person = new Person.Builder()
+                .setName("bubblebot")
+                .build();
+        // Make it messaging style
         Notification.Builder nb = new Notification.Builder(mContext,
                 mTestNotificationChannel.getId())
                 .setContentTitle("foo")
                 .setBubbleMetadata(data)
+                .setStyle(new Notification.MessagingStyle(person)
+                        .setConversationTitle("Bubble Chat")
+                        .addMessage("Hello?",
+                                SystemClock.currentThreadTimeMillis() - 300000, person)
+                        .addMessage("Is it me you're looking for?",
+                                SystemClock.currentThreadTimeMillis(), person)
+                )
                 .setSmallIcon(android.R.drawable.sym_def_app_icon);
 
         StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
@@ -4358,7 +4706,7 @@
     }
 
     @Test
-    public void testFlagBubbleNotifs_noFlagIfNotBubble() throws RemoteException {
+    public void testFlagBubbleNotifs_noFlag_notBubble() throws RemoteException {
         // Bubbles are allowed!
         mService.setPreferencesHelper(mPreferencesHelper);
         when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(true);
@@ -4369,27 +4717,20 @@
                 mTestNotificationChannel.getImportance());
 
         // Notif WITHOUT bubble metadata
-        Notification.Builder nb = new Notification.Builder(mContext,
-                mTestNotificationChannel.getId())
-                .setContentTitle("foo")
-                .setSmallIcon(android.R.drawable.sym_def_app_icon);
-
-        StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
-                nb.build(), new UserHandle(mUid), null, 0);
-        NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
+        NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel);
 
         // Post the notification
-        mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, "tag",
                 nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
         waitForIdle();
 
         // no bubble metadata, no bubble
         assertFalse(mService.getNotificationRecord(
-                sbn.getKey()).getNotification().isBubbleNotification());
+                nr.sbn.getKey()).getNotification().isBubbleNotification());
     }
 
     @Test
-    public void testFlagBubbleNotifs_noFlagIfChannelNotBubble() throws RemoteException {
+    public void testFlagBubbleNotifs_noFlag_messaging_channelNotAllowed() throws RemoteException {
         // Bubbles are allowed!
         mService.setPreferencesHelper(mPreferencesHelper);
         when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(true);
@@ -4402,12 +4743,24 @@
         // But not on this channel!
         mTestNotificationChannel.setAllowBubbles(false);
 
-        // Notif with bubble metadata
+        // Give it bubble metadata
         Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
+        // Give it a person
+        Person person = new Person.Builder()
+                .setName("bubblebot")
+                .build();
+        // Make it messaging style
         Notification.Builder nb = new Notification.Builder(mContext,
                 mTestNotificationChannel.getId())
                 .setContentTitle("foo")
                 .setBubbleMetadata(data)
+                .setStyle(new Notification.MessagingStyle(person)
+                        .setConversationTitle("Bubble Chat")
+                        .addMessage("Hello?",
+                                SystemClock.currentThreadTimeMillis() - 300000, person)
+                        .addMessage("Is it me you're looking for?",
+                                SystemClock.currentThreadTimeMillis(), person)
+                )
                 .setSmallIcon(android.R.drawable.sym_def_app_icon);
 
         StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
@@ -4425,6 +4778,91 @@
     }
 
     @Test
+    public void testFlagBubbleNotifs_noFlag_phonecall_notAllowed() throws RemoteException {
+        // Bubbles are allowed!
+        mService.setPreferencesHelper(mPreferencesHelper);
+        when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(false);
+        when(mPreferencesHelper.getNotificationChannel(
+                anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
+                mTestNotificationChannel);
+        when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
+                mTestNotificationChannel.getImportance());
+
+        // Give it bubble metadata
+        Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
+        // Give it a person
+        Person person = new Person.Builder()
+                .setName("bubblebot")
+                .build();
+        // Make it a phone call
+        Notification.Builder nb = new Notification.Builder(mContext,
+                mTestNotificationChannel.getId())
+                .setCategory(CATEGORY_CALL)
+                .addPerson(person)
+                .setContentTitle("foo")
+                .setBubbleMetadata(data)
+                .setSmallIcon(android.R.drawable.sym_def_app_icon);
+
+        StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
+                nb.build(), new UserHandle(mUid), null, 0);
+        // Make sure it has foreground service
+        sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
+        NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
+
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
+                nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
+        waitForIdle();
+
+        // yes phone call, yes person, yes foreground service, but not allowed, no bubble
+        assertFalse(mService.getNotificationRecord(
+                sbn.getKey()).getNotification().isBubbleNotification());
+    }
+
+    @Test
+    public void testFlagBubbleNotifs_noFlag_phonecall_channelNotAllowed() throws RemoteException {
+        // Bubbles are allowed!
+        mService.setPreferencesHelper(mPreferencesHelper);
+        when(mPreferencesHelper.areBubblesAllowed(anyString(), anyInt())).thenReturn(false);
+        when(mPreferencesHelper.getNotificationChannel(
+                anyString(), anyInt(), anyString(), anyBoolean())).thenReturn(
+                mTestNotificationChannel);
+        when(mPreferencesHelper.getImportance(anyString(), anyInt())).thenReturn(
+                mTestNotificationChannel.getImportance());
+
+        // But not on this channel!
+        mTestNotificationChannel.setAllowBubbles(false);
+
+        // Give it bubble metadata
+        Notification.BubbleMetadata data = getBasicBubbleMetadataBuilder().build();
+        // Give it a person
+        Person person = new Person.Builder()
+                .setName("bubblebot")
+                .build();
+        // Make it a phone call
+        Notification.Builder nb = new Notification.Builder(mContext,
+                mTestNotificationChannel.getId())
+                .setCategory(CATEGORY_CALL)
+                .addPerson(person)
+                .setContentTitle("foo")
+                .setBubbleMetadata(data)
+                .setSmallIcon(android.R.drawable.sym_def_app_icon);
+
+        StatusBarNotification sbn = new StatusBarNotification(PKG, PKG, 1, null, mUid, 0,
+                nb.build(), new UserHandle(mUid), null, 0);
+        // Make sure it has foreground service
+        sbn.getNotification().flags |= FLAG_FOREGROUND_SERVICE;
+        NotificationRecord nr = new NotificationRecord(mContext, sbn, mTestNotificationChannel);
+
+        mBinderService.enqueueNotificationWithTag(PKG, PKG, null,
+                nr.sbn.getId(), nr.sbn.getNotification(), nr.sbn.getUserId());
+        waitForIdle();
+
+        // yes phone call, yes person, yes foreground service, but channel not allowed, no bubble
+        assertFalse(mService.getNotificationRecord(
+                sbn.getKey()).getNotification().isBubbleNotification());
+    }
+
+    @Test
     public void testCancelAllNotifications_cancelsBubble() throws Exception {
         final NotificationRecord nr = generateNotificationRecord(mTestNotificationChannel);
         nr.sbn.getNotification().flags |= FLAG_BUBBLE;
diff --git a/telecomm/java/android/telecom/Call.java b/telecomm/java/android/telecom/Call.java
index c05a346..1822cee 100644
--- a/telecomm/java/android/telecom/Call.java
+++ b/telecomm/java/android/telecom/Call.java
@@ -552,7 +552,6 @@
         private final Bundle mExtras;
         private final Bundle mIntentExtras;
         private final long mCreationTimeMillis;
-        private final CallIdentification mCallIdentification;
         private final @CallDirection int mCallDirection;
 
         /**
@@ -738,8 +737,6 @@
          * The display name for the caller.
          * <p>
          * This is the name as reported by the {@link ConnectionService} associated with this call.
-         * The name reported by a {@link CallScreeningService} can be retrieved using
-         * {@link CallIdentification#getName()}.
          *
          * @return The display name for the caller.
          */
@@ -857,23 +854,6 @@
         }
 
         /**
-         * Returns {@link CallIdentification} information provided by a
-         * {@link CallScreeningService} for this call.
-         * <p>
-         * {@link InCallService} implementations should display the {@link CallIdentification} for
-         * calls.  The name of the call screening service is provided in
-         * {@link CallIdentification#getCallScreeningAppName()} and should be used to attribute the
-         * call identification information.
-         *
-         * @return The {@link CallIdentification} if it was provided by a
-         * {@link CallScreeningService}, or {@code null} if no {@link CallScreeningService} has
-         * provided {@link CallIdentification} information for the call.
-         */
-        public @Nullable CallIdentification getCallIdentification() {
-            return mCallIdentification;
-        }
-
-        /**
          * Indicates whether the call is an incoming or outgoing call.
          * @return The call's direction.
          */
@@ -902,7 +882,6 @@
                         areBundlesEqual(mExtras, d.mExtras) &&
                         areBundlesEqual(mIntentExtras, d.mIntentExtras) &&
                         Objects.equals(mCreationTimeMillis, d.mCreationTimeMillis) &&
-                        Objects.equals(mCallIdentification, d.mCallIdentification) &&
                         Objects.equals(mCallDirection, d.mCallDirection);
             }
             return false;
@@ -925,7 +904,6 @@
                             mExtras,
                             mIntentExtras,
                             mCreationTimeMillis,
-                            mCallIdentification,
                             mCallDirection);
         }
 
@@ -947,7 +925,6 @@
                 Bundle extras,
                 Bundle intentExtras,
                 long creationTimeMillis,
-                CallIdentification callIdentification,
                 int callDirection) {
             mTelecomCallId = telecomCallId;
             mHandle = handle;
@@ -965,7 +942,6 @@
             mExtras = extras;
             mIntentExtras = intentExtras;
             mCreationTimeMillis = creationTimeMillis;
-            mCallIdentification = callIdentification;
             mCallDirection = callDirection;
         }
 
@@ -988,7 +964,6 @@
                     parcelableCall.getExtras(),
                     parcelableCall.getIntentExtras(),
                     parcelableCall.getCreationTimeMillis(),
-                    parcelableCall.getCallIdentification(),
                     parcelableCall.getCallDirection());
         }
 
diff --git a/telecomm/java/android/telecom/CallIdentification.java b/telecomm/java/android/telecom/CallIdentification.java
deleted file mode 100644
index 745affd..0000000
--- a/telecomm/java/android/telecom/CallIdentification.java
+++ /dev/null
@@ -1,451 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.telecom;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.pm.ApplicationInfo;
-import android.graphics.drawable.Icon;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Objects;
-
-/**
- * Encapsulates information about an incoming or outgoing {@link Call} provided by a
- * {@link CallScreeningService}.
- * <p>
- * Call identified information is consumed by the {@link InCallService dialer} app to provide the
- * user with more information about a call.  This can include information such as the name of the
- * caller, address, etc.  Call identification information is persisted to the
- * {@link android.provider.CallLog}.
- */
-public final class CallIdentification implements Parcelable {
-    /**
-     * Builder for {@link CallIdentification} instances.
-     * <p>
-     * A {@link CallScreeningService} uses this class to create new instances of
-     * {@link CallIdentification} for a screened call.
-     */
-    public final static class Builder {
-        private CharSequence mName;
-        private CharSequence mDescription;
-        private CharSequence mDetails;
-        private Icon mPhoto;
-        private int mNuisanceConfidence = CallIdentification.CONFIDENCE_UNKNOWN;
-        private String mPackageName;
-        private CharSequence mAppName;
-
-        /**
-         * Default builder constructor.
-         */
-        public Builder() {
-            // Default constructor
-        }
-
-        /**
-         * Create instance of call identification with specified package/app name.
-         *
-         * @param callIdPackageName The package name.
-         * @param callIdAppName The app name.
-         * @hide
-         */
-        public Builder(@NonNull String callIdPackageName, @NonNull CharSequence callIdAppName) {
-            mPackageName = callIdPackageName;
-            mAppName = callIdAppName;
-        }
-
-        /**
-         * Sets the name associated with the {@link CallIdentification} being built.
-         * <p>
-         * Could be a business name, for example.
-         *
-         * @param name The name associated with the call, or {@code null} if none is provided.
-         * @return Builder instance.
-         */
-        public @NonNull Builder setName(@Nullable CharSequence name) {
-            mName = name;
-            return this;
-        }
-
-        /**
-         * Sets the description associated with the {@link CallIdentification} being built.
-         * <p>
-         * A description of the call as identified by a {@link CallScreeningService}.  The
-         * description is typically presented by Dialer apps after the
-         * {@link CallIdentification#getName() name} to provide a short piece of relevant
-         * information about the call.  This could include a location, address, or a message
-         * regarding the potential nature of the call (e.g. potential telemarketer).
-         *
-         * @param description The call description, or {@code null} if none is provided.
-         * @return Builder instance.
-         */
-        public @NonNull Builder setDescription(@Nullable CharSequence description) {
-            mDescription = description;
-            return this;
-        }
-
-        /**
-         * Sets the details associated with the {@link CallIdentification} being built.
-         * <p>
-         * The details is typically presented by Dialer apps after the
-         * {@link CallIdentification#getName() name} and
-         * {@link CallIdentification#getDescription() description} to provide further clarifying
-         * information about the call. This could include, for example, the opening hours of a
-         * business, or a stats about the number of times a call has been reported as spam.
-         *
-         * @param details The call details, or {@code null} if none is provided.
-         * @return Builder instance.
-         */
-
-        public @NonNull Builder setDetails(@Nullable CharSequence details) {
-            mDetails = details;
-            return this;
-        }
-
-        /**
-         * Sets the photo associated with the {@link CallIdentification} being built.
-         * <p>
-         * This could be, for example, a business logo, or a photo of the caller.
-         *
-         * @param photo The photo associated with the call, or {@code null} if none was provided.
-         * @return Builder instance.
-         */
-        public @NonNull Builder setPhoto(@Nullable Icon photo) {
-            mPhoto = photo;
-            return this;
-        }
-
-        /**
-         * Sets the nuisance confidence with the {@link CallIdentification} being built.
-         * <p>
-         * This can be used to specify how confident the {@link CallScreeningService} is that a call
-         * is or is not a nuisance call.
-         *
-         * @param nuisanceConfidence The nuisance confidence.
-         * @return The builder.
-         */
-        public @NonNull Builder setNuisanceConfidence(@NuisanceConfidence int nuisanceConfidence) {
-            mNuisanceConfidence = nuisanceConfidence;
-            return this;
-        }
-
-        /**
-         * Creates a new instance of {@link CallIdentification} based on the parameters set in this
-         * builder.
-         *
-         * @return {@link CallIdentification} instance.
-         */
-        public @NonNull CallIdentification build() {
-            return new CallIdentification(mName, mDescription, mDetails, mPhoto,
-                    mNuisanceConfidence, mPackageName, mAppName);
-        }
-    }
-
-    /** @hide */
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef(
-            prefix = { "CONFIDENCE_" },
-            value = {CONFIDENCE_NUISANCE, CONFIDENCE_LIKELY_NUISANCE, CONFIDENCE_UNKNOWN,
-                    CONFIDENCE_LIKELY_NOT_NUISANCE, CONFIDENCE_NOT_NUISANCE})
-    public @interface NuisanceConfidence {}
-
-    /**
-     * Call has been identified as a nuisance call.
-     * <p>
-     * Returned from {@link #getNuisanceConfidence()} to indicate that a
-     * {@link CallScreeningService} to indicate how confident it is that a call is or is not a
-     * nuisance call.
-     */
-    public static final int CONFIDENCE_NUISANCE = 2;
-
-    /**
-     * Call has been identified as a likely nuisance call.
-     * <p>
-     * Returned from {@link #getNuisanceConfidence()} to indicate that a
-     * {@link CallScreeningService} to indicate how confident it is that a call is or is not a
-     * nuisance call.
-     */
-    public static final int CONFIDENCE_LIKELY_NUISANCE = 1;
-
-    /**
-     * Call could not be classified as nuisance or non-nuisance.
-     * <p>
-     * Returned from {@link #getNuisanceConfidence()} to indicate that a
-     * {@link CallScreeningService} to indicate how confident it is that a call is or is not a
-     * nuisance call.
-     */
-    public static final int CONFIDENCE_UNKNOWN = 0;
-
-    /**
-     * Call has been identified as not likely to be a nuisance call.
-     * <p>
-     * Returned from {@link #getNuisanceConfidence()} to indicate that a
-     * {@link CallScreeningService} to indicate how confident it is that a call is or is not a
-     * nuisance call.
-     */
-    public static final int CONFIDENCE_LIKELY_NOT_NUISANCE = -1;
-
-    /**
-     * Call has been identified as not a nuisance call.
-     * <p>
-     * Returned from {@link #getNuisanceConfidence()} to indicate that a
-     * {@link CallScreeningService} to indicate how confident it is that a call is or is not a
-     * nuisance call.
-     */
-    public static final int CONFIDENCE_NOT_NUISANCE = -2;
-
-    /**
-     * Default constructor for {@link CallIdentification}.
-     *
-     * @param name The name.
-     * @param description The description.
-     * @param details The details.
-     * @param photo The photo.
-     * @param nuisanceConfidence Confidence that this is a nuisance call.
-     * @hide
-     */
-    private CallIdentification(@Nullable String name, @Nullable String description,
-            @Nullable String details, @Nullable Icon photo,
-            @NuisanceConfidence int nuisanceConfidence) {
-        this(name, description, details, photo, nuisanceConfidence, null, null);
-    }
-
-    /**
-     * Default constructor for {@link CallIdentification}.
-     *
-     * @param name The name.
-     * @param description The description.
-     * @param details The details.
-     * @param photo The photo.
-     * @param nuisanceConfidence Confidence that this is a nuisance call.
-     * @param callScreeningPackageName Package name of the {@link CallScreeningService} which
-     *                                 provided the call identification.
-     * @param callScreeningAppName App name of the {@link CallScreeningService} which provided the
-     *                             call identification.
-     * @hide
-     */
-    private CallIdentification(@Nullable CharSequence name, @Nullable CharSequence description,
-            @Nullable CharSequence details, @Nullable Icon photo,
-            @NuisanceConfidence int nuisanceConfidence, @NonNull String callScreeningPackageName,
-            @NonNull CharSequence callScreeningAppName) {
-        mName = name;
-        mDescription = description;
-        mDetails = details;
-        mPhoto = photo;
-        mNuisanceConfidence = nuisanceConfidence;
-        mCallScreeningAppName = callScreeningAppName;
-        mCallScreeningPackageName = callScreeningPackageName;
-    }
-
-    private CharSequence mName;
-    private CharSequence mDescription;
-    private CharSequence mDetails;
-    private Icon mPhoto;
-    private int mNuisanceConfidence;
-    private String mCallScreeningPackageName;
-    private CharSequence mCallScreeningAppName;
-
-    @Override
-    public int describeContents() {
-        return 0;
-    }
-
-    @Override
-    public void writeToParcel(Parcel parcel, int i) {
-        parcel.writeCharSequence(mName);
-        parcel.writeCharSequence(mDescription);
-        parcel.writeCharSequence(mDetails);
-        parcel.writeParcelable(mPhoto, 0);
-        parcel.writeInt(mNuisanceConfidence);
-        parcel.writeString(mCallScreeningPackageName);
-        parcel.writeCharSequence(mCallScreeningAppName);
-    }
-
-    /**
-     * Responsible for creating CallIdentification objects for deserialized Parcels.
-     */
-    public static final @android.annotation.NonNull Parcelable.Creator<CallIdentification> CREATOR =
-            new Parcelable.Creator<CallIdentification> () {
-
-                @Override
-                public CallIdentification createFromParcel(Parcel source) {
-                    CharSequence name = source.readCharSequence();
-                    CharSequence description = source.readCharSequence();
-                    CharSequence details = source.readCharSequence();
-                    Icon photo = source.readParcelable(ClassLoader.getSystemClassLoader());
-                    int nuisanceConfidence = source.readInt();
-                    String callScreeningPackageName = source.readString();
-                    CharSequence callScreeningAppName = source.readCharSequence();
-                    return new CallIdentification(name, description, details, photo,
-                            nuisanceConfidence, callScreeningPackageName, callScreeningAppName);
-                }
-
-                @Override
-                public CallIdentification[] newArray(int size) {
-                    return new CallIdentification[size];
-                }
-            };
-
-    /**
-     * The name associated with the number.
-     * <p>
-     * The name of the call as identified by a {@link CallScreeningService}.  Could be a business
-     * name, for example.
-     *
-     * @return The name associated with the number, or {@code null} if none was provided.
-     */
-    public final @Nullable CharSequence getName() {
-        return mName;
-    }
-
-    /**
-     * Description of the call.
-     * <p>
-     * A description of the call as identified by a {@link CallScreeningService}.  The description
-     * is typically presented by Dialer apps after the {@link #getName() name} to provide a short
-     * piece of relevant information about the call.  This could include a location, address, or a
-     * message regarding the potential nature of the call (e.g. potential telemarketer).
-     *
-     * @return The call description, or {@code null} if none was provided.
-     */
-    public final @Nullable CharSequence getDescription() {
-        return mDescription;
-    }
-
-    /**
-     * Details of the call.
-     * <p>
-     * Details of the call as identified by a {@link CallScreeningService}.  The details
-     * are typically presented by Dialer apps after the {@link #getName() name} and
-     * {@link #getDescription() description} to provide further clarifying information about the
-     * call. This could include, for example, the opening hours of a business, or stats about
-     * the number of times a call has been reported as spam.
-     *
-     * @return The call details, or {@code null} if none was provided.
-     */
-    public final @Nullable CharSequence getDetails() {
-        return mDetails;
-    }
-
-    /**
-     * Photo associated with the call.
-     * <p>
-     * A photo associated with the call as identified by a {@link CallScreeningService}.  This
-     * could be, for example, a business logo, or a photo of the caller.
-     *
-     * @return The photo associated with the call, or {@code null} if none was provided.
-     */
-    public final @Nullable Icon getPhoto() {
-        return mPhoto;
-    }
-
-    /**
-     * Indicates the likelihood that this call is a nuisance call.
-     * <p>
-     * How likely the call is a nuisance call, as identified by a {@link CallScreeningService}.
-     *
-     * @return The nuisance confidence.
-     */
-    public final @NuisanceConfidence int getNuisanceConfidence() {
-        return mNuisanceConfidence;
-    }
-
-    /**
-     * The package name of the {@link CallScreeningService} which provided the
-     * {@link CallIdentification}.
-     * <p>
-     * A {@link CallScreeningService} may not set this property; it is set by the system.
-     * @return the package name
-     */
-    public final @NonNull String getCallScreeningPackageName() {
-        return mCallScreeningPackageName;
-    }
-
-    /**
-     * The {@link android.content.pm.PackageManager#getApplicationLabel(ApplicationInfo) name} of
-     * the {@link CallScreeningService} which provided the {@link CallIdentification}.
-     * <p>
-     * A {@link CallScreeningService} may not set this property; it is set by the system.
-     *
-     * @return The name of the app.
-     */
-    public final @NonNull CharSequence getCallScreeningAppName() {
-        return mCallScreeningAppName;
-    }
-
-    /**
-     * Set the package name of the {@link CallScreeningService} which provided this information.
-     *
-     * @param callScreeningPackageName The package name.
-     * @hide
-     */
-    public void setCallScreeningPackageName(@NonNull String callScreeningPackageName) {
-        mCallScreeningPackageName = callScreeningPackageName;
-    }
-
-    /**
-     * Set the app name of the {@link CallScreeningService} which provided this information.
-     *
-     * @param callScreeningAppName The app name.
-     * @hide
-     */
-    public void setCallScreeningAppName(@NonNull CharSequence callScreeningAppName) {
-        mCallScreeningAppName = callScreeningAppName;
-    }
-
-    @Override
-    public boolean equals(Object o) {
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
-        CallIdentification that = (CallIdentification) o;
-        // Note: mPhoto purposely omit as no good comparison exists.
-        return mNuisanceConfidence == that.mNuisanceConfidence
-                && Objects.equals(mName, that.mName)
-                && Objects.equals(mDescription, that.mDescription)
-                && Objects.equals(mDetails, that.mDetails)
-                && Objects.equals(mCallScreeningAppName, that.mCallScreeningAppName)
-                && Objects.equals(mCallScreeningPackageName, that.mCallScreeningPackageName);
-    }
-
-    @Override
-    public int hashCode() {
-        return Objects.hash(mName, mDescription, mDetails, mPhoto, mNuisanceConfidence,
-                mCallScreeningAppName, mCallScreeningPackageName);
-    }
-
-    @Override
-    public String toString() {
-        StringBuilder sb = new StringBuilder();
-        sb.append("[CallId mName=");
-        sb.append(Log.pii(mName));
-        sb.append(", mDesc=");
-        sb.append(mDescription);
-        sb.append(", mDet=");
-        sb.append(mDetails);
-        sb.append(", conf=");
-        sb.append(mNuisanceConfidence);
-        sb.append(", appName=");
-        sb.append(mCallScreeningAppName);
-        sb.append(", pkgName=");
-        sb.append(mCallScreeningPackageName);
-        return sb.toString();
-    }
-}
diff --git a/telecomm/java/android/telecom/CallScreeningService.java b/telecomm/java/android/telecom/CallScreeningService.java
index b1aece7..0e0406d 100644
--- a/telecomm/java/android/telecom/CallScreeningService.java
+++ b/telecomm/java/android/telecom/CallScreeningService.java
@@ -39,8 +39,8 @@
 /**
  * This service can be implemented by the default dialer (see
  * {@link TelecomManager#getDefaultDialerPackage()}) or a third party app to allow or disallow
- * incoming calls before they are shown to a user.  This service can also provide
- * {@link CallIdentification} information for calls.
+ * incoming calls before they are shown to a user. A {@link CallScreeningService} can also see
+ * outgoing calls for the purpose of providing caller ID services for those calls.
  * <p>
  * Below is an example manifest registration for a {@code CallScreeningService}.
  * <pre>
@@ -58,9 +58,9 @@
  * <ol>
  *     <li>Call blocking/screening - the service can choose which calls will ring on the user's
  *     device, and which will be silently sent to voicemail.</li>
- *     <li>Call identification - the service can optionally provide {@link CallIdentification}
- *     information about a {@link Call.Details call} which will be shown to the user in the
- *     Dialer app.</li>
+ *     <li>Call identification - services which provide call identification functionality can
+ *     display a user-interface of their choosing which contains identifying information for a call.
+ *     </li>
  * </ol>
  * <p>
  * <h2>Becoming the {@link CallScreeningService}</h2>
@@ -92,128 +92,6 @@
  * </pre>
  */
 public abstract class CallScreeningService extends Service {
-
-    /** @hide */
-    @Retention(RetentionPolicy.SOURCE)
-    @IntDef(
-            prefix = { "CALL_DURATION_" },
-            value = {CALL_DURATION_VERY_SHORT, CALL_DURATION_SHORT, CALL_DURATION_MEDIUM,
-                    CALL_DURATION_LONG})
-    public @interface CallDuration {}
-
-    /**
-     * Call duration reported with {@link #EXTRA_CALL_DURATION} to indicate to the
-     * {@link CallScreeningService} the duration of a call for which the user reported the nuisance
-     * status (see {@link TelecomManager#reportNuisanceCallStatus(Uri, boolean)}).  The
-     * {@link CallScreeningService} can use this as a signal for training nuisance detection
-     * algorithms.  The call duration is reported in coarse grained buckets to minimize exposure of
-     * identifying call log information to the {@link CallScreeningService}.
-     * <p>
-     * Indicates the call was < 3 seconds in duration.
-     */
-    public static final int CALL_DURATION_VERY_SHORT = 1;
-
-    /**
-     * Call duration reported with {@link #EXTRA_CALL_DURATION} to indicate to the
-     * {@link CallScreeningService} the duration of a call for which the user reported the nuisance
-     * status (see {@link TelecomManager#reportNuisanceCallStatus(Uri, boolean)}).  The
-     * {@link CallScreeningService} can use this as a signal for training nuisance detection
-     * algorithms.  The call duration is reported in coarse grained buckets to minimize exposure of
-     * identifying call log information to the {@link CallScreeningService}.
-     * <p>
-     * Indicates the call was greater than 3 seconds, but less than 60 seconds in duration.
-     */
-    public static final int CALL_DURATION_SHORT = 2;
-
-    /**
-     * Call duration reported with {@link #EXTRA_CALL_DURATION} to indicate to the
-     * {@link CallScreeningService} the duration of a call for which the user reported the nuisance
-     * status (see {@link TelecomManager#reportNuisanceCallStatus(Uri, boolean)}).  The
-     * {@link CallScreeningService} can use this as a signal for training nuisance detection
-     * algorithms.  The call duration is reported in coarse grained buckets to minimize exposure of
-     * identifying call log information to the {@link CallScreeningService}.
-     * <p>
-     * Indicates the call was greater than 60 seconds, but less than 120 seconds in duration.
-     */
-    public static final int CALL_DURATION_MEDIUM = 3;
-
-    /**
-     * Call duration reported with {@link #EXTRA_CALL_DURATION} to indicate to the
-     * {@link CallScreeningService} the duration of a call for which the user reported the nuisance
-     * status (see {@link TelecomManager#reportNuisanceCallStatus(Uri, boolean)}).  The
-     * {@link CallScreeningService} can use this as a signal for training nuisance detection
-     * algorithms.  The call duration is reported in coarse grained buckets to minimize exposure of
-     * identifying call log information to the {@link CallScreeningService}.
-     * <p>
-     * Indicates the call was greater than 120 seconds.
-     */
-    public static final int CALL_DURATION_LONG = 4;
-
-    /**
-     * Telecom sends this intent to the {@link CallScreeningService} which the user has chosen to
-     * fill the call screening role when the user indicates through the default dialer whether a
-     * call is a nuisance call or not (see
-     * {@link TelecomManager#reportNuisanceCallStatus(Uri, boolean)}).
-     * <p>
-     * The following extra values are provided for the call:
-     * <ol>
-     *     <li>{@link #EXTRA_CALL_HANDLE} - the handle of the call.</li>
-     *     <li>{@link #EXTRA_IS_NUISANCE} - {@code true} if the user reported the call as a nuisance
-     *     call, {@code false} otherwise.</li>
-     *     <li>{@link #EXTRA_CALL_TYPE} - reports the type of call (incoming, rejected, missed,
-     *     blocked).</li>
-     *     <li>{@link #EXTRA_CALL_DURATION} - the duration of the call (see
-     *     {@link #EXTRA_CALL_DURATION} for valid values).</li>
-     * </ol>
-     * <p>
-     * {@link CallScreeningService} implementations which want to track whether the user reports
-     * calls are nuisance calls should use declare a broadcast receiver in their manifest for this
-     * intent.
-     * <p>
-     * Note: Only {@link CallScreeningService} implementations which have provided
-     * {@link CallIdentification} information for calls at some point will receive this intent.
-     */
-    public static final String ACTION_NUISANCE_CALL_STATUS_CHANGED =
-            "android.telecom.action.NUISANCE_CALL_STATUS_CHANGED";
-
-    /**
-     * Extra used to provide the handle of the call for
-     * {@link #ACTION_NUISANCE_CALL_STATUS_CHANGED}.  The call handle is reported as a
-     * {@link Uri}.
-     */
-    public static final String EXTRA_CALL_HANDLE = "android.telecom.extra.CALL_HANDLE";
-
-    /**
-     * Boolean extra used to indicate whether the user reported a call as a nuisance call.
-     * When {@code true}, the user reported that a call was a nuisance call, {@code false}
-     * otherwise.  Sent with {@link #ACTION_NUISANCE_CALL_STATUS_CHANGED}.
-     */
-    public static final String EXTRA_IS_NUISANCE = "android.telecom.extra.IS_NUISANCE";
-
-    /**
-     * Integer extra used with {@link #ACTION_NUISANCE_CALL_STATUS_CHANGED} to report the type of
-     * call. Valid values are:
-     * <UL>
-     *   <li>{@link android.provider.CallLog.Calls#MISSED_TYPE}</li>
-     *   <li>{@link android.provider.CallLog.Calls#INCOMING_TYPE}</li>
-     *   <li>{@link android.provider.CallLog.Calls#BLOCKED_TYPE}</li>
-     *   <li>{@link android.provider.CallLog.Calls#REJECTED_TYPE}</li>
-     * </UL>
-     */
-    public static final String EXTRA_CALL_TYPE = "android.telecom.extra.CALL_TYPE";
-
-    /**
-     * Integer extra used to with {@link #ACTION_NUISANCE_CALL_STATUS_CHANGED} to report how long
-     * the call lasted.  Valid values are:
-     * <UL>
-     *     <LI>{@link #CALL_DURATION_VERY_SHORT}</LI>
-     *     <LI>{@link #CALL_DURATION_SHORT}</LI>
-     *     <LI>{@link #CALL_DURATION_MEDIUM}</LI>
-     *     <LI>{@link #CALL_DURATION_LONG}</LI>
-     * </UL>
-     */
-    public static final String EXTRA_CALL_DURATION = "android.telecom.extra.CALL_DURATION";
-
     /**
      * The {@link Intent} that must be declared as handled by the service.
      */
@@ -413,10 +291,6 @@
      * Your app can tell if a call is an incoming call by checking to see if
      * {@link Call.Details#getCallDirection()} is {@link Call.Details#DIRECTION_INCOMING}.
      * <p>
-     * For incoming or outgoing calls, the {@link CallScreeningService} can call
-     * {@link #provideCallIdentification(Call.Details, CallIdentification)} in order to provide
-     * {@link CallIdentification} for the call.
-     * <p>
      * Note: The {@link Call.Details} instance provided to a call screening service will only have
      * the following properties set.  The rest of the {@link Call.Details} properties will be set to
      * their default value or {@code null}.
@@ -472,32 +346,4 @@
         } catch (RemoteException e) {
         }
     }
-
-    /**
-     * Provide {@link CallIdentification} information about a {@link Call.Details call}.
-     * <p>
-     * The {@link CallScreeningService} calls this method to provide information it has identified
-     * about a {@link Call.Details call}.  This information will potentially be shown to the user
-     * in the {@link InCallService dialer} app.  It will be logged to the
-     * {@link android.provider.CallLog}.
-     * <p>
-     * A {@link CallScreeningService} should only call this method for calls for which it is able to
-     * provide some {@link CallIdentification} for.  {@link CallIdentification} instances with no
-     * fields set will be ignored by the system.
-     *
-     * @param callDetails The call to provide information for.
-     *                    <p>
-     *                    Must be the same {@link Call.Details call} which was provided to the
-     *                    {@link CallScreeningService} via {@link #onScreenCall(Call.Details)}.
-     * @param identification An instance of {@link CallIdentification} with information about the
-     *                       {@link Call.Details call}.
-     */
-    public final void provideCallIdentification(@NonNull Call.Details callDetails,
-            @NonNull CallIdentification identification) {
-        try {
-            mCallScreeningAdapter.provideCallIdentification(callDetails.getTelecomCallId(),
-                    identification);
-        } catch (RemoteException e) {
-        }
-    }
 }
diff --git a/telecomm/java/android/telecom/ParcelableCall.java b/telecomm/java/android/telecom/ParcelableCall.java
index 345707e..aa50991 100644
--- a/telecomm/java/android/telecom/ParcelableCall.java
+++ b/telecomm/java/android/telecom/ParcelableCall.java
@@ -64,7 +64,6 @@
     private final Bundle mIntentExtras;
     private final Bundle mExtras;
     private final long mCreationTimeMillis;
-    private final CallIdentification mCallIdentification;
     private final int mCallDirection;
 
     public ParcelableCall(
@@ -94,7 +93,6 @@
             Bundle intentExtras,
             Bundle extras,
             long creationTimeMillis,
-            CallIdentification callIdentification,
             int callDirection) {
         mId = id;
         mState = state;
@@ -122,7 +120,6 @@
         mIntentExtras = intentExtras;
         mExtras = extras;
         mCreationTimeMillis = creationTimeMillis;
-        mCallIdentification = callIdentification;
         mCallDirection = callDirection;
     }
 
@@ -314,15 +311,6 @@
     }
 
     /**
-     * Contains call identification information returned by a {@link CallScreeningService}.
-     * @return The {@link CallIdentification} for this call, or {@code null} if a
-     * {@link CallScreeningService} did not provide information.
-     */
-    public @Nullable CallIdentification getCallIdentification() {
-        return mCallIdentification;
-    }
-
-    /**
      * Indicates whether the call is an incoming or outgoing call.
      */
     public @CallDirection int getCallDirection() {
@@ -366,7 +354,6 @@
             boolean isRttCallChanged = source.readByte() == 1;
             ParcelableRttCall rttCall = source.readParcelable(classLoader);
             long creationTimeMillis = source.readLong();
-            CallIdentification callIdentification = source.readParcelable(classLoader);
             int callDirection = source.readInt();
             return new ParcelableCall(
                     id,
@@ -395,7 +382,6 @@
                     intentExtras,
                     extras,
                     creationTimeMillis,
-                    callIdentification,
                     callDirection);
         }
 
@@ -441,7 +427,6 @@
         destination.writeByte((byte) (mIsRttCallChanged ? 1 : 0));
         destination.writeParcelable(mRttCall, 0);
         destination.writeLong(mCreationTimeMillis);
-        destination.writeParcelable(mCallIdentification, 0);
         destination.writeInt(mCallDirection);
     }
 
diff --git a/telecomm/java/android/telecom/TelecomManager.java b/telecomm/java/android/telecom/TelecomManager.java
index 3d0a3c5..391d788 100644
--- a/telecomm/java/android/telecom/TelecomManager.java
+++ b/telecomm/java/android/telecom/TelecomManager.java
@@ -2002,33 +2002,6 @@
     }
 
     /**
-     * Called by the default dialer to report to Telecom when the user has marked a previous
-     * incoming call as a nuisance call or not.
-     * <p>
-     * Where the user has chosen a {@link CallScreeningService} to fill the call screening role,
-     * Telecom will notify that {@link CallScreeningService} of the user's report.
-     * <p>
-     * Requires that the caller is the default dialer app.
-     *
-     * @param handle The phone number of an incoming call which the user is reporting as either a
-     *               nuisance of non-nuisance call.
-     * @param isNuisanceCall {@code true} if the user is reporting the call as a nuisance call,
-     *                       {@code false} if the user is reporting the call as a non-nuisance call.
-     */
-    @RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
-    public void reportNuisanceCallStatus(@NonNull Uri handle, boolean isNuisanceCall) {
-        ITelecomService service = getTelecomService();
-        if (service != null) {
-            try {
-                service.reportNuisanceCallStatus(handle, isNuisanceCall,
-                        mContext.getOpPackageName());
-            } catch (RemoteException e) {
-                Log.e(TAG, "Error calling ITelecomService#showCallScreen", e);
-            }
-        }
-    }
-
-    /**
      * Handles {@link Intent#ACTION_CALL} intents trampolined from UserCallActivity.
      * @param intent The {@link Intent#ACTION_CALL} intent to handle.
      * @hide
diff --git a/telecomm/java/com/android/internal/telecom/ICallScreeningAdapter.aidl b/telecomm/java/com/android/internal/telecom/ICallScreeningAdapter.aidl
index 1160d27..3ee3285 100644
--- a/telecomm/java/com/android/internal/telecom/ICallScreeningAdapter.aidl
+++ b/telecomm/java/com/android/internal/telecom/ICallScreeningAdapter.aidl
@@ -17,7 +17,6 @@
 package com.android.internal.telecom;
 
 import android.content.ComponentName;
-import android.telecom.CallIdentification;
 
 /**
  * Internal remote callback interface for call screening services.
@@ -37,8 +36,4 @@
             boolean shouldAddToCallLog,
             boolean shouldShowNotification,
             in ComponentName componentName);
-
-    void provideCallIdentification(
-            String callId,
-            in CallIdentification callIdentification);
 }
diff --git a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
index 93eea56..a814c03 100644
--- a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
+++ b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
@@ -286,8 +286,6 @@
      */
     boolean isInEmergencyCall();
 
-    oneway void reportNuisanceCallStatus(in Uri address, boolean isNuisance, String callingPackage);
-
     /**
      * @see TelecomServiceImpl#handleCallIntent
      */
diff --git a/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java b/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java
index 339cc9d..106cd1f 100644
--- a/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java
+++ b/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java
@@ -501,7 +501,7 @@
 
         when(mPackageManager.getPackagesForUid(MOCK_UID1)).thenReturn(new String[]{});
         mObserver.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1);
-        mNetdServiceMonitor.expectPermission(INetd.NO_PERMISSIONS, new int[]{MOCK_UID1});
+        mNetdServiceMonitor.expectPermission(INetd.PERMISSION_UNINSTALLED, new int[]{MOCK_UID1});
     }
 
     @Test
@@ -515,7 +515,7 @@
         // Remove and install the same package to simulate the update action
         when(mPackageManager.getPackagesForUid(MOCK_UID1)).thenReturn(new String[]{});
         mObserver.onPackageRemoved(MOCK_PACKAGE1, MOCK_UID1);
-        mNetdServiceMonitor.expectPermission(INetd.NO_PERMISSIONS, new int[]{MOCK_UID1});
+        mNetdServiceMonitor.expectPermission(INetd.PERMISSION_UNINSTALLED, new int[]{MOCK_UID1});
 
         addPackage(MOCK_PACKAGE1, MOCK_UID1, new String[] {INTERNET});
         mNetdServiceMonitor.expectPermission(INetd.PERMISSION_INTERNET, new int[]{MOCK_UID1});
diff --git a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
index f576745..4262017 100644
--- a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
+++ b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
@@ -374,12 +374,11 @@
         }
 
         /**
-         * Create a network suggestion object use in
+         * Create a network suggestion object for use in
          * {@link WifiManager#addNetworkSuggestions(List)}.
          *
-         * See {@link WifiNetworkSuggestion}.
-         *<p>
-         * Note: Apps can set a combination of SSID using {@link #setSsid(String)} and BSSID
+         *<p class="note">
+         * <b>Note:</b> Apps can set a combination of SSID using {@link #setSsid(String)} and BSSID
          * using {@link #setBssid(MacAddress)} to provide more fine grained network suggestions to
          * the platform.
          * </p>
@@ -387,7 +386,8 @@
          * For example:
          * To provide credentials for one open, one WPA2 and one WPA3 network with their
          * corresponding SSID's:
-         * {@code
+         *
+         * <pre>{@code
          * final WifiNetworkSuggestion suggestion1 =
          *      new Builder()
          *      .setSsid("test111111")
@@ -403,19 +403,20 @@
          *      .setWpa3Passphrase("test6789")
          *      .build()
          * final List<WifiNetworkSuggestion> suggestionsList =
-         *      new ArrayList<WifiNetworkSuggestion> &#123;{
+         *      new ArrayList<WifiNetworkSuggestion> { {
          *          add(suggestion1);
          *          add(suggestion2);
          *          add(suggestion3);
-         *      }};
+         *      } };
          * final WifiManager wifiManager =
          *      context.getSystemService(Context.WIFI_SERVICE);
          * wifiManager.addNetworkSuggestions(suggestionsList);
-         * ...
-         * }
+         * // ...
+         * }</pre>
          *
-         * @return Instance of {@link WifiNetworkSuggestion}.
-         * @throws IllegalStateException on invalid params set.
+         * @return Instance of {@link WifiNetworkSuggestion}
+         * @throws IllegalStateException on invalid params set
+         * @see WifiNetworkSuggestion
          */
         public @NonNull WifiNetworkSuggestion build() {
             if (mSsid == null) {