Support B&R of notifications in non-system users

- Only backup and restore global state for the system user.
- Ignore user id in data for restore (as user 0 on source device could
be restoring to user 10 on target device for example).
- Don't restore managed services for managed users.

Bug: 123349308
Test: 1) atest $(find \
frameworks/base/services/tests/uiservicestests/src/com/android/server/notification \
-name '*Test.java')
2) Manual: Test backup and restore of DND configurations and app
notifications in system and non-system user.
TODO: More testing
Change-Id: Iea2933f2d8709f830a65815871ce974c00f6ce83
diff --git a/services/core/java/com/android/server/notification/ManagedServices.java b/services/core/java/com/android/server/notification/ManagedServices.java
index c222e69..cf09b8f 100644
--- a/services/core/java/com/android/server/notification/ManagedServices.java
+++ b/services/core/java/com/android/server/notification/ManagedServices.java
@@ -306,18 +306,21 @@
         }
     }
 
-    public void writeXml(XmlSerializer out, boolean forBackup) throws IOException {
+    public void writeXml(XmlSerializer out, boolean forBackup, int userId) throws IOException {
         out.startTag(null, getConfig().xmlTag);
 
         out.attribute(null, ATT_VERSION, String.valueOf(DB_VERSION));
 
         if (forBackup) {
-            trimApprovedListsAccordingToInstalledServices();
+            trimApprovedListsAccordingToInstalledServices(userId);
         }
 
         final int N = mApproved.size();
         for (int i = 0 ; i < N; i++) {
-            final int userId = mApproved.keyAt(i);
+            final int approvedUserId = mApproved.keyAt(i);
+            if (forBackup && approvedUserId != userId) {
+                continue;
+            }
             final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.valueAt(i);
             if (approvedByType != null) {
                 final int M = approvedByType.size();
@@ -328,14 +331,14 @@
                         String allowedItems = String.join(ENABLED_SERVICES_SEPARATOR, approved);
                         out.startTag(null, TAG_MANAGED_SERVICES);
                         out.attribute(null, ATT_APPROVED_LIST, allowedItems);
-                        out.attribute(null, ATT_USER_ID, Integer.toString(userId));
+                        out.attribute(null, ATT_USER_ID, Integer.toString(approvedUserId));
                         out.attribute(null, ATT_IS_PRIMARY, Boolean.toString(isPrimary));
                         out.endTag(null, TAG_MANAGED_SERVICES);
 
                         if (!forBackup && isPrimary) {
                             // Also write values to settings, for observers who haven't migrated yet
                             Settings.Secure.putStringForUser(mContext.getContentResolver(),
-                                    getConfig().secureSettingName, allowedItems, userId);
+                                    getConfig().secureSettingName, allowedItems, approvedUserId);
                         }
 
                     }
@@ -350,15 +353,12 @@
         loadAllowedComponentsFromSettings();
     }
 
-    public void readXml(XmlPullParser parser, Predicate<String> allowedManagedServicePackages)
+    public void readXml(
+            XmlPullParser parser,
+            Predicate<String> allowedManagedServicePackages,
+            boolean forRestore,
+            int userId)
             throws XmlPullParserException, IOException {
-        // upgrade xml
-        int xmlVersion = XmlUtils.readIntAttribute(parser, ATT_VERSION, 0);
-        final List<UserInfo> activeUsers = mUm.getUsers(true);
-        for (UserInfo userInfo : activeUsers) {
-            upgradeXml(xmlVersion, userInfo.getUserHandle().getIdentifier());
-        }
-
         // read grants
         int type;
         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
@@ -372,14 +372,16 @@
                     Slog.i(TAG, "Read " + mConfig.caption + " permissions from xml");
 
                     final String approved = XmlUtils.readStringAttribute(parser, ATT_APPROVED_LIST);
-                    final int userId = XmlUtils.readIntAttribute(parser, ATT_USER_ID, 0);
+                    // Ignore parser's user id for restore.
+                    final int resolvedUserId = forRestore
+                            ? userId : XmlUtils.readIntAttribute(parser, ATT_USER_ID, 0);
                     final boolean isPrimary =
                             XmlUtils.readBooleanAttribute(parser, ATT_IS_PRIMARY, true);
 
                     if (allowedManagedServicePackages == null ||
                             allowedManagedServicePackages.test(getPackageName(approved))) {
-                        if (mUm.getUserInfo(userId) != null) {
-                            addApprovedList(approved, userId, isPrimary);
+                        if (mUm.getUserInfo(resolvedUserId) != null) {
+                            addApprovedList(approved, resolvedUserId, isPrimary);
                         }
                         mUseXml = true;
                     }
@@ -389,8 +391,6 @@
         rebindServices(false, USER_ALL);
     }
 
-    protected void upgradeXml(final int xmlVersion, final int userId) {}
-
     private void loadAllowedComponentsFromSettings() {
         for (UserInfo user : mUm.getUsers()) {
             final ContentResolver cr = mContext.getContentResolver();
@@ -784,26 +784,23 @@
         return allowedPackages;
     }
 
-    private void trimApprovedListsAccordingToInstalledServices() {
-        int N = mApproved.size();
-        for (int i = 0 ; i < N; i++) {
-            final int userId = mApproved.keyAt(i);
-            final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.valueAt(i);
-            int M = approvedByType.size();
-            for (int j = 0; j < M; j++) {
-                final ArraySet<String> approved = approvedByType.valueAt(j);
-                int P = approved.size();
-                for (int k = P - 1; k >= 0; k--) {
-                    final String approvedPackageOrComponent = approved.valueAt(k);
-                    if (!isValidEntry(approvedPackageOrComponent, userId)){
-                        approved.removeAt(k);
-                        Slog.v(TAG, "Removing " + approvedPackageOrComponent
-                                + " from approved list; no matching services found");
-                    } else {
-                        if (DEBUG) {
-                            Slog.v(TAG, "Keeping " + approvedPackageOrComponent
-                                    + " on approved list; matching services found");
-                        }
+    private void trimApprovedListsAccordingToInstalledServices(int userId) {
+        final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.get(userId);
+        if (approvedByType == null) {
+            return;
+        }
+        for (int i = 0; i < approvedByType.size(); i++) {
+            final ArraySet<String> approved = approvedByType.valueAt(i);
+            for (int j = approved.size() - 1; j >= 0; j--) {
+                final String approvedPackageOrComponent = approved.valueAt(j);
+                if (!isValidEntry(approvedPackageOrComponent, userId)){
+                    approved.removeAt(j);
+                    Slog.v(TAG, "Removing " + approvedPackageOrComponent
+                            + " from approved list; no matching services found");
+                } else {
+                    if (DEBUG) {
+                        Slog.v(TAG, "Keeping " + approvedPackageOrComponent
+                                + " on approved list; matching services found");
                     }
                 }
             }
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index ba187c0..34d3681 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -213,6 +213,7 @@
 import com.android.server.notification.ManagedServices.ManagedServiceInfo;
 import com.android.server.notification.ManagedServices.UserProfiles;
 import com.android.server.pm.PackageManagerService;
+import com.android.server.pm.UserManagerService;
 import com.android.server.policy.PhoneWindowManager;
 import com.android.server.statusbar.StatusBarManagerInternal;
 import com.android.server.uri.UriGrantsManagerInternal;
@@ -538,30 +539,49 @@
         }
     }
 
-    void readPolicyXml(InputStream stream, boolean forRestore)
+    UserManagerService getUserManagerService() {
+        return UserManagerService.getInstance();
+    }
+
+    void readPolicyXml(InputStream stream, boolean forRestore, int userId)
             throws XmlPullParserException, NumberFormatException, IOException {
         final XmlPullParser parser = Xml.newPullParser();
         parser.setInput(stream, StandardCharsets.UTF_8.name());
         XmlUtils.beginDocument(parser, TAG_NOTIFICATION_POLICY);
         boolean migratedManagedServices = false;
+        boolean ineligibleForManagedServices = forRestore
+                && getUserManagerService().isManagedProfile(userId);
         int outerDepth = parser.getDepth();
         while (XmlUtils.nextElementWithin(parser, outerDepth)) {
             if (ZenModeConfig.ZEN_TAG.equals(parser.getName())) {
-                mZenModeHelper.readXml(parser, forRestore);
+                mZenModeHelper.readXml(parser, forRestore, userId);
             } else if (PreferencesHelper.TAG_RANKING.equals(parser.getName())){
-                mPreferencesHelper.readXml(parser, forRestore);
+                mPreferencesHelper.readXml(parser, forRestore, userId);
             }
             if (mListeners.getConfig().xmlTag.equals(parser.getName())) {
-                mListeners.readXml(parser, mAllowedManagedServicePackages);
+                if (ineligibleForManagedServices) {
+                    continue;
+                }
+                mListeners.readXml(parser, mAllowedManagedServicePackages, forRestore, userId);
                 migratedManagedServices = true;
             } else if (mAssistants.getConfig().xmlTag.equals(parser.getName())) {
-                mAssistants.readXml(parser, mAllowedManagedServicePackages);
+                if (ineligibleForManagedServices) {
+                    continue;
+                }
+                mAssistants.readXml(parser, mAllowedManagedServicePackages, forRestore, userId);
                 migratedManagedServices = true;
             } else if (mConditionProviders.getConfig().xmlTag.equals(parser.getName())) {
-                mConditionProviders.readXml(parser, mAllowedManagedServicePackages);
+                if (ineligibleForManagedServices) {
+                    continue;
+                }
+                mConditionProviders.readXml(
+                        parser, mAllowedManagedServicePackages, forRestore, userId);
                 migratedManagedServices = true;
             }
             if (LOCKSCREEN_ALLOW_SECURE_NOTIFICATIONS_TAG.equals(parser.getName())) {
+                if (forRestore && userId != UserHandle.USER_SYSTEM) {
+                    continue;
+                }
                 mLockScreenAllowSecureNotifications =
                         safeBoolean(parser.getAttributeValue(null,
                                         LOCKSCREEN_ALLOW_SECURE_NOTIFICATIONS_VALUE), true);
@@ -584,7 +604,7 @@
             InputStream infile = null;
             try {
                 infile = mPolicyFile.openRead();
-                readPolicyXml(infile, false /*forRestore*/);
+                readPolicyXml(infile, false /*forRestore*/, UserHandle.USER_ALL);
             } catch (FileNotFoundException e) {
                 // No data yet
                 // Load default managed services approvals
@@ -615,7 +635,7 @@
                 }
 
                 try {
-                    writePolicyXml(stream, false /*forBackup*/);
+                    writePolicyXml(stream, false /*forBackup*/, UserHandle.USER_ALL);
                     mPolicyFile.finishWrite(stream);
                 } catch (IOException e) {
                     Slog.w(TAG, "Failed to save policy file, restoring backup", e);
@@ -626,18 +646,21 @@
         });
     }
 
-    private void writePolicyXml(OutputStream stream, boolean forBackup) throws IOException {
+    private void writePolicyXml(OutputStream stream, boolean forBackup, int userId)
+            throws IOException {
         final XmlSerializer out = new FastXmlSerializer();
         out.setOutput(stream, StandardCharsets.UTF_8.name());
         out.startDocument(null, true);
         out.startTag(null, TAG_NOTIFICATION_POLICY);
         out.attribute(null, ATTR_VERSION, Integer.toString(DB_VERSION));
-        mZenModeHelper.writeXml(out, forBackup, null);
-        mPreferencesHelper.writeXml(out, forBackup);
-        mListeners.writeXml(out, forBackup);
-        mAssistants.writeXml(out, forBackup);
-        mConditionProviders.writeXml(out, forBackup);
-        writeSecureNotificationsPolicy(out);
+        mZenModeHelper.writeXml(out, forBackup, null, userId);
+        mPreferencesHelper.writeXml(out, forBackup, userId);
+        mListeners.writeXml(out, forBackup, userId);
+        mAssistants.writeXml(out, forBackup, userId);
+        mConditionProviders.writeXml(out, forBackup, userId);
+        if (!forBackup || userId == UserHandle.USER_SYSTEM) {
+            writeSecureNotificationsPolicy(out);
+        }
         out.endTag(null, TAG_NOTIFICATION_POLICY);
         out.endDocument();
     }
@@ -3497,14 +3520,9 @@
         public byte[] getBackupPayload(int user) {
             checkCallerIsSystem();
             if (DBG) Slog.d(TAG, "getBackupPayload u=" + user);
-            //TODO: http://b/22388012
-            if (user != USER_SYSTEM) {
-                Slog.w(TAG, "getBackupPayload: cannot backup policy for user " + user);
-                return null;
-            }
             final ByteArrayOutputStream baos = new ByteArrayOutputStream();
             try {
-                writePolicyXml(baos, true /*forBackup*/);
+                writePolicyXml(baos, true /*forBackup*/, user);
                 return baos.toByteArray();
             } catch (IOException e) {
                 Slog.w(TAG, "getBackupPayload: error writing payload for user " + user, e);
@@ -3521,14 +3539,9 @@
                 Slog.w(TAG, "applyRestore: no payload to restore for user " + user);
                 return;
             }
-            //TODO: http://b/22388012
-            if (user != USER_SYSTEM) {
-                Slog.w(TAG, "applyRestore: cannot restore policy for user " + user);
-                return;
-            }
             final ByteArrayInputStream bais = new ByteArrayInputStream(payload);
             try {
-                readPolicyXml(bais, true /*forRestore*/);
+                readPolicyXml(bais, true /*forRestore*/, user);
                 handleSavePolicyFile();
             } catch (NumberFormatException | XmlPullParserException | IOException e) {
                 Slog.w(TAG, "applyRestore: error reading payload", e);
diff --git a/services/core/java/com/android/server/notification/PreferencesHelper.java b/services/core/java/com/android/server/notification/PreferencesHelper.java
index 6ed4f5c..5555936 100644
--- a/services/core/java/com/android/server/notification/PreferencesHelper.java
+++ b/services/core/java/com/android/server/notification/PreferencesHelper.java
@@ -141,7 +141,7 @@
         syncChannelsBypassingDnd(mContext.getUserId());
     }
 
-    public void readXml(XmlPullParser parser, boolean forRestore)
+    public void readXml(XmlPullParser parser, boolean forRestore, int userId)
             throws XmlPullParserException, IOException {
         int type = parser.getEventType();
         if (type != XmlPullParser.START_TAG) return;
@@ -158,6 +158,9 @@
                 }
                 if (type == XmlPullParser.START_TAG) {
                     if (TAG_STATUS_ICONS.equals(tag)) {
+                        if (forRestore && userId != UserHandle.USER_SYSTEM) {
+                            continue;
+                        }
                         mHideSilentStatusBarIcons = XmlUtils.readBooleanAttribute(
                                 parser, ATT_HIDE_SILENT, DEFAULT_HIDE_SILENT_STATUS_BAR_ICONS);
                     } else if (TAG_PACKAGE.equals(tag)) {
@@ -166,9 +169,7 @@
                         if (!TextUtils.isEmpty(name)) {
                             if (forRestore) {
                                 try {
-                                    //TODO: http://b/22388012
-                                    uid = mPm.getPackageUidAsUser(name,
-                                            UserHandle.USER_SYSTEM);
+                                    uid = mPm.getPackageUidAsUser(name, userId);
                                 } catch (PackageManager.NameNotFoundException e) {
                                     // noop
                                 }
@@ -379,10 +380,11 @@
         r.channels.put(channel.getId(), channel);
     }
 
-    public void writeXml(XmlSerializer out, boolean forBackup) throws IOException {
+    public void writeXml(XmlSerializer out, boolean forBackup, int userId) throws IOException {
         out.startTag(null, TAG_RANKING);
         out.attribute(null, ATT_VERSION, Integer.toString(XML_VERSION));
-        if (mHideSilentStatusBarIcons != DEFAULT_HIDE_SILENT_STATUS_BAR_ICONS) {
+        if (mHideSilentStatusBarIcons != DEFAULT_HIDE_SILENT_STATUS_BAR_ICONS
+                && (!forBackup || userId == UserHandle.USER_SYSTEM)) {
             out.startTag(null, TAG_STATUS_ICONS);
             out.attribute(null, ATT_HIDE_SILENT, String.valueOf(mHideSilentStatusBarIcons));
             out.endTag(null, TAG_STATUS_ICONS);
@@ -392,8 +394,7 @@
             final int N = mPackagePreferences.size();
             for (int i = 0; i < N; i++) {
                 final PackagePreferences r = mPackagePreferences.valueAt(i);
-                //TODO: http://b/22388012
-                if (forBackup && UserHandle.getUserId(r.uid) != UserHandle.USER_SYSTEM) {
+                if (forBackup && UserHandle.getUserId(r.uid) != userId) {
                     continue;
                 }
                 final boolean hasNonDefaultSettings =
diff --git a/services/core/java/com/android/server/notification/ZenModeHelper.java b/services/core/java/com/android/server/notification/ZenModeHelper.java
index afc0b72..ea7bf2d2 100644
--- a/services/core/java/com/android/server/notification/ZenModeHelper.java
+++ b/services/core/java/com/android/server/notification/ZenModeHelper.java
@@ -104,7 +104,7 @@
     protected final RingerModeDelegate mRingerModeDelegate = new
             RingerModeDelegate();
     @VisibleForTesting protected final ZenModeConditions mConditions;
-    private final SparseArray<ZenModeConfig> mConfigs = new SparseArray<>();
+    @VisibleForTesting final SparseArray<ZenModeConfig> mConfigs = new SparseArray<>();
     private final Metrics mMetrics = new Metrics();
     private final ConditionProviders.Config mServiceConfig;
 
@@ -662,17 +662,14 @@
         }
     }
 
-    public void readXml(XmlPullParser parser, boolean forRestore)
+    public void readXml(XmlPullParser parser, boolean forRestore, int userId)
             throws XmlPullParserException, IOException {
         ZenModeConfig config = ZenModeConfig.readXml(parser);
         String reason = "readXml";
 
         if (config != null) {
             if (forRestore) {
-                //TODO: http://b/22388012
-                if (config.user != UserHandle.USER_SYSTEM) {
-                    return;
-                }
+                config.user = userId;
                 config.manualRule = null;  // don't restore the manual rule
             }
 
@@ -707,13 +704,15 @@
                 reason += ", reset to default rules";
             }
 
+            // Resolve user id for settings.
+            userId = userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId;
             if (config.version < ZenModeConfig.XML_VERSION) {
-                Settings.Secure.putInt(mContext.getContentResolver(),
-                        Settings.Secure.SHOW_ZEN_UPGRADE_NOTIFICATION, 1);
+                Settings.Secure.putIntForUser(mContext.getContentResolver(),
+                        Settings.Secure.SHOW_ZEN_UPGRADE_NOTIFICATION, 1, userId);
             } else {
                 // devices not restoring/upgrading already have updated zen settings
-                Settings.Secure.putInt(mContext.getContentResolver(),
-                        Settings.Secure.ZEN_SETTINGS_UPDATED, 1);
+                Settings.Secure.putIntForUser(mContext.getContentResolver(),
+                        Settings.Secure.ZEN_SETTINGS_UPDATED, 1, userId);
             }
             if (DEBUG) Log.d(TAG, reason);
             synchronized (mConfig) {
@@ -722,11 +721,11 @@
         }
     }
 
-    public void writeXml(XmlSerializer out, boolean forBackup, Integer version) throws IOException {
+    public void writeXml(XmlSerializer out, boolean forBackup, Integer version, int userId)
+            throws IOException {
         final int N = mConfigs.size();
         for (int i = 0; i < N; i++) {
-            //TODO: http://b/22388012
-            if (forBackup && mConfigs.keyAt(i) != UserHandle.USER_SYSTEM) {
+            if (forBackup && mConfigs.keyAt(i) != userId) {
                 continue;
             }
             mConfigs.valueAt(i).writeXml(out, version);
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
index 20f72bf..7a530df 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
@@ -74,6 +74,7 @@
 import java.io.ByteArrayOutputStream;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.List;
 import java.util.Set;
 
@@ -305,6 +306,82 @@
         }
     }
 
+    /** Test that restore ignores the user id attribute and applies the data to the target user. */
+    @Test
+    public void testReadXml_onlyRestoresForTargetUser() throws Exception {
+        for (int approvalLevel : new int[] {APPROVAL_BY_COMPONENT, APPROVAL_BY_PACKAGE}) {
+            ManagedServices service =
+                    new TestManagedServices(
+                            getContext(), mLock, mUserProfiles, mIpm, approvalLevel);
+            String testPackage = "user.test.package";
+            String testComponent = "user.test.component/C1";
+            String resolvedValue =
+                    (approvalLevel == APPROVAL_BY_COMPONENT) ? testComponent : testPackage;
+            XmlPullParser parser =
+                    getParserWithEntries(service, getXmlEntry(resolvedValue, 0, true));
+
+            service.readXml(parser, null, true, 10);
+
+            assertFalse(service.isPackageOrComponentAllowed(resolvedValue, 0));
+            assertTrue(service.isPackageOrComponentAllowed(resolvedValue, 10));
+        }
+    }
+
+    /** Test that backup only writes packages/components that belong to the target user. */
+    @Test
+    public void testWriteXml_onlyBackupsForTargetUser() throws Exception {
+        for (int approvalLevel : new int[] {APPROVAL_BY_COMPONENT, APPROVAL_BY_PACKAGE}) {
+            ManagedServices service =
+                    new TestManagedServices(
+                            getContext(), mLock, mUserProfiles, mIpm, approvalLevel);
+            // Set up components.
+            String testPackage0 = "user0.test.package";
+            String testComponent0 = "user0.test.component/C1";
+            String testPackage10 = "user10.test.package";
+            String testComponent10 = "user10.test.component/C1";
+            String resolvedValue0 =
+                    (approvalLevel == APPROVAL_BY_COMPONENT) ? testComponent0 : testPackage0;
+            String resolvedValue10 =
+                    (approvalLevel == APPROVAL_BY_COMPONENT) ? testComponent10 : testPackage10;
+            addExpectedServices(
+                    service, Collections.singletonList(service.getPackageName(resolvedValue0)), 0);
+            addExpectedServices(
+                    service,
+                    Collections.singletonList(service.getPackageName(resolvedValue10)),
+                    10);
+            XmlPullParser parser =
+                    getParserWithEntries(
+                            service,
+                            getXmlEntry(resolvedValue0, 0, true),
+                            getXmlEntry(resolvedValue10, 10, true));
+            service.readXml(parser, null, false, UserHandle.USER_ALL);
+
+            // Write backup.
+            XmlSerializer serializer = new FastXmlSerializer();
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            serializer.setOutput(new BufferedOutputStream(baos), "utf-8");
+            serializer.startDocument(null, true);
+            service.writeXml(serializer, true, 10);
+            serializer.endDocument();
+            serializer.flush();
+
+            // Reset values.
+            service.setPackageOrComponentEnabled(resolvedValue0, 0, true, false);
+            service.setPackageOrComponentEnabled(resolvedValue10, 10, true, false);
+
+            // Parse backup via restore.
+            XmlPullParser restoreParser = Xml.newPullParser();
+            restoreParser.setInput(
+                    new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray())), null);
+            restoreParser.nextTag();
+            service.readXml(restoreParser, null, true, 10);
+
+            assertFalse(service.isPackageOrComponentAllowed(resolvedValue0, 0));
+            assertFalse(service.isPackageOrComponentAllowed(resolvedValue0, 10));
+            assertTrue(service.isPackageOrComponentAllowed(resolvedValue10, 10));
+        }
+    }
+
     @Test
     public void testWriteXml_trimsMissingServices() throws Exception {
         for (int approvalLevel : new int[] {APPROVAL_BY_COMPONENT, APPROVAL_BY_PACKAGE}) {
@@ -348,7 +425,9 @@
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             serializer.setOutput(new BufferedOutputStream(baos), "utf-8");
             serializer.startDocument(null, true);
-            service.writeXml(serializer, true);
+            for (UserInfo userInfo : mUm.getUsers()) {
+                service.writeXml(serializer, true, userInfo.id);
+            }
             serializer.endDocument();
             serializer.flush();
 
@@ -356,7 +435,9 @@
             parser.setInput(new BufferedInputStream(
                     new ByteArrayInputStream(baos.toByteArray())), null);
             parser.nextTag();
-            service.readXml(parser, null);
+            for (UserInfo userInfo : mUm.getUsers()) {
+                service.readXml(parser, null, true, userInfo.id);
+            }
 
             verifyExpectedApprovedEntries(service);
             assertFalse(service.isPackageOrComponentAllowed("this.is.a.package.name", 0));
@@ -376,7 +457,7 @@
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             serializer.setOutput(new BufferedOutputStream(baos), "utf-8");
             serializer.startDocument(null, true);
-            service.writeXml(serializer, false);
+            service.writeXml(serializer, false, UserHandle.USER_ALL);
             serializer.endDocument();
             serializer.flush();
 
@@ -921,7 +1002,23 @@
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(xml.toString().getBytes())), null);
         parser.nextTag();
-        service.readXml(parser, null);
+        service.readXml(parser, null, false, UserHandle.USER_ALL);
+    }
+
+    private XmlPullParser getParserWithEntries(ManagedServices service, String... xmlEntries)
+            throws Exception {
+        final StringBuffer xml = new StringBuffer();
+        xml.append("<" + service.getConfig().xmlTag + ">\n");
+        for (String xmlEntry : xmlEntries) {
+            xml.append(xmlEntry);
+        }
+        xml.append("</" + service.getConfig().xmlTag + ">");
+
+        XmlPullParser parser = Xml.newPullParser();
+        parser.setInput(new BufferedInputStream(
+                new ByteArrayInputStream(xml.toString().getBytes())), null);
+        parser.nextTag();
+        return parser;
     }
 
     private void addExpectedServices(final ManagedServices service, final List<String> packages,
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationAssistantsTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationAssistantsTest.java
index 0b488c0..19b567f 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationAssistantsTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationAssistantsTest.java
@@ -33,6 +33,7 @@
 import android.content.pm.ResolveInfo;
 import android.content.pm.ServiceInfo;
 import android.content.pm.UserInfo;
+import android.os.UserHandle;
 import android.os.UserManager;
 import android.util.IntArray;
 import android.util.Xml;
@@ -129,7 +130,7 @@
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(xml.toString().getBytes())), null);
         parser.nextTag();
-        mAssistants.readXml(parser, null);
+        mAssistants.readXml(parser, null, false, UserHandle.USER_ALL);
 
         verify(mNm, never()).readDefaultAssistant(anyInt());
         verify(mAssistants, times(1)).addApprovedList(
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 4cae3b3..9ade196 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -123,6 +123,7 @@
 import com.android.server.lights.LightsManager;
 import com.android.server.notification.NotificationManagerService.NotificationAssistants;
 import com.android.server.notification.NotificationManagerService.NotificationListeners;
+import com.android.server.pm.UserManagerService;
 import com.android.server.uri.UriGrantsManagerInternal;
 import com.android.server.wm.WindowManagerInternal;
 
@@ -206,15 +207,19 @@
     UriGrantsManagerInternal mUgmInternal;
     @Mock
     AppOpsManager mAppOpsManager;
+    @Mock
+    private UserManagerService mUserMangerService;
 
     // Use a Testable subclass so we can simulate calls from the system without failing.
     private static class TestableNotificationManagerService extends NotificationManagerService {
         int countSystemChecks = 0;
         boolean isSystemUid = true;
         int countLogSmartSuggestionsVisible = 0;
+        UserManagerService mUserManagerService;
 
-        public TestableNotificationManagerService(Context context) {
+        TestableNotificationManagerService(Context context, UserManagerService userManagerService) {
             super(context);
+            mUserManagerService = userManagerService;
         }
 
         @Override
@@ -250,7 +255,10 @@
             countLogSmartSuggestionsVisible++;
         }
 
-
+        @Override
+        UserManagerService getUserManagerService() {
+            return mUserManagerService;
+        }
     }
 
     private class TestableToastCallback extends ITransientNotification.Stub {
@@ -277,7 +285,7 @@
         LocalServices.removeServiceForTest(WindowManagerInternal.class);
         LocalServices.addService(WindowManagerInternal.class, mWindowManagerInternal);
 
-        mService = new TestableNotificationManagerService(mContext);
+        mService = new TestableNotificationManagerService(mContext, mUserMangerService);
 
         // Use this testable looper.
         mTestableLooper = TestableLooper.get(this);
@@ -1847,7 +1855,7 @@
 
     @Test
     public void testHasCompanionDevice_noService() throws Exception {
-        mService = new TestableNotificationManagerService(mContext);
+        mService = new TestableNotificationManagerService(mContext, mUserMangerService);
 
         assertFalse(mService.hasCompanionDevice(mListener));
     }
@@ -2500,10 +2508,12 @@
                 + "</dnd_apps>"
                 + "</notification-policy>";
         mService.readPolicyXml(
-                new BufferedInputStream(new ByteArrayInputStream(upgradeXml.getBytes())), false);
-        verify(mListeners, times(1)).readXml(any(), any());
-        verify(mConditionProviders, times(1)).readXml(any(), any());
-        verify(mAssistants, times(1)).readXml(any(), any());
+                new BufferedInputStream(new ByteArrayInputStream(upgradeXml.getBytes())),
+                false,
+                UserHandle.USER_ALL);
+        verify(mListeners, times(1)).readXml(any(), any(), anyBoolean(), anyInt());
+        verify(mConditionProviders, times(1)).readXml(any(), any(), anyBoolean(), anyInt());
+        verify(mAssistants, times(1)).readXml(any(), any(), anyBoolean(), anyInt());
 
         // numbers are inflated for setup
         verify(mListeners, times(1)).migrateToXml();
@@ -2518,10 +2528,12 @@
                 + "<ranking></ranking>"
                 + "</notification-policy>";
         mService.readPolicyXml(
-                new BufferedInputStream(new ByteArrayInputStream(preupgradeXml.getBytes())), false);
-        verify(mListeners, never()).readXml(any(), any());
-        verify(mConditionProviders, never()).readXml(any(), any());
-        verify(mAssistants, never()).readXml(any(), any());
+                new BufferedInputStream(new ByteArrayInputStream(preupgradeXml.getBytes())),
+                false,
+                UserHandle.USER_ALL);
+        verify(mListeners, never()).readXml(any(), any(), anyBoolean(), anyInt());
+        verify(mConditionProviders, never()).readXml(any(), any(), anyBoolean(), anyInt());
+        verify(mAssistants, never()).readXml(any(), any(), anyBoolean(), anyInt());
 
         // numbers are inflated for setup
         verify(mListeners, times(2)).migrateToXml();
@@ -2530,6 +2542,53 @@
         verify(mAssistants, times(2)).ensureAssistant();
     }
 
+    @Test
+    public void testReadPolicyXml_doesNotRestoreManagedServicesForManagedUser() throws Exception {
+        final String policyXml = "<notification-policy version=\"1\">"
+                + "<ranking></ranking>"
+                + "<enabled_listeners>"
+                + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
+                + "</enabled_listeners>"
+                + "<enabled_assistants>"
+                + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
+                + "</enabled_assistants>"
+                + "<dnd_apps>"
+                + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
+                + "</dnd_apps>"
+                + "</notification-policy>";
+        when(mUserMangerService.isManagedProfile(10)).thenReturn(true);
+        mService.readPolicyXml(
+                new BufferedInputStream(new ByteArrayInputStream(policyXml.getBytes())),
+                true,
+                10);
+        verify(mListeners, never()).readXml(any(), any(), eq(true), eq(10));
+        verify(mConditionProviders, never()).readXml(any(), any(), eq(true), eq(10));
+        verify(mAssistants, never()).readXml(any(), any(), eq(true), eq(10));
+    }
+
+    @Test
+    public void testReadPolicyXml_restoresManagedServicesForNonManagedUser() throws Exception {
+        final String policyXml = "<notification-policy version=\"1\">"
+                + "<ranking></ranking>"
+                + "<enabled_listeners>"
+                + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
+                + "</enabled_listeners>"
+                + "<enabled_assistants>"
+                + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
+                + "</enabled_assistants>"
+                + "<dnd_apps>"
+                + "<service_listing approved=\"test\" user=\"10\" primary=\"true\" />"
+                + "</dnd_apps>"
+                + "</notification-policy>";
+        when(mUserMangerService.isManagedProfile(10)).thenReturn(false);
+        mService.readPolicyXml(
+                new BufferedInputStream(new ByteArrayInputStream(policyXml.getBytes())),
+                true,
+                10);
+        verify(mListeners, times(1)).readXml(any(), any(), eq(true), eq(10));
+        verify(mConditionProviders, times(1)).readXml(any(), any(), eq(true), eq(10));
+        verify(mAssistants, times(1)).readXml(any(), any(), eq(true), eq(10));
+    }
 
     @Test
     public void testLocaleChangedCallsUpdateDefaultZenModeRules() throws Exception {
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
index 47ec390..d46b41a 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
@@ -174,14 +174,14 @@
                 .build();
     }
 
-    private ByteArrayOutputStream writeXmlAndPurge(String pkg, int uid, boolean forBackup,
-            String... channelIds)
+    private ByteArrayOutputStream writeXmlAndPurge(
+            String pkg, int uid, boolean forBackup, int userId, String... channelIds)
             throws Exception {
         XmlSerializer serializer = new FastXmlSerializer();
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         serializer.setOutput(new BufferedOutputStream(baos), "utf-8");
         serializer.startDocument(null, true);
-        mHelper.writeXml(serializer, forBackup);
+        mHelper.writeXml(serializer, forBackup, userId);
         serializer.endDocument();
         serializer.flush();
         for (String channelId : channelIds) {
@@ -190,15 +190,17 @@
         return baos;
     }
 
-    private void loadStreamXml(ByteArrayOutputStream stream, boolean forRestore) throws Exception {
-        loadByteArrayXml(stream.toByteArray(), forRestore);
+    private void loadStreamXml(ByteArrayOutputStream stream, boolean forRestore, int userId)
+            throws Exception {
+        loadByteArrayXml(stream.toByteArray(), forRestore, userId);
     }
 
-    private void loadByteArrayXml(byte[] byteArray, boolean forRestore) throws Exception {
+    private void loadByteArrayXml(byte[] byteArray, boolean forRestore, int userId)
+            throws Exception {
         XmlPullParser parser = Xml.newPullParser();
         parser.setInput(new BufferedInputStream(new ByteArrayInputStream(byteArray)), null);
         parser.nextTag();
-        mHelper.readXml(parser, forRestore);
+        mHelper.readXml(parser, forRestore, userId);
     }
 
     private void compareChannels(NotificationChannel expected, NotificationChannel actual) {
@@ -242,6 +244,69 @@
         when(mMockZenModeHelper.getNotificationPolicy()).thenReturn(mTestNotificationPolicy);
     }
 
+    private void setUpPackageWithUid(String packageName, int uid) throws Exception {
+        when(mPm.getApplicationInfoAsUser(eq(packageName), anyInt(), anyInt()))
+                .thenReturn(new ApplicationInfo());
+        when(mPm.getPackageUidAsUser(eq(packageName), anyInt())).thenReturn(uid);
+    }
+
+    @Test
+    public void testWriteXml_onlyBackupsTargetUser() throws Exception {
+        // Setup package notifications.
+        String package0 = "test.package.user0";
+        int uid0 = 1001;
+        setUpPackageWithUid(package0, uid0);
+        NotificationChannel channel0 = new NotificationChannel("id0", "name0", IMPORTANCE_HIGH);
+        mHelper.createNotificationChannel(package0, uid0, channel0, true, false);
+
+        String package10 = "test.package.user10";
+        int uid10 = 1001001;
+        setUpPackageWithUid(package10, uid10);
+        NotificationChannel channel10 = new NotificationChannel("id10", "name10", IMPORTANCE_HIGH);
+        mHelper.createNotificationChannel(package10, uid10, channel10, true, false);
+
+        ByteArrayOutputStream baos = writeXmlAndPurge(package10, uid10, true, 10);
+
+        // Reset state.
+        mHelper.onPackagesChanged(true, 0, new String[] {package0}, new int[] {uid0});
+        mHelper.onPackagesChanged(true, 10, new String[] {package10}, new int[] {uid10});
+
+        // Parse backup data.
+        loadStreamXml(baos, true, 0);
+        loadStreamXml(baos, true, 10);
+
+        assertEquals(
+                channel10,
+                mHelper.getNotificationChannel(package10, uid10, channel10.getId(), false));
+        assertNull(mHelper.getNotificationChannel(package0, uid0, channel0.getId(), false));
+    }
+
+    @Test
+    public void testReadXml_onlyRestoresTargetUser() throws Exception {
+        // Setup package in user 0.
+        String package0 = "test.package.user0";
+        int uid0 = 1001;
+        setUpPackageWithUid(package0, uid0);
+        NotificationChannel channel0 = new NotificationChannel("id0", "name0", IMPORTANCE_HIGH);
+        mHelper.createNotificationChannel(package0, uid0, channel0, true, false);
+
+        ByteArrayOutputStream baos = writeXmlAndPurge(package0, uid0, true, 0);
+
+        // Reset state.
+        mHelper.onPackagesChanged(true, 0, new String[] {package0}, new int[] {uid0});
+
+        // Restore should convert the uid according to the target user.
+        int expectedUid = 1001001;
+        setUpPackageWithUid(package0, expectedUid);
+        // Parse backup data.
+        loadStreamXml(baos, true, 10);
+
+        assertEquals(
+                channel0,
+                mHelper.getNotificationChannel(package0, expectedUid, channel0.getId(), false));
+        assertNull(mHelper.getNotificationChannel(package0, uid0, channel0.getId(), false));
+    }
+
     @Test
     public void testChannelXml() throws Exception {
         NotificationChannelGroup ncg = new NotificationChannelGroup("1", "bye");
@@ -270,12 +335,13 @@
         mHelper.setShowBadge(PKG_N_MR1, UID_N_MR1, true);
         mHelper.setAppImportanceLocked(PKG_N_MR1, UID_N_MR1);
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, false, channel1.getId(),
-                channel2.getId(), NotificationChannel.DEFAULT_CHANNEL_ID);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, false,
+                UserHandle.USER_ALL, channel1.getId(), channel2.getId(),
+                NotificationChannel.DEFAULT_CHANNEL_ID);
         mHelper.onPackagesChanged(true, UserHandle.myUserId(), new String[]{PKG_N_MR1}, new int[]{
                 UID_N_MR1});
 
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         assertTrue(mHelper.canShowBadge(PKG_N_MR1, UID_N_MR1));
         assertTrue(mHelper.getIsAppImportanceLocked(PKG_N_MR1, UID_N_MR1));
@@ -337,14 +403,15 @@
 
         mHelper.setImportance(PKG_O, UID_O, IMPORTANCE_NONE);
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true, channel1.getId(),
-                channel2.getId(), channel3.getId(), NotificationChannel.DEFAULT_CHANNEL_ID);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true,
+                UserHandle.USER_SYSTEM, channel1.getId(), channel2.getId(), channel3.getId(),
+                NotificationChannel.DEFAULT_CHANNEL_ID);
         mHelper.onPackagesChanged(true, UserHandle.myUserId(), new String[]{PKG_N_MR1, PKG_O},
                 new int[]{UID_N_MR1, UID_O});
 
         mHelper.setShowBadge(PKG_O, UID_O, true);
 
-        loadStreamXml(baos, true);
+        loadStreamXml(baos, true, UserHandle.USER_SYSTEM);
 
         assertEquals(IMPORTANCE_NONE, mHelper.getImportance(PKG_O, UID_O));
         assertTrue(mHelper.canShowBadge(PKG_N_MR1, UID_N_MR1));
@@ -385,10 +452,11 @@
         channel.setSound(SOUND_URI, mAudioAttributes);
         mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1, channel, true, false);
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true, channel.getId());
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true,
+                UserHandle.USER_SYSTEM, channel.getId());
 
         // Testing that in restore we are given the canonical version
-        loadStreamXml(baos, true);
+        loadStreamXml(baos, true, UserHandle.USER_SYSTEM);
         verify(mTestIContentProvider).uncanonicalize(any(), eq(CANONICAL_SOUND_URI));
     }
 
@@ -410,9 +478,10 @@
                 new NotificationChannel("id", "name", IMPORTANCE_LOW);
         channel.setSound(SOUND_URI, mAudioAttributes);
         mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1, channel, true, false);
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true, channel.getId());
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true,
+                UserHandle.USER_SYSTEM, channel.getId());
 
-        loadStreamXml(baos, true);
+        loadStreamXml(baos, true, UserHandle.USER_SYSTEM);
 
         NotificationChannel actualChannel = mHelper.getNotificationChannel(
                 PKG_N_MR1, UID_N_MR1, channel.getId(), false);
@@ -431,9 +500,10 @@
                 new NotificationChannel("id", "name", IMPORTANCE_LOW);
         channel.setSound(SOUND_URI, mAudioAttributes);
         mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1, channel, true, false);
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true, channel.getId());
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true,
+                UserHandle.USER_SYSTEM, channel.getId());
 
-        loadStreamXml(baos, true);
+        loadStreamXml(baos, true, UserHandle.USER_SYSTEM);
 
         NotificationChannel actualChannel = mHelper.getNotificationChannel(
                 PKG_N_MR1, UID_N_MR1, channel.getId(), false);
@@ -460,7 +530,8 @@
                 + "</package>\n"
                 + "</ranking>\n";
 
-        loadByteArrayXml(backupWithUncanonicalizedSoundUri.getBytes(), true);
+        loadByteArrayXml(
+                backupWithUncanonicalizedSoundUri.getBytes(), true, UserHandle.USER_SYSTEM);
 
         NotificationChannel actualChannel = mHelper.getNotificationChannel(PKG_N_MR1, UID_N_MR1, id, false);
         assertEquals(Settings.System.DEFAULT_NOTIFICATION_URI, actualChannel.getSound());
@@ -472,9 +543,10 @@
                 new NotificationChannel("id", "name", IMPORTANCE_LOW);
         channel.setSound(null, mAudioAttributes);
         mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1, channel, true, false);
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true, channel.getId());
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true,
+                UserHandle.USER_SYSTEM, channel.getId());
 
-        loadStreamXml(baos, true);
+        loadStreamXml(baos, true, UserHandle.USER_SYSTEM);
 
         NotificationChannel actualChannel = mHelper.getNotificationChannel(
                 PKG_N_MR1, UID_N_MR1, channel.getId(), false);
@@ -504,8 +576,9 @@
         assertEquals(channel2,
                 mHelper.getNotificationChannel(PKG_N_MR1, UID_N_MR1, channel2.getId(), false));
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true, channel1.getId(),
-                channel2.getId(), channel3.getId(), NotificationChannel.DEFAULT_CHANNEL_ID);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, true,
+                UserHandle.USER_SYSTEM, channel1.getId(), channel2.getId(), channel3.getId(),
+                NotificationChannel.DEFAULT_CHANNEL_ID);
         mHelper.onPackagesChanged(true, UserHandle.myUserId(), new String[]{PKG_N_MR1}, new int[]{
                 UID_N_MR1});
 
@@ -513,7 +586,7 @@
         parser.setInput(new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray())),
                 null);
         parser.nextTag();
-        mHelper.readXml(parser, true);
+        mHelper.readXml(parser, true, UserHandle.USER_SYSTEM);
 
         assertNull(mHelper.getNotificationChannel(PKG_N_MR1, UID_N_MR1, channel1.getId(), false));
         assertNull(mHelper.getNotificationChannel(PKG_N_MR1, UID_N_MR1, channel3.getId(), false));
@@ -525,9 +598,9 @@
     @Test
     public void testChannelXml_defaultChannelLegacyApp_noUserSettings() throws Exception {
         ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, false,
-                NotificationChannel.DEFAULT_CHANNEL_ID);
+                UserHandle.USER_ALL, NotificationChannel.DEFAULT_CHANNEL_ID);
 
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         final NotificationChannel updated = mHelper.getNotificationChannel(PKG_N_MR1, UID_N_MR1,
                 NotificationChannel.DEFAULT_CHANNEL_ID, false);
@@ -546,9 +619,9 @@
         mHelper.updateNotificationChannel(PKG_N_MR1, UID_N_MR1, defaultChannel, true);
 
         ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, false,
-                NotificationChannel.DEFAULT_CHANNEL_ID);
+                UserHandle.USER_ALL, NotificationChannel.DEFAULT_CHANNEL_ID);
 
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         assertEquals(NotificationManager.IMPORTANCE_LOW, mHelper.getNotificationChannel(
                 PKG_N_MR1, UID_N_MR1, NotificationChannel.DEFAULT_CHANNEL_ID, false).getImportance());
@@ -568,7 +641,7 @@
         parser.setInput(new BufferedInputStream(new ByteArrayInputStream(preupgradeXml.getBytes())),
                 null);
         parser.nextTag();
-        mHelper.readXml(parser, false);
+        mHelper.readXml(parser, false, UserHandle.USER_ALL);
 
         final NotificationChannel updated1 =
             mHelper.getNotificationChannel(PKG_N_MR1, UID_N_MR1, NotificationChannel.DEFAULT_CHANNEL_ID, false);
@@ -590,13 +663,13 @@
         final NotificationChannel defaultChannel = mHelper.getNotificationChannel(
                 PKG_N_MR1, UID_N_MR1, NotificationChannel.DEFAULT_CHANNEL_ID, false);
         assertTrue(defaultChannel != null);
-        ByteArrayOutputStream baos =
-                writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, false, NotificationChannel.DEFAULT_CHANNEL_ID);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, false,
+                UserHandle.USER_ALL, NotificationChannel.DEFAULT_CHANNEL_ID);
         // Load package at higher sdk.
         final ApplicationInfo upgraded = new ApplicationInfo();
         upgraded.targetSdkVersion = Build.VERSION_CODES.N_MR1 + 1;
         when(mPm.getApplicationInfoAsUser(eq(PKG_N_MR1), anyInt(), anyInt())).thenReturn(upgraded);
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         // Default Channel should be gone.
         assertEquals(null, mHelper.getNotificationChannel(PKG_N_MR1, UID_N_MR1,
@@ -608,13 +681,13 @@
         mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1,
                 new NotificationChannel("bananas", "bananas", IMPORTANCE_LOW), true, false);
         ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, false,
-                NotificationChannel.DEFAULT_CHANNEL_ID, "bananas");
+                UserHandle.USER_ALL, NotificationChannel.DEFAULT_CHANNEL_ID, "bananas");
 
         // Load package at higher sdk.
         final ApplicationInfo upgraded = new ApplicationInfo();
         upgraded.targetSdkVersion = Build.VERSION_CODES.N_MR1 + 1;
         when(mPm.getApplicationInfoAsUser(eq(PKG_N_MR1), anyInt(), anyInt())).thenReturn(upgraded);
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         // Default Channel should be gone.
         assertEquals(null, mHelper.getNotificationChannel(PKG_N_MR1, UID_N_MR1,
@@ -624,11 +697,11 @@
     @Test
     public void testLoadingOldChannelsDoesNotDeleteNewlyCreatedChannels() throws Exception {
         ByteArrayOutputStream baos = writeXmlAndPurge(PKG_N_MR1, UID_N_MR1, false,
-                NotificationChannel.DEFAULT_CHANNEL_ID, "bananas");
+                UserHandle.USER_ALL, NotificationChannel.DEFAULT_CHANNEL_ID, "bananas");
         mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1,
                 new NotificationChannel("bananas", "bananas", IMPORTANCE_LOW), true, false);
 
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         // Should still have the newly created channel that wasn't in the xml.
         assertTrue(mHelper.getNotificationChannel(PKG_N_MR1, UID_N_MR1, "bananas", false) != null);
@@ -2007,9 +2080,9 @@
 
     @Test
     public void testXml_statusBarIcons_default() throws Exception {
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false, UserHandle.USER_ALL);
         mHelper = new PreferencesHelper(getContext(), mPm, mHandler, mMockZenModeHelper);
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         assertEquals(PreferencesHelper.DEFAULT_HIDE_SILENT_STATUS_BAR_ICONS,
                 mHelper.shouldHideSilentStatusIcons());
@@ -2019,9 +2092,9 @@
     public void testXml_statusBarIcons() throws Exception {
         mHelper.setHideSilentStatusIcons(!PreferencesHelper.DEFAULT_HIDE_SILENT_STATUS_BAR_ICONS);
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false, UserHandle.USER_ALL);
         mHelper = new PreferencesHelper(getContext(), mPm, mHandler, mMockZenModeHelper);
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         assertEquals(!PreferencesHelper.DEFAULT_HIDE_SILENT_STATUS_BAR_ICONS,
                 mHelper.shouldHideSilentStatusIcons());
@@ -2115,9 +2188,9 @@
     public void testDelegateXml_noDelegate() throws Exception {
         mHelper.setImportance(PKG_O, UID_O, IMPORTANCE_UNSPECIFIED);
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false, UserHandle.USER_ALL);
         mHelper = new PreferencesHelper(getContext(), mPm, mHandler, mMockZenModeHelper);
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         assertNull(mHelper.getNotificationDelegate(PKG_O, UID_O));
     }
@@ -2126,9 +2199,9 @@
     public void testDelegateXml_delegate() throws Exception {
         mHelper.setNotificationDelegate(PKG_O, UID_O, "other", 53);
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false, UserHandle.USER_ALL);
         mHelper = new PreferencesHelper(getContext(), mPm, mHandler, mMockZenModeHelper);
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         assertEquals("other", mHelper.getNotificationDelegate(PKG_O, UID_O));
     }
@@ -2138,9 +2211,9 @@
         mHelper.setNotificationDelegate(PKG_O, UID_O, "other", 53);
         mHelper.revokeNotificationDelegate(PKG_O, UID_O);
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false, UserHandle.USER_ALL);
         mHelper = new PreferencesHelper(getContext(), mPm, mHandler, mMockZenModeHelper);
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         assertNull(mHelper.getNotificationDelegate(PKG_O, UID_O));
     }
@@ -2150,9 +2223,9 @@
         mHelper.setNotificationDelegate(PKG_O, UID_O, "other", 53);
         mHelper.toggleNotificationDelegate(PKG_O, UID_O, false);
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false, UserHandle.USER_ALL);
         mHelper = new PreferencesHelper(getContext(), mPm, mHandler, mMockZenModeHelper);
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         // appears disabled
         assertNull(mHelper.getNotificationDelegate(PKG_O, UID_O));
@@ -2168,9 +2241,9 @@
         mHelper.toggleNotificationDelegate(PKG_O, UID_O, false);
         mHelper.revokeNotificationDelegate(PKG_O, UID_O);
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false, UserHandle.USER_ALL);
         mHelper = new PreferencesHelper(getContext(), mPm, mHandler, mMockZenModeHelper);
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         // appears disabled
         assertNull(mHelper.getNotificationDelegate(PKG_O, UID_O));
@@ -2186,9 +2259,9 @@
     public void testAllowBubbles_defaults() throws Exception {
         assertTrue(mHelper.areBubblesAllowed(PKG_O, UID_O));
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false, UserHandle.USER_ALL);
         mHelper = new PreferencesHelper(getContext(), mPm, mHandler, mMockZenModeHelper);
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         assertTrue(mHelper.areBubblesAllowed(PKG_O, UID_O));
         assertEquals(0, mHelper.getAppLockedFields(PKG_O, UID_O));
@@ -2201,9 +2274,9 @@
         assertEquals(PreferencesHelper.LockableAppFields.USER_LOCKED_BUBBLE,
                 mHelper.getAppLockedFields(PKG_O, UID_O));
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false);
+        ByteArrayOutputStream baos = writeXmlAndPurge(PKG_O, UID_O, false, UserHandle.USER_ALL);
         mHelper = new PreferencesHelper(getContext(), mPm, mHandler, mMockZenModeHelper);
-        loadStreamXml(baos, false);
+        loadStreamXml(baos, false, UserHandle.USER_ALL);
 
         assertFalse(mHelper.areBubblesAllowed(PKG_O, UID_O));
         assertEquals(PreferencesHelper.LockableAppFields.USER_LOCKED_BUBBLE,
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
index a459b0a..08d8333 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
@@ -25,6 +25,7 @@
 import static junit.framework.Assert.assertFalse;
 import static junit.framework.TestCase.assertTrue;
 
+import static org.junit.Assert.assertNotEquals;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyInt;
@@ -56,6 +57,7 @@
 import android.media.AudioSystem;
 import android.media.VolumePolicy;
 import android.net.Uri;
+import android.os.UserHandle;
 import android.provider.Settings;
 import android.provider.Settings.Global;
 import android.service.notification.Condition;
@@ -158,19 +160,58 @@
         return new XmlResourceParserImpl(parser);
     }
 
-    private ByteArrayOutputStream writeXmlAndPurge(boolean forBackup, Integer version)
+    private ByteArrayOutputStream writeXmlAndPurge(Integer version) throws Exception {
+        XmlSerializer serializer = new FastXmlSerializer();
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        serializer.setOutput(new BufferedOutputStream(baos), "utf-8");
+        serializer.startDocument(null, true);
+        mZenModeHelperSpy.writeXml(serializer, false, version, UserHandle.USER_ALL);
+        serializer.endDocument();
+        serializer.flush();
+        mZenModeHelperSpy.setConfig(new ZenModeConfig(), null, "writing xml");
+        return baos;
+    }
+
+    private ByteArrayOutputStream writeXmlAndPurgeForUser(Integer version, int userId)
             throws Exception {
         XmlSerializer serializer = new FastXmlSerializer();
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         serializer.setOutput(new BufferedOutputStream(baos), "utf-8");
         serializer.startDocument(null, true);
-        mZenModeHelperSpy.writeXml(serializer, forBackup, version);
+        mZenModeHelperSpy.writeXml(serializer, true, version, userId);
         serializer.endDocument();
         serializer.flush();
-        mZenModeHelperSpy.setConfig(new ZenModeConfig(), null, "writing xml");
+        ZenModeConfig newConfig = new ZenModeConfig();
+        newConfig.user = userId;
+        mZenModeHelperSpy.setConfig(newConfig, null, "writing xml");
         return baos;
     }
 
+    private XmlPullParser getParserForByteStream(ByteArrayOutputStream baos) throws Exception {
+        XmlPullParser parser = Xml.newPullParser();
+        parser.setInput(
+                new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray())), null);
+        parser.nextTag();
+        return parser;
+    }
+
+    private ArrayMap<String, ZenModeConfig.ZenRule> getCustomAutomaticRules() {
+        ArrayMap<String, ZenModeConfig.ZenRule> automaticRules = new ArrayMap<>();
+        ZenModeConfig.ZenRule customRule = new ZenModeConfig.ZenRule();
+        final ScheduleInfo customRuleInfo = new ScheduleInfo();
+        customRule.enabled = true;
+        customRule.creationTime = 0;
+        customRule.id = "customRule";
+        customRule.name = "Custom Rule";
+        customRule.zenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
+        customRule.conditionId = ZenModeConfig.toScheduleConditionId(customRuleInfo);
+        customRule.configurationActivity =
+                new ComponentName("android", "ScheduleConditionProvider");
+        customRule.pkg = customRule.configurationActivity.getPackageName();
+        automaticRules.put("customRule", customRule);
+        return automaticRules;
+    }
+
     @Test
     public void testZenOff_NoMuteApplied() {
         mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_OFF;
@@ -639,50 +680,86 @@
 
         ZenModeConfig expected = mZenModeHelperSpy.mConfig.copy();
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(false, null);
-        XmlPullParser parser = Xml.newPullParser();
-        parser.setInput(new BufferedInputStream(
-                new ByteArrayInputStream(baos.toByteArray())), null);
-        parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        ByteArrayOutputStream baos = writeXmlAndPurge(null);
+        XmlPullParser parser = getParserForByteStream(baos);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         assertEquals("Config mismatch: current vs expected: "
                 + mZenModeHelperSpy.mConfig.diff(expected), expected, mZenModeHelperSpy.mConfig);
     }
 
     @Test
-    public void testReadXmlRestore() throws Exception {
+    public void testWriteXml_onlyBackupsTargetUser() throws Exception {
+        // Setup configs for user 10 and 11.
         setupZenConfig();
+        ZenModeConfig config10 = mZenModeHelperSpy.mConfig.copy();
+        config10.user = 10;
+        config10.allowAlarms = true;
+        config10.allowMedia = true;
+        mZenModeHelperSpy.setConfig(config10, null, "writeXml");
+        ZenModeConfig config11 = mZenModeHelperSpy.mConfig.copy();
+        config11.user = 11;
+        config11.allowAlarms = false;
+        config11.allowMedia = false;
+        mZenModeHelperSpy.setConfig(config11, null, "writeXml");
 
+        // Backup user 10 and reset values.
+        ByteArrayOutputStream baos = writeXmlAndPurgeForUser(null, 10);
+        ZenModeConfig newConfig11 = new ZenModeConfig();
+        newConfig11.user = 11;
+        mZenModeHelperSpy.mConfigs.put(11, newConfig11);
+
+        // Parse backup data.
+        XmlPullParser parser = getParserForByteStream(baos);
+        mZenModeHelperSpy.readXml(parser, true, 10);
+        mZenModeHelperSpy.readXml(parser, true, 11);
+
+        ZenModeConfig actual = mZenModeHelperSpy.mConfigs.get(10);
+        assertEquals(
+                "Config mismatch: current vs expected: " + actual.diff(config10), config10, actual);
+        assertNotEquals("Expected config mismatch", config11, mZenModeHelperSpy.mConfigs.get(11));
+    }
+
+    @Test
+    public void testReadXmlRestore_forSystemUser() throws Exception {
+        setupZenConfig();
         // one enabled automatic rule
-        ArrayMap<String, ZenModeConfig.ZenRule> automaticRules = new ArrayMap<>();
-        ZenModeConfig.ZenRule customRule = new ZenModeConfig.ZenRule();
-        final ScheduleInfo customRuleInfo = new ScheduleInfo();
-        customRule.enabled = true;
-        customRule.creationTime = 0;
-        customRule.id = "customRule";
-        customRule.name = "Custom Rule";
-        customRule.zenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
-        customRule.conditionId = ZenModeConfig.toScheduleConditionId(customRuleInfo);
-        customRule.configurationActivity
-                = new ComponentName("android", "ScheduleConditionProvider");
-        customRule.pkg = customRule.configurationActivity.getPackageName();
-        automaticRules.put("customRule", customRule);
-        mZenModeHelperSpy.mConfig.automaticRules = automaticRules;
-
+        mZenModeHelperSpy.mConfig.automaticRules = getCustomAutomaticRules();
         ZenModeConfig original = mZenModeHelperSpy.mConfig.copy();
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(false, null);
-        XmlPullParser parser = Xml.newPullParser();
-        parser.setInput(new BufferedInputStream(
-                new ByteArrayInputStream(baos.toByteArray())), null);
-        parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, true);
+        ByteArrayOutputStream baos = writeXmlAndPurgeForUser(null, UserHandle.USER_SYSTEM);
+        XmlPullParser parser = getParserForByteStream(baos);
+        mZenModeHelperSpy.readXml(parser, true, UserHandle.USER_SYSTEM);
+
         assertEquals("Config mismatch: current vs original: "
                 + mZenModeHelperSpy.mConfig.diff(original), original, mZenModeHelperSpy.mConfig);
         assertEquals(original.hashCode(), mZenModeHelperSpy.mConfig.hashCode());
     }
 
+    /** Restore should ignore the data's user id and restore for the target user. */
+    @Test
+    public void testReadXmlRestore_forNonSystemUser() throws Exception {
+        // Setup config.
+        setupZenConfig();
+        mZenModeHelperSpy.mConfig.automaticRules = getCustomAutomaticRules();
+        ZenModeConfig expected = mZenModeHelperSpy.mConfig.copy();
+
+        // Backup data for user 0.
+        ByteArrayOutputStream baos = writeXmlAndPurgeForUser(null, UserHandle.USER_SYSTEM);
+
+        // Restore data for user 10.
+        XmlPullParser parser = getParserForByteStream(baos);
+        mZenModeHelperSpy.readXml(parser, true, 10);
+
+        ZenModeConfig actual = mZenModeHelperSpy.mConfigs.get(10);
+        expected.user = 10;
+        assertEquals(
+                "Config mismatch: current vs original: " + actual.diff(expected), expected, actual);
+        assertEquals(expected.hashCode(), actual.hashCode());
+        expected.user = 0;
+        assertNotEquals(expected, mZenModeHelperSpy.mConfig);
+    }
+
     @Test
     public void testWriteXmlWithZenPolicy() throws Exception {
         final String ruleId = "customRule";
@@ -715,12 +792,12 @@
 
         ZenModeConfig expected = mZenModeHelperSpy.mConfig.copy();
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(false, null);
+        ByteArrayOutputStream baos = writeXmlAndPurge(null);
         XmlPullParser parser = Xml.newPullParser();
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(baos.toByteArray())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         ZenModeConfig.ZenRule original = expected.automaticRules.get(ruleId);
         ZenModeConfig.ZenRule current = mZenModeHelperSpy.mConfig.automaticRules.get(ruleId);
@@ -729,7 +806,7 @@
     }
 
     @Test
-    public void testReadXmlRestoreWithZenPolicy() throws Exception {
+    public void testReadXmlRestoreWithZenPolicy_forSystemUser() throws Exception {
         final String ruleId = "customRule";
         setupZenConfig();
 
@@ -756,12 +833,9 @@
 
         ZenModeConfig expected = mZenModeHelperSpy.mConfig.copy();
 
-        ByteArrayOutputStream baos = writeXmlAndPurge(false, null);
-        XmlPullParser parser = Xml.newPullParser();
-        parser.setInput(new BufferedInputStream(
-                new ByteArrayInputStream(baos.toByteArray())), null);
-        parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, true);
+        ByteArrayOutputStream baos = writeXmlAndPurgeForUser(null, UserHandle.USER_SYSTEM);
+        XmlPullParser parser = getParserForByteStream(baos);
+        mZenModeHelperSpy.readXml(parser, true, UserHandle.USER_SYSTEM);
 
         ZenModeConfig.ZenRule original = expected.automaticRules.get(ruleId);
         ZenModeConfig.ZenRule current = mZenModeHelperSpy.mConfig.automaticRules.get(ruleId);
@@ -786,12 +860,12 @@
         mZenModeHelperSpy.mConfig.automaticRules = enabledAutoRule;
 
         // set previous version
-        ByteArrayOutputStream baos = writeXmlAndPurge(false, 5);
+        ByteArrayOutputStream baos = writeXmlAndPurge(5);
         XmlPullParser parser = Xml.newPullParser();
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(baos.toByteArray())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         assertTrue(mZenModeHelperSpy.mConfig.automaticRules.containsKey("customRule"));
         setupZenConfigMaintained();
@@ -811,7 +885,7 @@
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(xml.getBytes())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         assertEquals(0, mZenModeHelperSpy.mConfig.suppressedVisualEffects);
 
@@ -827,7 +901,7 @@
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(xml.getBytes())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         assertEquals(0, mZenModeHelperSpy.mConfig.suppressedVisualEffects);
     }
@@ -846,7 +920,7 @@
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(xml.getBytes())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         assertEquals(0, mZenModeHelperSpy.mConfig.suppressedVisualEffects);
     }
@@ -865,7 +939,7 @@
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(xml.getBytes())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         assertEquals(SUPPRESSED_EFFECT_FULL_SCREEN_INTENT
                         | SUPPRESSED_EFFECT_LIGHTS
@@ -884,7 +958,7 @@
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(xml.getBytes())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         assertEquals(SUPPRESSED_EFFECT_PEEK, mZenModeHelperSpy.mConfig.suppressedVisualEffects);
 
@@ -900,7 +974,7 @@
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(xml.getBytes())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         assertEquals(SUPPRESSED_EFFECT_FULL_SCREEN_INTENT | SUPPRESSED_EFFECT_LIGHTS,
                 mZenModeHelperSpy.mConfig.suppressedVisualEffects);
@@ -915,12 +989,12 @@
         mZenModeHelperSpy.mConfig.automaticRules = new ArrayMap<>();
 
         // set previous version
-        ByteArrayOutputStream baos = writeXmlAndPurge(false, 5);
+        ByteArrayOutputStream baos = writeXmlAndPurge(5);
         XmlPullParser parser = Xml.newPullParser();
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(baos.toByteArray())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         // check default rules
         ArrayMap<String, ZenModeConfig.ZenRule> rules = mZenModeHelperSpy.mConfig.automaticRules;
@@ -951,12 +1025,12 @@
         mZenModeHelperSpy.mConfig.automaticRules = disabledAutoRule;
 
         // set previous version
-        ByteArrayOutputStream baos = writeXmlAndPurge(false, 5);
+        ByteArrayOutputStream baos = writeXmlAndPurge(5);
         XmlPullParser parser = Xml.newPullParser();
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(baos.toByteArray())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         // check default rules
         ArrayMap<String, ZenModeConfig.ZenRule> rules = mZenModeHelperSpy.mConfig.automaticRules;
@@ -1003,12 +1077,12 @@
         mZenModeHelperSpy.mConfig.automaticRules = automaticRules;
 
         // set previous version
-        ByteArrayOutputStream baos = writeXmlAndPurge(false, 5);
+        ByteArrayOutputStream baos = writeXmlAndPurge(5);
         XmlPullParser parser = Xml.newPullParser();
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(baos.toByteArray())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         // check default rules
         ArrayMap<String, ZenModeConfig.ZenRule> rules = mZenModeHelperSpy.mConfig.automaticRules;
@@ -1072,12 +1146,12 @@
         mZenModeHelperSpy.mConfig.automaticRules = automaticRules;
 
         // set previous version
-        ByteArrayOutputStream baos = writeXmlAndPurge(false, 5);
+        ByteArrayOutputStream baos = writeXmlAndPurge(5);
         XmlPullParser parser = Xml.newPullParser();
         parser.setInput(new BufferedInputStream(
                 new ByteArrayInputStream(baos.toByteArray())), null);
         parser.nextTag();
-        mZenModeHelperSpy.readXml(parser, false);
+        mZenModeHelperSpy.readXml(parser, false, UserHandle.USER_ALL);
 
         // check default rules
         ArrayMap<String, ZenModeConfig.ZenRule> rules = mZenModeHelperSpy.mConfig.automaticRules;