Fixed several time related states for secondary users

The 24 hour setting was not respected correctly. Also
fixed a bug where the next alarm would not display itself
in the QS panel.

Bug: 16239208
Change-Id: I89734f783912dead5831db49db53fba04dbf54ee
diff --git a/core/java/android/service/notification/ZenModeConfig.java b/core/java/android/service/notification/ZenModeConfig.java
index 36401eb..ce28d0a 100644
--- a/core/java/android/service/notification/ZenModeConfig.java
+++ b/core/java/android/service/notification/ZenModeConfig.java
@@ -474,13 +474,14 @@
         return downtime;
     }
 
-    public static Condition toTimeCondition(Context context, int minutesFromNow) {
+    public static Condition toTimeCondition(Context context, int minutesFromNow, int userHandle) {
         final long now = System.currentTimeMillis();
         final long millis = minutesFromNow == 0 ? ZERO_VALUE_MS : minutesFromNow * MINUTES_MS;
-        return toTimeCondition(context, now + millis, minutesFromNow, now);
+        return toTimeCondition(context, now + millis, minutesFromNow, now, userHandle);
     }
 
-    public static Condition toTimeCondition(Context context, long time, int minutes, long now) {
+    public static Condition toTimeCondition(Context context, long time, int minutes, long now,
+            int userHandle) {
         final int num, summaryResId, line1ResId;
         if (minutes < 60) {
             // display as minutes
@@ -493,7 +494,7 @@
             summaryResId = com.android.internal.R.plurals.zen_mode_duration_hours_summary;
             line1ResId = com.android.internal.R.plurals.zen_mode_duration_hours;
         }
-        final String skeleton = DateFormat.is24HourFormat(context) ? "Hm" : "hma";
+        final String skeleton = DateFormat.is24HourFormat(context, userHandle) ? "Hm" : "hma";
         final String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
         final CharSequence formattedTime = DateFormat.format(pattern, time);
         final Resources res = context.getResources();
diff --git a/core/java/android/text/format/DateFormat.java b/core/java/android/text/format/DateFormat.java
index 933bcee..72bbb2b 100755
--- a/core/java/android/text/format/DateFormat.java
+++ b/core/java/android/text/format/DateFormat.java
@@ -17,6 +17,7 @@
 package android.text.format;
 
 import android.content.Context;
+import android.os.UserHandle;
 import android.provider.Settings;
 import android.text.SpannableStringBuilder;
 import android.text.Spanned;
@@ -166,8 +167,20 @@
      * @return true if 24 hour time format is selected, false otherwise.
      */
     public static boolean is24HourFormat(Context context) {
-        String value = Settings.System.getString(context.getContentResolver(),
-                Settings.System.TIME_12_24);
+        return is24HourFormat(context, UserHandle.myUserId());
+    }
+
+    /**
+     * Returns true if user preference with the given user handle is set to 24-hour format.
+     * @param context the context to use for the content resolver
+     * @param userHandle the user handle of the user to query.
+     * @return true if 24 hour time format is selected, false otherwise.
+     *
+     * @hide
+     */
+    public static boolean is24HourFormat(Context context, int userHandle) {
+        String value = Settings.System.getStringForUser(context.getContentResolver(),
+                Settings.System.TIME_12_24, userHandle);
 
         if (value == null) {
             Locale locale = context.getResources().getConfiguration().locale;
@@ -179,7 +192,7 @@
             }
 
             java.text.DateFormat natural =
-                java.text.DateFormat.getTimeInstance(java.text.DateFormat.LONG, locale);
+                    java.text.DateFormat.getTimeInstance(java.text.DateFormat.LONG, locale);
 
             if (natural instanceof SimpleDateFormat) {
                 SimpleDateFormat sdf = (SimpleDateFormat) natural;
@@ -253,8 +266,19 @@
      * @hide
      */
     public static String getTimeFormatString(Context context) {
+        return getTimeFormatString(context, UserHandle.myUserId());
+    }
+
+    /**
+     * Returns a String pattern that can be used to format the time according
+     * to the current locale and the user's 12-/24-hour clock preference.
+     * @param context the application context
+     * @param userHandle the user handle of the user to query the format for
+     * @hide
+     */
+    public static String getTimeFormatString(Context context, int userHandle) {
         LocaleData d = LocaleData.get(context.getResources().getConfiguration().locale);
-        return is24HourFormat(context) ? d.timeFormat24 : d.timeFormat12;
+        return is24HourFormat(context, userHandle) ? d.timeFormat24 : d.timeFormat12;
     }
 
     /**
diff --git a/core/java/android/widget/TextClock.java b/core/java/android/widget/TextClock.java
index 4c5c71d..a98d272 100644
--- a/core/java/android/widget/TextClock.java
+++ b/core/java/android/widget/TextClock.java
@@ -16,6 +16,7 @@
 
 package android.widget;
 
+import android.app.ActivityManager;
 import android.content.BroadcastReceiver;
 import android.content.ContentResolver;
 import android.content.Context;
@@ -26,6 +27,7 @@
 import android.net.Uri;
 import android.os.Handler;
 import android.os.SystemClock;
+import android.os.UserHandle;
 import android.provider.Settings;
 import android.text.format.DateFormat;
 import android.util.AttributeSet;
@@ -127,6 +129,8 @@
     private Calendar mTime;
     private String mTimeZone;
 
+    private boolean mShowCurrentUserTime;
+
     private final ContentObserver mFormatChangeObserver = new ContentObserver(new Handler()) {
         @Override
         public void onChange(boolean selfChange) {
@@ -342,6 +346,22 @@
     }
 
     /**
+     * Sets whether this clock should always track the current user and not the user of the
+     * current process. This is used for single instance processes like the systemUI who need
+     * to display time for different users.
+     *
+     * @hide
+     */
+    public void setShowCurrentUserTime(boolean showCurrentUserTime) {
+        mShowCurrentUserTime = showCurrentUserTime;
+
+        chooseFormat();
+        onTimeChanged();
+        unregisterObserver();
+        registerObserver();
+    }
+
+    /**
      * Indicates whether the system is currently using the 24-hour mode.
      *
      * When the system is in 24-hour mode, this view will use the pattern
@@ -360,7 +380,11 @@
      * @see #getFormat24Hour()
      */
     public boolean is24HourModeEnabled() {
-        return DateFormat.is24HourFormat(getContext());
+        if (mShowCurrentUserTime) {
+            return DateFormat.is24HourFormat(getContext(), ActivityManager.getCurrentUser());
+        } else {
+            return DateFormat.is24HourFormat(getContext());
+        }
     }
 
     /**
@@ -500,7 +524,13 @@
 
     private void registerObserver() {
         final ContentResolver resolver = getContext().getContentResolver();
-        resolver.registerContentObserver(Settings.System.CONTENT_URI, true, mFormatChangeObserver);
+        if (mShowCurrentUserTime) {
+            resolver.registerContentObserver(Settings.System.CONTENT_URI, true,
+                    mFormatChangeObserver, UserHandle.USER_ALL);
+        } else {
+            resolver.registerContentObserver(Settings.System.CONTENT_URI, true,
+                    mFormatChangeObserver);
+        }
     }
 
     private void unregisterReceiver() {
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardStatusView.java b/packages/Keyguard/src/com/android/keyguard/KeyguardStatusView.java
index 8898f9e..c8d9fe2 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardStatusView.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardStatusView.java
@@ -16,6 +16,7 @@
 
 package com.android.keyguard;
 
+import android.app.ActivityManager;
 import android.app.AlarmManager;
 import android.content.ContentResolver;
 import android.content.Context;
@@ -105,6 +106,8 @@
         mAlarmStatusView = (TextView) findViewById(R.id.alarm_status);
         mDateView = (TextClock) findViewById(R.id.date_view);
         mClockView = (TextClock) findViewById(R.id.clock_view);
+        mDateView.setShowCurrentUserTime(true);
+        mClockView.setShowCurrentUserTime(true);
         mOwnerInfo = (TextView) findViewById(R.id.owner_info);
         mLockPatternUtils = new LockPatternUtils(getContext());
         final boolean screenOn = KeyguardUpdateMonitor.getInstance(mContext).isScreenOn();
@@ -160,7 +163,9 @@
         if (info == null) {
             return "";
         }
-        String skeleton = DateFormat.is24HourFormat(context) ? "EHm" : "Ehma";
+        String skeleton = DateFormat.is24HourFormat(context, ActivityManager.getCurrentUser())
+                ? "EHm"
+                : "Ehma";
         String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
         return DateFormat.format(pattern, info.getTriggerTime()).toString();
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
index 55a0bba..779ff52 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
@@ -16,12 +16,14 @@
 
 package com.android.systemui.statusbar.policy;
 
+import android.app.ActivityManager;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.res.TypedArray;
 import android.os.Bundle;
+import android.os.UserHandle;
 import android.text.Spannable;
 import android.text.SpannableStringBuilder;
 import android.text.format.DateFormat;
@@ -91,7 +93,8 @@
             filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
             filter.addAction(Intent.ACTION_USER_SWITCHED);
 
-            getContext().registerReceiver(mIntentReceiver, filter, null, getHandler());
+            getContext().registerReceiverAsUser(mIntentReceiver, UserHandle.ALL, filter,
+                    null, getHandler());
         }
 
         // NOTE: It's safe to do these after registering the receiver since the receiver always runs
@@ -142,7 +145,7 @@
 
     private final CharSequence getSmallTime() {
         Context context = getContext();
-        boolean is24 = DateFormat.is24HourFormat(context);
+        boolean is24 = DateFormat.is24HourFormat(context, ActivityManager.getCurrentUser());
         LocaleData d = LocaleData.get(context.getResources().getConfiguration().locale);
 
         final char MAGIC1 = '\uEF00';
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NextAlarmController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NextAlarmController.java
index 8f1f7c7..787acc5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NextAlarmController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NextAlarmController.java
@@ -39,7 +39,7 @@
         IntentFilter filter = new IntentFilter();
         filter.addAction(Intent.ACTION_USER_SWITCHED);
         filter.addAction(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED);
-        context.registerReceiver(this, filter);
+        context.registerReceiverAsUser(this, UserHandle.ALL, filter, null, null);
         updateNextAlarm();
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SplitClockView.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SplitClockView.java
index e7c4ede..50e3977 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SplitClockView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SplitClockView.java
@@ -16,10 +16,12 @@
 
 package com.android.systemui.statusbar.policy;
 
+import android.app.ActivityManager;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.os.UserHandle;
 import android.text.format.DateFormat;
 import android.util.AttributeSet;
 import android.widget.LinearLayout;
@@ -42,7 +44,9 @@
             final String action = intent.getAction();
             if (Intent.ACTION_TIME_CHANGED.equals(action)
                     || Intent.ACTION_TIMEZONE_CHANGED.equals(action)
-                    || Intent.ACTION_LOCALE_CHANGED.equals(action)) {
+                    || Intent.ACTION_LOCALE_CHANGED.equals(action)
+                    || Intent.ACTION_CONFIGURATION_CHANGED.equals(action)
+                    || Intent.ACTION_USER_SWITCHED.equals(action)) {
                 updatePatterns();
             }
         }
@@ -57,6 +61,8 @@
         super.onFinishInflate();
         mTimeView = (TextClock) findViewById(R.id.time_view);
         mAmPmView = (TextClock) findViewById(R.id.am_pm_view);
+        mTimeView.setShowCurrentUserTime(true);
+        mAmPmView.setShowCurrentUserTime(true);
     }
 
     @Override
@@ -67,7 +73,9 @@
         filter.addAction(Intent.ACTION_TIME_CHANGED);
         filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
         filter.addAction(Intent.ACTION_LOCALE_CHANGED);
-        getContext().registerReceiver(mIntentReceiver, filter, null, null);
+        filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
+        filter.addAction(Intent.ACTION_USER_SWITCHED);
+        getContext().registerReceiverAsUser(mIntentReceiver, UserHandle.ALL, filter, null, null);
 
         updatePatterns();
     }
@@ -79,7 +87,8 @@
     }
 
     private void updatePatterns() {
-        String formatString = DateFormat.getTimeFormatString(getContext());
+        String formatString = DateFormat.getTimeFormatString(getContext(),
+                ActivityManager.getCurrentUser());
         int index = getAmPmPartEndIndex(formatString);
         String timeString;
         String amPmString;
diff --git a/packages/SystemUI/src/com/android/systemui/volume/ZenModePanel.java b/packages/SystemUI/src/com/android/systemui/volume/ZenModePanel.java
index ed6ddd2..5b37f78 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/ZenModePanel.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/ZenModePanel.java
@@ -18,6 +18,7 @@
 
 import android.animation.Animator;
 import android.animation.AnimatorListenerAdapter;
+import android.app.ActivityManager;
 import android.content.Context;
 import android.content.Intent;
 import android.content.SharedPreferences;
@@ -218,7 +219,7 @@
             } else {
                 mBucketIndex = DEFAULT_BUCKET_INDEX;
                 mTimeCondition = ZenModeConfig.toTimeCondition(mContext,
-                        MINUTE_BUCKETS[mBucketIndex]);
+                        MINUTE_BUCKETS[mBucketIndex], ActivityManager.getCurrentUser());
             }
             if (DEBUG) Log.d(mTag, "Initial bucket index: " + mBucketIndex);
             mConditions = null; // reset conditions
@@ -341,7 +342,7 @@
         final long span = time - now;
         if (span <= 0 || span > MAX_BUCKET_MINUTES * MINUTES_MS) return null;
         return ZenModeConfig.toTimeCondition(mContext,
-                time, Math.round(span / (float) MINUTES_MS), now);
+                time, Math.round(span / (float) MINUTES_MS), now, ActivityManager.getCurrentUser());
     }
 
     private void handleUpdateConditions(Condition[] conditions) {
@@ -397,7 +398,8 @@
         if (favoriteIndex == -1) {
             getConditionTagAt(FOREVER_CONDITION_INDEX).rb.setChecked(true);
         } else {
-            mTimeCondition = ZenModeConfig.toTimeCondition(mContext, MINUTE_BUCKETS[favoriteIndex]);
+            mTimeCondition = ZenModeConfig.toTimeCondition(mContext,
+                    MINUTE_BUCKETS[favoriteIndex], ActivityManager.getCurrentUser());
             mBucketIndex = favoriteIndex;
             bind(mTimeCondition, mZenConditions.getChildAt(TIME_CONDITION_INDEX));
             getConditionTagAt(TIME_CONDITION_INDEX).rb.setChecked(true);
@@ -511,7 +513,7 @@
                 final long span = time - System.currentTimeMillis();
                 button1.setEnabled(span > MIN_BUCKET_MINUTES * MINUTES_MS);
                 final Condition maxCondition = ZenModeConfig.toTimeCondition(mContext,
-                        MAX_BUCKET_MINUTES);
+                        MAX_BUCKET_MINUTES, ActivityManager.getCurrentUser());
                 button2.setEnabled(!Objects.equals(condition.summary, maxCondition.summary));
             }
 
@@ -562,20 +564,20 @@
                 if (up && bucketTime > time || !up && bucketTime < time) {
                     mBucketIndex = j;
                     newCondition = ZenModeConfig.toTimeCondition(mContext,
-                            bucketTime, bucketMinutes, now);
+                            bucketTime, bucketMinutes, now, ActivityManager.getCurrentUser());
                     break;
                 }
             }
             if (newCondition == null) {
                 mBucketIndex = DEFAULT_BUCKET_INDEX;
                 newCondition = ZenModeConfig.toTimeCondition(mContext,
-                        MINUTE_BUCKETS[mBucketIndex]);
+                        MINUTE_BUCKETS[mBucketIndex], ActivityManager.getCurrentUser());
             }
         } else {
             // on a known index, simply increment or decrement
             mBucketIndex = Math.max(0, Math.min(N - 1, mBucketIndex + (up ? 1 : -1)));
             newCondition = ZenModeConfig.toTimeCondition(mContext,
-                    MINUTE_BUCKETS[mBucketIndex]);
+                    MINUTE_BUCKETS[mBucketIndex], ActivityManager.getCurrentUser());
         }
         mTimeCondition = newCondition;
         bind(mTimeCondition, row);
diff --git a/services/core/java/com/android/server/AlarmManagerService.java b/services/core/java/com/android/server/AlarmManagerService.java
index 08c47dc..831af85 100644
--- a/services/core/java/com/android/server/AlarmManagerService.java
+++ b/services/core/java/com/android/server/AlarmManagerService.java
@@ -1124,7 +1124,7 @@
 
                     if (DEBUG_ALARM_CLOCK) {
                         Log.v(TAG, "Found AlarmClockInfo at " +
-                                formatNextAlarm(getContext(), a.alarmClock) +
+                                formatNextAlarm(getContext(), a.alarmClock, userId) +
                                 " for user " + userId);
                     }
 
@@ -1162,7 +1162,7 @@
         if (alarmClock != null) {
             if (DEBUG_ALARM_CLOCK) {
                 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
-                        formatNextAlarm(getContext(), alarmClock));
+                        formatNextAlarm(getContext(), alarmClock, userId));
             }
             mNextAlarmClockForUser.put(userId, alarmClock);
         } else {
@@ -1204,7 +1204,7 @@
             AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
             Settings.System.putStringForUser(getContext().getContentResolver(),
                     Settings.System.NEXT_ALARM_FORMATTED,
-                    formatNextAlarm(getContext(), alarmClock),
+                    formatNextAlarm(getContext(), alarmClock, userId),
                     userId);
 
             getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
@@ -1215,8 +1215,9 @@
     /**
      * Formats an alarm like platform/packages/apps/DeskClock used to.
      */
-    private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info) {
-        String skeleton = DateFormat.is24HourFormat(context) ? "EHm" : "Ehma";
+    private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
+            int userId) {
+        String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
         String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
         return (info == null) ? "" :
                 DateFormat.format(pattern, info.getTriggerTime()).toString();