Merge "Update manifest shortcut XML schema" into nyc-mr1-dev
diff --git a/Android.mk b/Android.mk
index 2b248d4..50bed92 100644
--- a/Android.mk
+++ b/Android.mk
@@ -1120,6 +1120,9 @@
 		-showAnnotation android.annotation.SystemApi \
 		-title "Android SDK - Including system APIs." \
 		-toroot / \
+		-hide 101 \
+		-hide 104 \
+		-hide 108 \
 		-hdf android.whichdoc online \
 		$(sample_groups) \
 		-hdf android.hasSamples true \
diff --git a/core/java/android/app/ActivityManagerNative.java b/core/java/android/app/ActivityManagerNative.java
index f12c284..3c7eef5 100644
--- a/core/java/android/app/ActivityManagerNative.java
+++ b/core/java/android/app/ActivityManagerNative.java
@@ -1779,9 +1779,10 @@
 
         case START_BACKUP_AGENT_TRANSACTION: {
             data.enforceInterface(IActivityManager.descriptor);
-            ApplicationInfo info = ApplicationInfo.CREATOR.createFromParcel(data);
+            String packageName = data.readString();
             int backupRestoreMode = data.readInt();
-            boolean success = bindBackupAgent(info, backupRestoreMode);
+            int userId = data.readInt();
+            boolean success = bindBackupAgent(packageName, backupRestoreMode, userId);
             reply.writeNoException();
             reply.writeInt(success ? 1 : 0);
             return true;
@@ -4448,13 +4449,14 @@
         return binder;
     }
 
-    public boolean bindBackupAgent(ApplicationInfo app, int backupRestoreMode)
+    public boolean bindBackupAgent(String packageName, int backupRestoreMode, int userId)
             throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
         data.writeInterfaceToken(IActivityManager.descriptor);
-        app.writeToParcel(data, 0);
+        data.writeString(packageName);
         data.writeInt(backupRestoreMode);
+        data.writeInt(userId);
         mRemote.transact(START_BACKUP_AGENT_TRANSACTION, data, reply, 0);
         reply.readException();
         boolean success = reply.readInt() != 0;
diff --git a/core/java/android/app/IActivityManager.java b/core/java/android/app/IActivityManager.java
index 81788da..ac21346 100644
--- a/core/java/android/app/IActivityManager.java
+++ b/core/java/android/app/IActivityManager.java
@@ -250,7 +250,7 @@
     public IBinder peekService(Intent service, String resolvedType, String callingPackage)
             throws RemoteException;
 
-    public boolean bindBackupAgent(ApplicationInfo appInfo, int backupRestoreMode)
+    public boolean bindBackupAgent(String packageName, int backupRestoreMode, int userId)
             throws RemoteException;
     public void clearPendingBackup() throws RemoteException;
     public void backupAgentCreated(String packageName, IBinder agent) throws RemoteException;
diff --git a/core/java/android/bluetooth/BluetoothSap.java b/core/java/android/bluetooth/BluetoothSap.java
index 014cb22..e70c936 100644
--- a/core/java/android/bluetooth/BluetoothSap.java
+++ b/core/java/android/bluetooth/BluetoothSap.java
@@ -138,7 +138,7 @@
     }
 
     boolean doBind() {
-        Intent intent = new Intent(IBluetoothMap.class.getName());
+        Intent intent = new Intent(IBluetoothSap.class.getName());
         ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
         intent.setComponent(comp);
         if (comp == null || !mContext.bindServiceAsUser(intent, mConnection, 0,
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index df2c6fc..c140f1bd5 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -1556,7 +1556,7 @@
 
     /**
      * Used as an int extra field with {@link #ACTION_INSTALL_PACKAGE} and
-     * {@link} #ACTION_VIEW} to indicate the uid of the package that initiated the install
+     * {@link #ACTION_VIEW} to indicate the uid of the package that initiated the install
      * @hide
      */
     @SystemApi
diff --git a/core/java/android/os/IDeviceIdleController.aidl b/core/java/android/os/IDeviceIdleController.aidl
index 082194b..cc2af21 100644
--- a/core/java/android/os/IDeviceIdleController.aidl
+++ b/core/java/android/os/IDeviceIdleController.aidl
@@ -38,8 +38,6 @@
     long addPowerSaveTempWhitelistAppForMms(String name, int userId, String reason);
     long addPowerSaveTempWhitelistAppForSms(String name, int userId, String reason);
     void exitIdle(String reason);
-    void downloadServiceActive(IBinder token);
-    void downloadServiceInactive();
     boolean registerMaintenanceActivityListener(IMaintenanceActivityListener listener);
     void unregisterMaintenanceActivityListener(IMaintenanceActivityListener listener);
 }
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index f8a6a17..72126d0 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -106,12 +106,13 @@
      * @param alwaysFocusable True if the app windows are always focusable regardless of the stack
      *                        they are in.
      * @param homeTask True if this is the task.
+     * @param targetSdkVersion The application's target SDK version
      */
     void addAppToken(int addPos, IApplicationToken token, int taskId, int stackId,
             int requestedOrientation, boolean fullscreen, boolean showWhenLocked, int userId,
             int configChanges, boolean voiceInteraction, boolean launchTaskBehind,
             in Rect taskBounds, in Configuration configuration, int taskResizeMode,
-            boolean alwaysFocusable, boolean homeTask);
+            boolean alwaysFocusable, boolean homeTask, int targetSdkVersion);
     /**
      *
      * @param token The token we are adding to the input task Id.
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index d59c8ac..17834fb 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -464,7 +464,8 @@
             || mUpdateWindowNeeded || mReportDrawNeeded || redrawNeeded) {
             getLocationInWindow(mLocation);
 
-            if (DEBUG) Log.i(TAG, "Changes: creating=" + creating
+            if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
+                    + "Changes: creating=" + creating
                     + " format=" + formatChanged + " size=" + sizeChanged
                     + " visible=" + visibleChanged
                     + " left=" + (mWindowSpaceLeft != mLocation[0])
@@ -534,7 +535,8 @@
                     mReportDrawNeeded = false;
                     mDrawingStopped = !visible;
 
-                    if (DEBUG) Log.i(TAG, "Cur surface: " + mSurface);
+                    if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
+                            + "Cur surface: " + mSurface);
 
                     relayoutResult = mSession.relayout(
                         mWindow, mWindow.mSeq, mLayout, mWindowSpaceWidth, mWindowSpaceHeight,
@@ -547,7 +549,8 @@
                         reportDrawNeeded = true;
                     }
 
-                    if (DEBUG) Log.i(TAG, "New surface: " + mNewSurface
+                    if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
+                            + "New surface: " + mNewSurface
                             + ", vis=" + visible + ", frame=" + mWinFrame);
 
                     mSurfaceFrame.left = 0;
@@ -581,7 +584,8 @@
                     if (mSurfaceCreated && (surfaceChanged || (!visible && visibleChanged))) {
                         mSurfaceCreated = false;
                         if (mSurface.isValid()) {
-                            if (DEBUG) Log.i(TAG, "visibleChanged -- surfaceDestroyed");
+                            if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
+                                    + "visibleChanged -- surfaceDestroyed");
                             callbacks = getSurfaceCallbacks();
                             for (SurfaceHolder.Callback c : callbacks) {
                                 c.surfaceDestroyed(mSurfaceHolder);
@@ -594,7 +598,8 @@
                         if (!mSurfaceCreated && (surfaceChanged || visibleChanged)) {
                             mSurfaceCreated = true;
                             mIsCreating = true;
-                            if (DEBUG) Log.i(TAG, "visibleChanged -- surfaceCreated");
+                            if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
+                                    + "visibleChanged -- surfaceCreated");
                             if (callbacks == null) {
                                 callbacks = getSurfaceCallbacks();
                             }
@@ -604,7 +609,8 @@
                         }
                         if (creating || formatChanged || sizeChanged
                                 || visibleChanged || realSizeChanged) {
-                            if (DEBUG) Log.i(TAG, "surfaceChanged -- format=" + mFormat
+                            if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
+                                    + "surfaceChanged -- format=" + mFormat
                                     + " w=" + myWidth + " h=" + myHeight);
                             if (callbacks == null) {
                                 callbacks = getSurfaceCallbacks();
@@ -614,7 +620,8 @@
                             }
                         }
                         if (redrawNeeded) {
-                            if (DEBUG) Log.i(TAG, "surfaceRedrawNeeded");
+                            if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
+                                    + "surfaceRedrawNeeded");
                             if (callbacks == null) {
                                 callbacks = getSurfaceCallbacks();
                             }
@@ -629,7 +636,8 @@
                 } finally {
                     mIsCreating = false;
                     if (redrawNeeded) {
-                        if (DEBUG) Log.i(TAG, "finishedDrawing");
+                        if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " "
+                                + "finishedDrawing");
                         mSession.finishDrawing(mWindow);
                     }
                     mSession.performDeferredDestroy(mWindow);
@@ -663,8 +671,9 @@
                 }
 
                 try {
-                    Log.d(TAG, String.format("updateWindowPosition UI, " +
-                            "postion = [%d, %d, %d, %d]", mWinFrame.left, mWinFrame.top,
+                    Log.d(TAG, String.format("%d updateWindowPosition UI, " +
+                            "postion = [%d, %d, %d, %d]", System.identityHashCode(this),
+                            mWinFrame.left, mWinFrame.top,
                             mWinFrame.right, mWinFrame.bottom));
                     mSession.repositionChild(mWindow, mWinFrame.left, mWinFrame.top,
                             mWinFrame.right, mWinFrame.bottom, -1, mWinFrame);
@@ -697,9 +706,9 @@
         }
         try {
             if (DEBUG) {
-                Log.d(TAG, String.format("updateWindowPosition RT, frameNr = %d, " +
-                        "postion = [%d, %d, %d, %d]", frameNumber, left, top,
-                        right, bottom));
+                Log.d(TAG, String.format("%d updateWindowPosition RT, frameNr = %d, " +
+                        "postion = [%d, %d, %d, %d]", System.identityHashCode(this),
+                        frameNumber, left, top, right, bottom));
             }
             // Just using mRTLastReportedPosition as a dummy rect here
             session.repositionChild(window, left, top, right, bottom,
@@ -712,6 +721,25 @@
         }
     }
 
+    /**
+     * Called by native on RenderThread to notify that the window is no longer in the
+     * draw tree
+     * @hide
+     */
+    public final void windowPositionLostRT(long frameNumber) {
+        if (DEBUG) {
+            Log.d(TAG, String.format("%d windowPositionLostRT RT, frameNr = %d",
+                    System.identityHashCode(this), frameNumber));
+        }
+        // TODO: This is a bit of a hack as we don't have an API to report to WM
+        // to hide a window with a frameNumber, so just shift the window very far into
+        // negative space which will do effectively the same thing.
+        // Use the last reported size to avoid influencing the size of the bufferqueue
+        int x = -1000 - mRTLastReportedPosition.width();
+        int y = -1000 - mRTLastReportedPosition.height();
+        updateWindowPositionRT(frameNumber, x, y, -1000, -1000);
+    }
+
     private SurfaceHolder.Callback[] getSurfaceCallbacks() {
         SurfaceHolder.Callback callbacks[];
         synchronized (mCallbacks) {
@@ -750,8 +778,7 @@
                 boolean alwaysConsumeNavBar) {
             SurfaceView surfaceView = mSurfaceView.get();
             if (surfaceView != null) {
-                if (DEBUG) Log.v(
-                        "SurfaceView", surfaceView + " got resized: w=" + frame.width()
+                if (DEBUG) Log.v(TAG, surfaceView + " got resized: w=" + frame.width()
                         + " h=" + frame.height() + ", cur w=" + mCurWidth + " h=" + mCurHeight);
                 surfaceView.mSurfaceLock.lock();
                 try {
@@ -907,7 +934,7 @@
         private final Canvas internalLockCanvas(Rect dirty) {
             mSurfaceLock.lock();
 
-            if (DEBUG) Log.i(TAG, "Locking canvas... stopped="
+            if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + "Locking canvas... stopped="
                     + mDrawingStopped + ", win=" + mWindow);
 
             Canvas c = null;
@@ -919,7 +946,7 @@
                 }
             }
 
-            if (DEBUG) Log.i(TAG, "Returned canvas: " + c);
+            if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + "Returned canvas: " + c);
             if (c != null) {
                 mLastLockTime = SystemClock.uptimeMillis();
                 return c;
diff --git a/core/jni/android_view_RenderNode.cpp b/core/jni/android_view_RenderNode.cpp
index a6db0f4..4fc546c 100644
--- a/core/jni/android_view_RenderNode.cpp
+++ b/core/jni/android_view_RenderNode.cpp
@@ -534,6 +534,7 @@
 // ----------------------------------------------------------------------------
 
 jmethodID gSurfaceViewPositionUpdateMethod;
+jmethodID gSurfaceViewPositionLostMethod;
 
 static void android_view_RenderNode_requestPositionUpdates(JNIEnv* env, jobject,
         jlong renderNodePtr, jobject surfaceview) {
@@ -581,6 +582,20 @@
             info.canvasContext.enqueueFrameWork(std::move(functor));
         }
 
+        virtual void onPositionLost(RenderNode& node, const TreeInfo* info) override {
+            if (CC_UNLIKELY(!mWeakRef || (info && !info->updateWindowPositions))) return;
+
+            if (info) {
+                auto functor = std::bind(
+                    std::mem_fn(&SurfaceViewPositionUpdater::doNotifyPositionLost), this,
+                    (jlong) info->canvasContext.getFrameNumber());
+
+                info->canvasContext.enqueueFrameWork(std::move(functor));
+            } else {
+                doNotifyPositionLost(0);
+            }
+        }
+
     private:
         JNIEnv* jnienv() {
             JNIEnv* env;
@@ -607,6 +622,21 @@
             env->DeleteLocalRef(localref);
         }
 
+        void doNotifyPositionLost(jlong frameNumber) {
+            ATRACE_NAME("SurfaceView position lost");
+
+            JNIEnv* env = jnienv();
+            jobject localref = env->NewLocalRef(mWeakRef);
+            if (CC_UNLIKELY(!localref)) {
+                jnienv()->DeleteWeakGlobalRef(mWeakRef);
+                mWeakRef = nullptr;
+                return;
+            }
+
+            env->CallVoidMethod(localref, gSurfaceViewPositionLostMethod, frameNumber);
+            env->DeleteLocalRef(localref);
+        }
+
         JavaVM* mVm;
         jobject mWeakRef;
     };
@@ -701,6 +731,8 @@
     jclass clazz = FindClassOrDie(env, "android/view/SurfaceView");
     gSurfaceViewPositionUpdateMethod = GetMethodIDOrDie(env, clazz,
             "updateWindowPositionRT", "(JIIII)V");
+    gSurfaceViewPositionLostMethod = GetMethodIDOrDie(env, clazz,
+            "windowPositionLostRT", "(J)V");
     clazz = FindClassOrDie(env, "android/view/RenderNode");
     gOnRenderNodeDetached = GetMethodIDOrDie(env, clazz,
             "onRenderNodeDetached", "()V");
diff --git a/core/res/res/values-watch/config_material.xml b/core/res/res/values-watch/config_material.xml
index 951c088..81b53e7 100644
--- a/core/res/res/values-watch/config_material.xml
+++ b/core/res/res/values-watch/config_material.xml
@@ -27,9 +27,6 @@
     <!-- Use micro alert controller -->
     <integer name="config_alertDialogController">1</integer>
 
-    <!-- Dialog windows in watch should occupy the whole screen and not be floating. -->
-    <bool name="config_dialogWindowIsFloating">false</bool>
-
     <!-- Always overscan by default to ensure onApplyWindowInsets will always be called. -->
     <bool name="config_windowOverscanByDefault">true</bool>
 
diff --git a/core/res/res/values-watch/themes_material.xml b/core/res/res/values-watch/themes_material.xml
index d92a947..4ae4367 100644
--- a/core/res/res/values-watch/themes_material.xml
+++ b/core/res/res/values-watch/themes_material.xml
@@ -38,4 +38,25 @@
         <item name="imeFullscreenBackground">?colorBackground</item>
         <item name="imeExtractEnterAnimation">@anim/input_method_extract_enter</item>
     </style>
+
+    <!-- Override behaviour to set the theme colours for dialogs, keep them the same. -->
+    <style name="ThemeOverlay.Material.Dialog" parent="ThemeOverlay.Material.BaseDialog">
+        <item name="windowIsFloating">false</item>
+    </style>
+
+    <!-- Force the background and floating colours to be the default colours. -->
+    <style name="Theme.Material.Dialog" parent="Theme.Material.BaseDialog">
+        <item name="colorBackground">@color/background_material_dark</item>
+        <item name="colorBackgroundFloating">@color/background_floating_material_dark</item>
+        <item name="colorBackgroundCacheHint">@color/background_cache_hint_selector_material_dark</item>
+        <item name="windowIsFloating">false</item>
+    </style>
+
+    <!-- Force the background and floating colours to be the default colours. -->
+    <style name="Theme.Material.Light.Dialog" parent="Theme.Material.Light.BaseDialog">
+        <item name="colorBackground">@color/background_material_light</item>
+        <item name="colorBackgroundFloating">@color/background_floating_material_light</item>
+        <item name="colorBackgroundCacheHint">@color/background_cache_hint_selector_material_light</item>
+        <item name="windowIsFloating">false</item>
+    </style>
 </resources>
diff --git a/core/res/res/values/colors_device_defaults.xml b/core/res/res/values/colors_device_defaults.xml
new file mode 100644
index 0000000..e830b64
--- /dev/null
+++ b/core/res/res/values/colors_device_defaults.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2016 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<!-- Colors specific to DeviceDefault themes. These are mostly pass-throughs to enable
+     overlaying new theme colors. -->
+<resources>
+    <color name="primary_device_default_dark">@color/primary_material_dark</color>
+    <color name="primary_device_default_light">@color/primary_material_light</color>
+    <color name="primary_device_default_settings">@color/primary_material_settings</color>
+    <color name="primary_dark_device_default_dark">@color/primary_dark_material_dark</color>
+    <color name="primary_dark_device_default_light">@color/primary_dark_material_light</color>
+    <color name="primary_dark_device_default_settings">@color/primary_dark_material_settings</color>
+
+    <color name="secondary_device_default_settings">@color/secondary_material_settings</color>
+
+    <color name="accent_device_default_light">@color/accent_material_light</color>
+    <color name="accent_device_default_dark">@color/accent_material_dark</color>
+</resources>
\ No newline at end of file
diff --git a/core/res/res/values/colors_material.xml b/core/res/res/values/colors_material.xml
index c8ca116..a18abdf 100644
--- a/core/res/res/values/colors_material.xml
+++ b/core/res/res/values/colors_material.xml
@@ -26,9 +26,13 @@
 
     <color name="primary_material_dark">@color/material_grey_900</color>
     <color name="primary_material_light">@color/material_grey_100</color>
+    <color name="primary_material_settings">@color/material_blue_grey_900</color>
     <color name="primary_dark_material_dark">@color/black</color>
     <color name="primary_dark_material_light">@color/material_grey_600</color>
     <color name="primary_dark_material_light_light_status_bar">@color/material_grey_300</color>
+    <color name="primary_dark_material_settings">@color/material_blue_grey_950</color>
+
+    <color name="secondary_material_settings">@color/material_blue_grey_800</color>
 
     <color name="accent_material_light">@color/material_deep_teal_500</color>
     <color name="accent_material_dark">@color/material_deep_teal_200</color>
diff --git a/core/res/res/values/config_material.xml b/core/res/res/values/config_material.xml
index f62678a..a37be83 100644
--- a/core/res/res/values/config_material.xml
+++ b/core/res/res/values/config_material.xml
@@ -29,9 +29,6 @@
     <!-- The alert controller to use for alert dialogs. -->
     <integer name="config_alertDialogController">0</integer>
 
-    <!-- True if dialog windows are floating. -->
-    <bool name="config_dialogWindowIsFloating">true</bool>
-
     <!-- True if windowOverscan should be on by default. -->
     <bool name="config_windowOverscanByDefault">false</bool>
 
diff --git a/core/res/res/values/themes_device_defaults.xml b/core/res/res/values/themes_device_defaults.xml
index ea1b626..e5b6c78 100644
--- a/core/res/res/values/themes_device_defaults.xml
+++ b/core/res/res/values/themes_device_defaults.xml
@@ -199,25 +199,50 @@
 
         <item name="mediaRouteButtonStyle">@style/Widget.DeviceDefault.MediaRouteButton</item>
 
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+
     </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault} with no action bar -->
-    <style name="Theme.DeviceDefault.NoActionBar" parent="Theme.Material.NoActionBar"  />
+    <style name="Theme.DeviceDefault.NoActionBar" parent="Theme.Material.NoActionBar">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault} with no action bar and no status bar.  This theme
          sets {@link android.R.attr#windowFullscreen} to true.  -->
-    <style name="Theme.DeviceDefault.NoActionBar.Fullscreen" parent="Theme.Material.NoActionBar.Fullscreen"  />
+    <style name="Theme.DeviceDefault.NoActionBar.Fullscreen" parent="Theme.Material.NoActionBar.Fullscreen">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault} with no action bar and no status bar and
     extending in to overscan region.  This theme
     sets {@link android.R.attr#windowFullscreen} and {@link android.R.attr#windowOverscan}
     to true. -->
-    <style name="Theme.DeviceDefault.NoActionBar.Overscan" parent="Theme.Material.NoActionBar.Overscan"  />
+    <style name="Theme.DeviceDefault.NoActionBar.Overscan" parent="Theme.Material.NoActionBar.Overscan">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault} that has no title bar and translucent
          system decor.  This theme sets {@link android.R.attr#windowTranslucentStatus} and
          {@link android.R.attr#windowTranslucentNavigation} to true. -->
-    <style name="Theme.DeviceDefault.NoActionBar.TranslucentDecor" parent="Theme.Material.NoActionBar.TranslucentDecor"  />
+    <style name="Theme.DeviceDefault.NoActionBar.TranslucentDecor" parent="Theme.Material.NoActionBar.TranslucentDecor">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- DeviceDefault theme for dialog windows and activities. This changes the window to be
     floating (not fill the entire screen), and puts a frame around its contents. You can set this
@@ -231,18 +256,38 @@
 
         <item name="textAppearance">@style/TextAppearance.DeviceDefault</item>
         <item name="textAppearanceInverse">@style/TextAppearance.DeviceDefault.Inverse</item>
+
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
     </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault_Dialog} that has a nice minimum width for a
     regular dialog. -->
-    <style name="Theme.DeviceDefault.Dialog.MinWidth" parent="Theme.Material.Dialog.MinWidth" />
+    <style name="Theme.DeviceDefault.Dialog.MinWidth" parent="Theme.Material.Dialog.MinWidth">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault_Dialog} without an action bar -->
-    <style name="Theme.DeviceDefault.Dialog.NoActionBar" parent="Theme.Material.Dialog.NoActionBar" />
+    <style name="Theme.DeviceDefault.Dialog.NoActionBar" parent="Theme.Material.Dialog.NoActionBar">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault_Dialog_NoActionBar} that has a nice minimum width
     for a regular dialog. -->
-    <style name="Theme.DeviceDefault.Dialog.NoActionBar.MinWidth" parent="Theme.Material.Dialog.NoActionBar.MinWidth" />
+    <style name="Theme.DeviceDefault.Dialog.NoActionBar.MinWidth" parent="Theme.Material.Dialog.NoActionBar.MinWidth">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- Variant of Theme.DeviceDefault.Dialog that has a fixed size. -->
     <style name="Theme.DeviceDefault.Dialog.FixedSize">
@@ -262,44 +307,99 @@
 
     <!-- DeviceDefault theme for a window that will be displayed either full-screen on smaller
     screens (small, normal) or as a dialog on larger screens (large, xlarge). -->
-    <style name="Theme.DeviceDefault.DialogWhenLarge" parent="Theme.Material.DialogWhenLarge"  />
+    <style name="Theme.DeviceDefault.DialogWhenLarge" parent="Theme.Material.DialogWhenLarge">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- DeviceDefault theme for a window without an action bar that will be displayed either
     full-screen on smaller screens (small, normal) or as a dialog on larger screens (large,
     xlarge). -->
-    <style name="Theme.DeviceDefault.DialogWhenLarge.NoActionBar" parent="Theme.Material.DialogWhenLarge.NoActionBar"  />
+    <style name="Theme.DeviceDefault.DialogWhenLarge.NoActionBar" parent="Theme.Material.DialogWhenLarge.NoActionBar">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- DeviceDefault theme for a presentation window on a secondary display. -->
-    <style name="Theme.DeviceDefault.Dialog.Presentation" parent="Theme.Material.Dialog.Presentation" />
+    <style name="Theme.DeviceDefault.Dialog.Presentation" parent="Theme.Material.Dialog.Presentation">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- DeviceDefault theme for panel windows. This removes all extraneous window
     decorations, so you basically have an empty rectangle in which to place your content. It makes
     the window floating, with a transparent background, and turns off dimming behind the window. -->
-    <style name="Theme.DeviceDefault.Panel" parent="Theme.Material.Panel"  />
+    <style name="Theme.DeviceDefault.Panel" parent="Theme.Material.Panel">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- DeviceDefault theme for windows that want to have the user's selected wallpaper appear
     behind them. -->
-    <style name="Theme.DeviceDefault.Wallpaper" parent="Theme.Material.Wallpaper"  />
+    <style name="Theme.DeviceDefault.Wallpaper" parent="Theme.Material.Wallpaper">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- DeviceDefault theme for windows that want to have the user's selected wallpaper appear
     behind them and without an action bar. -->
-    <style name="Theme.DeviceDefault.Wallpaper.NoTitleBar" parent="Theme.Material.Wallpaper.NoTitleBar"  />
+    <style name="Theme.DeviceDefault.Wallpaper.NoTitleBar" parent="Theme.Material.Wallpaper.NoTitleBar">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- DeviceDefault style for input methods, which is used by the
          {@link android.inputmethodservice.InputMethodService} class.-->
-    <style name="Theme.DeviceDefault.InputMethod" parent="Theme.Material.InputMethod"  />
+    <style name="Theme.DeviceDefault.InputMethod" parent="Theme.Material.InputMethod">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- DeviceDefault style for input methods, which is used by the
          {@link android.service.voice.VoiceInteractionSession} class.-->
-    <style name="Theme.DeviceDefault.VoiceInteractionSession" parent="Theme.Material.VoiceInteractionSession" >
-
+    <style name="Theme.DeviceDefault.VoiceInteractionSession" parent="Theme.Material.VoiceInteractionSession">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
     </style>
+
     <style name="Theme.DeviceDefault.Dialog.Alert" parent="Theme.Material.Dialog.Alert">
         <item name="windowTitleStyle">@style/DialogWindowTitle.DeviceDefault</item>
+
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
     </style>
 
-    <style name="Theme.DeviceDefault.SearchBar" parent="Theme.Material.SearchBar" />
-    <style name="Theme.DeviceDefault.Dialog.NoFrame" parent="Theme.Material.Dialog.NoFrame" />
+    <style name="Theme.DeviceDefault.SearchBar" parent="Theme.Material.SearchBar">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
+
+    <style name="Theme.DeviceDefault.Dialog.NoFrame" parent="Theme.Material.Dialog.NoFrame">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_dark</item>
+    </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault} with a light-colored style -->
     <style name="Theme.DeviceDefault.Light" parent="Theme.Material.Light" >
@@ -447,34 +547,63 @@
 
         <item name="mediaRouteButtonStyle">@style/Widget.DeviceDefault.Light.MediaRouteButton</item>
 
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
     </style>
 
     <!-- Variant of the DeviceDefault (light) theme that has a solid (opaque) action bar with an
     inverse color profile. -->
-    <style name="Theme.DeviceDefault.Light.DarkActionBar" parent="Theme.Material.Light.DarkActionBar" />
+    <style name="Theme.DeviceDefault.Light.DarkActionBar" parent="Theme.Material.Light.DarkActionBar">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_dark</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_dark</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault_Light} with no action bar -->
-    <style name="Theme.DeviceDefault.Light.NoActionBar" parent="Theme.Material.Light.NoActionBar"  />
+    <style name="Theme.DeviceDefault.Light.NoActionBar" parent="Theme.Material.Light.NoActionBar">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault_Light} with no action bar and no status bar.
          This theme sets {@link android.R.attr#windowFullscreen} to true.  -->
-    <style name="Theme.DeviceDefault.Light.NoActionBar.Fullscreen" parent="Theme.Material.Light.NoActionBar.Fullscreen"  />
+    <style name="Theme.DeviceDefault.Light.NoActionBar.Fullscreen" parent="Theme.Material.Light.NoActionBar.Fullscreen">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault_Light} with no action bar and no status bar
     and extending in to overscan region.  This theme
     sets {@link android.R.attr#windowFullscreen} and {@link android.R.attr#windowOverscan}
     to true. -->
-    <style name="Theme.DeviceDefault.Light.NoActionBar.Overscan" parent="Theme.Material.Light.NoActionBar.Overscan" />
+    <style name="Theme.DeviceDefault.Light.NoActionBar.Overscan" parent="Theme.Material.Light.NoActionBar.Overscan">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault_Light} that has no title bar and translucent
          system decor.  This theme sets {@link android.R.attr#windowTranslucentStatus} and
          {@link android.R.attr#windowTranslucentNavigation} to true. -->
-    <style name="Theme.DeviceDefault.Light.NoActionBar.TranslucentDecor" parent="Theme.Material.Light.NoActionBar.TranslucentDecor" />
+    <style name="Theme.DeviceDefault.Light.NoActionBar.TranslucentDecor" parent="Theme.Material.Light.NoActionBar.TranslucentDecor">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- DeviceDefault light theme for dialog windows and activities. This changes the window to be
     floating (not fill the entire screen), and puts a frame around its contents. You can set this
     theme on an activity if you would like to make an activity that looks like a Dialog.-->
-    <style name="Theme.DeviceDefault.Light.Dialog" parent="Theme.Material.Light.Dialog" >
+    <style name="Theme.DeviceDefault.Light.Dialog" parent="Theme.Material.Light.Dialog">
         <item name="windowTitleStyle">@style/DialogWindowTitle.DeviceDefault.Light</item>
         <item name="windowAnimationStyle">@style/Animation.DeviceDefault.Dialog</item>
 
@@ -483,18 +612,38 @@
 
         <item name="textAppearance">@style/TextAppearance.DeviceDefault</item>
         <item name="textAppearanceInverse">@style/TextAppearance.DeviceDefault.Inverse</item>
+
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
     </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault_Light_Dialog} that has a nice minimum width for a
     regular dialog. -->
-    <style name="Theme.DeviceDefault.Light.Dialog.MinWidth" parent="Theme.Material.Light.Dialog.MinWidth" />
+    <style name="Theme.DeviceDefault.Light.Dialog.MinWidth" parent="Theme.Material.Light.Dialog.MinWidth">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
      <!-- Variant of {@link #Theme_DeviceDefault_Light_Dialog} without an action bar -->
-    <style name="Theme.DeviceDefault.Light.Dialog.NoActionBar" parent="Theme.Material.Light.Dialog.NoActionBar" />
+    <style name="Theme.DeviceDefault.Light.Dialog.NoActionBar" parent="Theme.Material.Light.Dialog.NoActionBar">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- Variant of {@link #Theme_DeviceDefault_Light_Dialog_NoActionBar} that has a nice minimum
     width for a regular dialog. -->
-    <style name="Theme.DeviceDefault.Light.Dialog.NoActionBar.MinWidth" parent="Theme.Material.Light.Dialog.NoActionBar.MinWidth" />
+    <style name="Theme.DeviceDefault.Light.Dialog.NoActionBar.MinWidth" parent="Theme.Material.Light.Dialog.NoActionBar.MinWidth">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- Variant of Theme.DeviceDefault.Dialog that has a fixed size. -->
     <style name="Theme.DeviceDefault.Light.Dialog.FixedSize">
@@ -502,6 +651,11 @@
         <item name="windowFixedWidthMinor">@dimen/dialog_fixed_width_minor</item>
         <item name="windowFixedHeightMajor">@dimen/dialog_fixed_height_major</item>
         <item name="windowFixedHeightMinor">@dimen/dialog_fixed_height_minor</item>
+
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
     </style>
 
     <!-- Variant of Theme.DeviceDefault.Dialog.NoActionBar that has a fixed size. -->
@@ -510,33 +664,74 @@
         <item name="windowFixedWidthMinor">@dimen/dialog_fixed_width_minor</item>
         <item name="windowFixedHeightMajor">@dimen/dialog_fixed_height_major</item>
         <item name="windowFixedHeightMinor">@dimen/dialog_fixed_height_minor</item>
+
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
     </style>
 
     <!-- DeviceDefault light theme for a window that will be displayed either full-screen on smaller
     screens (small, normal) or as a dialog on larger screens (large, xlarge). -->
-    <style name="Theme.DeviceDefault.Light.DialogWhenLarge" parent="Theme.Material.Light.DialogWhenLarge"  />
+    <style name="Theme.DeviceDefault.Light.DialogWhenLarge" parent="Theme.Material.Light.DialogWhenLarge">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- DeviceDefault light theme for a window without an action bar that will be displayed either
     full-screen on smaller screens (small, normal) or as a dialog on larger screens (large,
     xlarge). -->
-    <style name="Theme.DeviceDefault.Light.DialogWhenLarge.NoActionBar" parent="Theme.Material.Light.DialogWhenLarge.NoActionBar"  />
+    <style name="Theme.DeviceDefault.Light.DialogWhenLarge.NoActionBar" parent="Theme.Material.Light.DialogWhenLarge.NoActionBar">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- DeviceDefault light theme for a presentation window on a secondary display. -->
-    <style name="Theme.DeviceDefault.Light.Dialog.Presentation" parent="Theme.Material.Light.Dialog.Presentation" />
+    <style name="Theme.DeviceDefault.Light.Dialog.Presentation" parent="Theme.Material.Light.Dialog.Presentation">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- DeviceDefault light theme for panel windows. This removes all extraneous window
     decorations, so you basically have an empty rectangle in which to place your content. It makes
     the window floating, with a transparent background, and turns off dimming behind the window. -->
-    <style name="Theme.DeviceDefault.Light.Panel" parent="Theme.Material.Light.Panel"  />
+    <style name="Theme.DeviceDefault.Light.Panel" parent="Theme.Material.Light.Panel">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <style name="Theme.DeviceDefault.Light.Dialog.Alert" parent="Theme.Material.Light.Dialog.Alert">
         <item name="windowTitleStyle">@style/DialogWindowTitle.DeviceDefault.Light</item>
+
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
     </style>
 
-    <style name="Theme.DeviceDefault.Light.SearchBar" parent="Theme.Material.Light.SearchBar" />
+    <style name="Theme.DeviceDefault.Light.SearchBar" parent="Theme.Material.Light.SearchBar">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
+
 
     <!-- DeviceDefault theme for a window that should look like the Settings app.  -->
-    <style name="Theme.DeviceDefault.Settings" parent="Theme.Material.Settings" />
+    <style name="Theme.DeviceDefault.Settings" parent="Theme.Material.Settings">
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_settings</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_settings</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
+    </style>
 
     <!-- Theme used for the intent picker activity. -->
     <style name="Theme.DeviceDefault.Resolver" parent="Theme.Material.Light">
@@ -549,8 +744,13 @@
         <item name="colorControlActivated">?attr/colorControlHighlight</item>
         <item name="listPreferredItemPaddingStart">?attr/dialogPreferredPadding</item>
         <item name="listPreferredItemPaddingEnd">?attr/dialogPreferredPadding</item>
+
+        <!-- Color palette -->
+        <item name="colorPrimary">@color/primary_device_default_light</item>
+        <item name="colorPrimaryDark">@color/primary_dark_device_default_light</item>
+        <item name="colorAccent">@color/accent_device_default_light</item>
     </style>
 
     <!-- DeviceDefault theme for the default system theme.  -->
-    <style name="Theme.DeviceDefault.System" parent="Theme.Material.Light.DarkActionBar" />
+    <style name="Theme.DeviceDefault.System" parent="Theme.DeviceDefault.Light.DarkActionBar" />
 </resources>
diff --git a/core/res/res/values/themes_material.xml b/core/res/res/values/themes_material.xml
index 0e4e060..d437032 100644
--- a/core/res/res/values/themes_material.xml
+++ b/core/res/res/values/themes_material.xml
@@ -864,17 +864,14 @@
         <item name="searchViewStyle">@style/Widget.Material.SearchView.ActionBar</item>
     </style>
 
-    <!-- Theme overlay that overrides window properties to display as a dialog. -->
-    <style name="ThemeOverlay.Material.Dialog">
-        <item name="colorBackgroundCacheHint">@null</item>
-        <item name="colorBackground">?attr/colorBackgroundFloating</item>
-
+    <!-- Base theme for overlay dialogs, customize the colours in the actual dialog theme. -->
+    <style name="ThemeOverlay.Material.BaseDialog">
         <item name="windowFrame">@null</item>
         <item name="windowTitleStyle">@style/DialogWindowTitle.Material</item>
         <item name="windowTitleBackgroundStyle">@style/DialogWindowTitleBackground.Material</item>
         <item name="windowBackground">@drawable/dialog_background_material</item>
         <item name="windowElevation">@dimen/floating_window_z</item>
-        <item name="windowIsFloating">@bool/config_dialogWindowIsFloating</item>
+        <item name="windowIsFloating">true</item>
         <item name="windowContentOverlay">@null</item>
         <item name="windowAnimationStyle">@style/Animation.Material.Dialog</item>
         <item name="windowSoftInputMode">stateUnspecified|adjustPan</item>
@@ -897,6 +894,12 @@
         <item name="windowFixedHeightMinor">@null</item>
     </style>
 
+    <!-- Theme overlay that overrides window properties to display as a dialog. -->
+    <style name="ThemeOverlay.Material.Dialog" parent="ThemeOverlay.Material.BaseDialog">
+        <item name="colorBackgroundCacheHint">@null</item>
+        <item name="colorBackground">?attr/colorBackgroundFloating</item>
+    </style>
+
     <!-- Theme overlay that overrides window properties to display as a date picker dialog. -->
     <style name="ThemeOverlay.Material.Dialog.DatePicker">
         <item name="alertDialogStyle">@style/DatePickerDialog.Material</item>
@@ -1080,7 +1083,7 @@
         <item name="windowTitleBackgroundStyle">@style/DialogWindowTitleBackground.Material</item>
         <item name="windowBackground">@drawable/dialog_background_material</item>
         <item name="windowElevation">@dimen/floating_window_z</item>
-        <item name="windowIsFloating">@bool/config_dialogWindowIsFloating</item>
+        <item name="windowIsFloating">true</item>
         <item name="windowContentOverlay">@null</item>
         <item name="windowAnimationStyle">@style/Animation.Material.Dialog</item>
         <item name="windowSoftInputMode">stateUnspecified|adjustPan</item>
@@ -1300,8 +1303,8 @@
 
     <!-- Default theme for Settings and activities launched from Settings. -->
     <style name="Theme.Material.Settings" parent="Theme.Material.Light.DarkActionBar">
-        <item name="colorPrimary">@color/material_blue_grey_900</item>
-        <item name="colorPrimaryDark">@color/material_blue_grey_950</item>
+        <item name="colorPrimary">@color/primary_material_settings</item>
+        <item name="colorPrimaryDark">@color/primary_dark_material_settings</item>
 
         <item name="presentationTheme">@style/Theme.Material.Settings.Dialog.Presentation</item>
         <item name="searchDialogTheme">@style/Theme.Material.Settings.SearchBar</item>
@@ -1310,8 +1313,8 @@
 
     <!-- Default theme for Settings and activities launched from Settings. -->
     <style name="Theme.Material.Settings.NoActionBar" parent="Theme.Material.Light.NoActionBar">
-        <item name="colorPrimary">@color/material_blue_grey_900</item>
-        <item name="colorPrimaryDark">@color/material_blue_grey_950</item>
+        <item name="colorPrimary">@color/primary_material_settings</item>
+        <item name="colorPrimaryDark">@color/primary_dark_material_settings</item>
 
         <item name="presentationTheme">@style/Theme.Material.Settings.Dialog.Presentation</item>
         <item name="searchDialogTheme">@style/Theme.Material.Settings.SearchBar</item>
@@ -1319,41 +1322,41 @@
     </style>
 
     <style name="Theme.Material.Settings.BaseDialog" parent="Theme.Material.Light.BaseDialog">
-        <item name="colorPrimary">@color/material_blue_grey_900</item>
-        <item name="colorPrimaryDark">@color/material_blue_grey_950</item>
+        <item name="colorPrimary">@color/primary_material_settings</item>
+        <item name="colorPrimaryDark">@color/primary_dark_material_settings</item>
     </style>
 
     <style name="Theme.Material.Settings.Dialog" parent="Theme.Material.Settings.BaseDialog" />
 
     <style name="Theme.Material.Settings.Dialog.BaseAlert" parent="Theme.Material.Light.Dialog.BaseAlert">
-        <item name="colorPrimary">@color/material_blue_grey_900</item>
-        <item name="colorPrimaryDark">@color/material_blue_grey_950</item>
+        <item name="colorPrimary">@color/primary_material_settings</item>
+        <item name="colorPrimaryDark">@color/primary_dark_material_settings</item>
     </style>
 
     <style name="Theme.Material.Settings.Dialog.Alert" parent="Theme.Material.Settings.Dialog.BaseAlert" />
 
     <style name="Theme.Material.Settings.DialogWhenLarge" parent="Theme.Material.Light.DialogWhenLarge.DarkActionBar">
-        <item name="colorPrimary">@color/material_blue_grey_900</item>
-        <item name="colorPrimaryDark">@color/material_blue_grey_950</item>
+        <item name="colorPrimary">@color/primary_material_settings</item>
+        <item name="colorPrimaryDark">@color/primary_dark_material_settings</item>
     </style>
 
     <style name="Theme.Material.Settings.DialogWhenLarge.NoActionBar" parent="Theme.Material.Light.DialogWhenLarge.NoActionBar">
-        <item name="colorPrimary">@color/material_blue_grey_900</item>
-        <item name="colorPrimaryDark">@color/material_blue_grey_950</item>
+        <item name="colorPrimary">@color/primary_material_settings</item>
+        <item name="colorPrimaryDark">@color/primary_dark_material_settings</item>
     </style>
 
     <style name="Theme.Material.Settings.Dialog.Presentation" parent="Theme.Material.Light.Dialog.Presentation">
-        <item name="colorPrimary">@color/material_blue_grey_900</item>
-        <item name="colorPrimaryDark">@color/material_blue_grey_950</item>
+        <item name="colorPrimary">@color/primary_material_settings</item>
+        <item name="colorPrimaryDark">@color/primary_dark_material_settings</item>
     </style>
 
     <style name="Theme.Material.Settings.SearchBar" parent="Theme.Material.Light.SearchBar">
-        <item name="colorPrimary">@color/material_blue_grey_900</item>
-        <item name="colorPrimaryDark">@color/material_blue_grey_950</item>
+        <item name="colorPrimary">@color/primary_material_settings</item>
+        <item name="colorPrimaryDark">@color/primary_dark_material_settings</item>
     </style>
 
     <style name="Theme.Material.Settings.CompactMenu" parent="Theme.Material.Light.CompactMenu">
-        <item name="colorPrimary">@color/material_blue_grey_900</item>
-        <item name="colorPrimaryDark">@color/material_blue_grey_950</item>
+        <item name="colorPrimary">@color/primary_material_settings</item>
+        <item name="colorPrimaryDark">@color/primary_dark_material_settings</item>
     </style>
 </resources>
diff --git a/docs/html/preview/support.jd b/docs/html/preview/support.jd
index 5328fd8..ef8a652 100644
--- a/docs/html/preview/support.jd
+++ b/docs/html/preview/support.jd
@@ -17,6 +17,7 @@
       <li><a href="#general">General advisories</a></li>
       <li><a href="#new">New in DP4</a></li>
       <li><a href="#ki">Known issues</a></li>
+      <li><a href="#upgrade-notes">Notes on publishing apps that target API 24</a></li>
     </ul>
   </li>
   <li><a href="#dp3">Developer Preview 3</a></li>
@@ -279,6 +280,15 @@
   </li>
 </ul>
 
+<h4 id="">Android Auto</h4>
+
+<p>
+  The version of Google Maps included in Developer Preview 4 (9.30) crashes
+  when used with Android Auto. This issue will be fixed in the next update to
+  Google Maps (9.31), expected in the coming weeks.
+</p>
+
+
 <!-- TBA, if any
 <h4>Device-specific issues</h4>
 
@@ -328,13 +338,34 @@
 
   <li>Additional bluetooth connectivity fixes
   </li>
+
 </ul>
 
 <p>For the full list of fixed issues, see <a href="https://goo.gl/6uCKtf">the
 issue tracker</a>.</p>
 
+<h3 id="upgrade-notes">Notes on publishing apps that target API 24</h3>
 
+<p>
+  Before publishing apps that target API 24 in Google Play, keep these points
+  in mind:
+</p>
 
+<ul>
+  <li>If your app’s current <code>targetSdkVersion</code> is 22 or lower and
+  you want to target API 24, you’ll need to support <a href=
+  "{@docRoot}about/versions/marshmallow/android-6.0-changes.html">behaviors
+  introduced with Android 6.0 (Marshmallow)</a>, such as <a href=
+  "{@docRoot}training/permissions/requesting.html">runtime permissions</a>, in
+  addition to Android N behaviors.
+  </li>
+
+  <li>Once you publish an app with <code>targetSdkVersion</code> set to 23 or
+  higher, you can't later publish a version of the app with a higher
+  <code>versionCode</code> that targets 22 or lower. This restriction applies
+  in alpha and beta channels as well as production channel.
+  </li>
+</ul>
 
 <!-- DP3 Release Notes Archive -->
 
diff --git a/graphics/java/android/graphics/drawable/AnimatedVectorDrawable.java b/graphics/java/android/graphics/drawable/AnimatedVectorDrawable.java
index 6bb93aec..0bdc76f 100644
--- a/graphics/java/android/graphics/drawable/AnimatedVectorDrawable.java
+++ b/graphics/java/android/graphics/drawable/AnimatedVectorDrawable.java
@@ -239,6 +239,17 @@
 
     @Override
     public void draw(Canvas canvas) {
+        if (!canvas.isHardwareAccelerated() && mAnimatorSet instanceof VectorDrawableAnimatorRT) {
+            // If we have SW canvas and the RT animation is waiting to start, We need to fallback
+            // to UI thread animation for AVD.
+            if (!mAnimatorSet.isRunning() &&
+                    ((VectorDrawableAnimatorRT) mAnimatorSet).mPendingAnimationActions.size() > 0) {
+                VectorDrawableAnimatorRT oldAnim = (VectorDrawableAnimatorRT) mAnimatorSet;
+                mAnimatorSet = new VectorDrawableAnimatorUI(this);
+                mAnimatorSet.init(mAnimatorSetFromXml);
+                oldAnim.transferPendingActions(mAnimatorSet);
+            }
+        }
         mAnimatorSet.onDraw(canvas);
         mAnimatedVectorState.mVectorDrawable.draw(canvas);
     }
@@ -1590,6 +1601,25 @@
         private static void callOnFinished(VectorDrawableAnimatorRT set, int id) {
             set.onAnimationEnd(id);
         }
+
+        private void transferPendingActions(VectorDrawableAnimator animatorSet) {
+            for (int i = 0; i < mPendingAnimationActions.size(); i++) {
+                int pendingAction = mPendingAnimationActions.get(i);
+                if (pendingAction == START_ANIMATION) {
+                    animatorSet.start();
+                } else if (pendingAction == END_ANIMATION) {
+                    animatorSet.end();
+                } else if (pendingAction == REVERSE_ANIMATION) {
+                    animatorSet.reverse();
+                } else if (pendingAction == RESET_ANIMATION) {
+                    animatorSet.reset();
+                } else {
+                    throw new UnsupportedOperationException("Animation action " +
+                            pendingAction + "is not supported");
+                }
+            }
+            mPendingAnimationActions.clear();
+        }
     }
 
     private static native long nCreateAnimatorSet();
diff --git a/libs/hwui/RenderNode.cpp b/libs/hwui/RenderNode.cpp
index 5a3300a..f8797bf 100644
--- a/libs/hwui/RenderNode.cpp
+++ b/libs/hwui/RenderNode.cpp
@@ -474,7 +474,7 @@
 }
 #endif
 
-void RenderNode::syncDisplayList(TreeObserver* observer) {
+void RenderNode::syncDisplayList(TreeInfo* info) {
     // Make sure we inc first so that we don't fluctuate between 0 and 1,
     // which would thrash the layer cache
     if (mStagingDisplayList) {
@@ -482,7 +482,7 @@
             child->renderNode->incParentRefCount();
         }
     }
-    deleteDisplayList(observer);
+    deleteDisplayList(info ? info->observer : nullptr, info);
     mDisplayList = mStagingDisplayList;
     mStagingDisplayList = nullptr;
     if (mDisplayList) {
@@ -501,15 +501,15 @@
         // Damage with the old display list first then the new one to catch any
         // changes in isRenderable or, in the future, bounds
         damageSelf(info);
-        syncDisplayList(info.observer);
+        syncDisplayList(&info);
         damageSelf(info);
     }
 }
 
-void RenderNode::deleteDisplayList(TreeObserver* observer) {
+void RenderNode::deleteDisplayList(TreeObserver* observer, TreeInfo* info) {
     if (mDisplayList) {
         for (auto&& child : mDisplayList->getChildren()) {
-            child->renderNode->decParentRefCount(observer);
+            child->renderNode->decParentRefCount(observer, info);
         }
     }
     delete mDisplayList;
@@ -541,35 +541,38 @@
     }
 }
 
-void RenderNode::destroyHardwareResources(TreeObserver* observer) {
+void RenderNode::destroyHardwareResources(TreeObserver* observer, TreeInfo* info) {
     if (mLayer) {
         destroyLayer(mLayer);
         mLayer = nullptr;
     }
     if (mDisplayList) {
         for (auto&& child : mDisplayList->getChildren()) {
-            child->renderNode->destroyHardwareResources(observer);
+            child->renderNode->destroyHardwareResources(observer, info);
         }
         if (mNeedsDisplayListSync) {
             // Next prepare tree we are going to push a new display list, so we can
             // drop our current one now
-            deleteDisplayList(observer);
+            deleteDisplayList(observer, info);
         }
     }
 }
 
-void RenderNode::decParentRefCount(TreeObserver* observer) {
+void RenderNode::decParentRefCount(TreeObserver* observer, TreeInfo* info) {
     LOG_ALWAYS_FATAL_IF(!mParentCount, "already 0!");
     mParentCount--;
     if (!mParentCount) {
         if (observer) {
             observer->onMaybeRemovedFromTree(this);
         }
+        if (CC_UNLIKELY(mPositionListener.get())) {
+            mPositionListener->onPositionLost(*this, info);
+        }
         // If a child of ours is being attached to our parent then this will incorrectly
         // destroy its hardware resources. However, this situation is highly unlikely
         // and the failure is "just" that the layer is re-created, so this should
         // be safe enough
-        destroyHardwareResources(observer);
+        destroyHardwareResources(observer, info);
     }
 }
 
diff --git a/libs/hwui/RenderNode.h b/libs/hwui/RenderNode.h
index acdc3d8..f80be5e 100644
--- a/libs/hwui/RenderNode.h
+++ b/libs/hwui/RenderNode.h
@@ -196,7 +196,7 @@
     }
 
     ANDROID_API virtual void prepareTree(TreeInfo& info);
-    void destroyHardwareResources(TreeObserver* observer);
+    void destroyHardwareResources(TreeObserver* observer, TreeInfo* info = nullptr);
 
     // UI thread only!
     ANDROID_API void addAnimator(const sp<BaseRenderNodeAnimator>& animator);
@@ -228,10 +228,19 @@
     OffscreenBuffer** getLayerHandle() { return &mLayer; } // ugh...
 #endif
 
+    // Note: The position callbacks are relying on the listener using
+    // the frameNumber to appropriately batch/synchronize these transactions.
+    // There is no other filtering/batching to ensure that only the "final"
+    // state called once per frame.
     class ANDROID_API PositionListener {
     public:
         virtual ~PositionListener() {}
+        // Called when the RenderNode's position changes
         virtual void onPositionUpdated(RenderNode& node, const TreeInfo& info) = 0;
+        // Called when the RenderNode no longer has a position. As in, it's
+        // no longer being drawn.
+        // Note, tree info might be null
+        virtual void onPositionLost(RenderNode& node, const TreeInfo* info) = 0;
     };
 
     // Note this is not thread safe, this needs to be called
@@ -306,7 +315,7 @@
 
 
     void syncProperties();
-    void syncDisplayList(TreeObserver* observer);
+    void syncDisplayList(TreeInfo* info);
 
     void prepareTreeImpl(TreeInfo& info, bool functorsNeedLayer);
     void pushStagingPropertiesChanges(TreeInfo& info);
@@ -317,11 +326,11 @@
 #endif
     void prepareLayer(TreeInfo& info, uint32_t dirtyMask);
     void pushLayerUpdate(TreeInfo& info);
-    void deleteDisplayList(TreeObserver* observer);
+    void deleteDisplayList(TreeObserver* observer, TreeInfo* info = nullptr);
     void damageSelf(TreeInfo& info);
 
     void incParentRefCount() { mParentCount++; }
-    void decParentRefCount(TreeObserver* observer);
+    void decParentRefCount(TreeObserver* observer, TreeInfo* info = nullptr);
 
     String8 mName;
     sp<VirtualLightRefBase> mUserContext;
diff --git a/location/java/android/location/LocationManager.java b/location/java/android/location/LocationManager.java
index b246360..2b3ed87 100644
--- a/location/java/android/location/LocationManager.java
+++ b/location/java/android/location/LocationManager.java
@@ -2008,7 +2008,7 @@
      * No-op method to keep backward-compatibility.
      * Don't use it. Use {@link #registerGnssMeasurementsCallback} instead.
      * @hide
-     * @deprecated
+     * @deprecated Not supported anymore.
      */
     @Deprecated
     @SystemApi
@@ -2065,7 +2065,7 @@
      * No-op method to keep backward-compatibility.
      * Don't use it. Use {@link #registerGnssNavigationMessageCallback} instead.
      * @hide
-     * @deprecated
+     * @deprecated Not supported anymore.
      */
     @Deprecated
     @SystemApi
diff --git a/media/jni/android_media_Utils.cpp b/media/jni/android_media_Utils.cpp
index 359ebad..c62d930 100644
--- a/media/jni/android_media_Utils.cpp
+++ b/media/jni/android_media_Utils.cpp
@@ -68,16 +68,19 @@
         if (sizeToRead <= kMinSizeToRead) {
             sizeToRead = kMinSizeToRead;
         }
+
         void* tempBuffer = malloc(sizeToRead);
-        if (tempBuffer != NULL) {
-            size_t bytesRead = mStream->read(tempBuffer, sizeToRead);
-            if (bytesRead != sizeToRead) {
-                free(tempBuffer);
-                return piex::Error::kFail;
-            }
-            mStreamBuffer.write(tempBuffer, bytesRead);
-            free(tempBuffer);
+        if (tempBuffer == NULL) {
+          return piex::Error::kFail;
         }
+
+        size_t bytesRead = mStream->read(tempBuffer, sizeToRead);
+        if (bytesRead != sizeToRead) {
+            free(tempBuffer);
+            return piex::Error::kFail;
+        }
+        mStreamBuffer.write(tempBuffer, bytesRead);
+        free(tempBuffer);
     }
 
     // Read bytes.
@@ -126,8 +129,8 @@
     size_t size = fread((void*)data, sizeof(std::uint8_t), length, mFile);
     mPosition += size;
 
-    // Handle errors.
-    if (ferror(mFile)) {
+    // Handle errors and verify the size.
+    if (ferror(mFile) || size != length) {
         ALOGV("GetData read failed: (offset: %zu, length: %zu)", offset, length);
         return piex::Error::kFail;
     }
diff --git a/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java b/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java
index f10af43..53fa3cc4 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java
@@ -227,7 +227,7 @@
         try {
             mBatchSize = calculateSize(mSrcs);
         } catch (ResourceException e) {
-            Log.w(TAG, "Failed to calculate total size. Copying without progress.");
+            Log.w(TAG, "Failed to calculate total size. Copying without progress.", e);
             mBatchSize = -1;
         }
 
@@ -236,25 +236,19 @@
         for (int i = 0; i < mSrcs.size() && !isCanceled(); ++i) {
             srcInfo = mSrcs.get(i);
 
-            // Guard unsupported recursive operation.
-            try {
-                if (dstInfo.equals(srcInfo) || isDescendentOf(srcInfo, dstInfo)) {
-                    throw new ResourceException("Cannot copy to itself recursively.");
-                }
-            } catch (ResourceException e) {
-                Log.e(TAG, e.toString());
-                onFileFailed(srcInfo);
-                continue;
-            }
-
             if (DEBUG) Log.d(TAG,
                     "Copying " + srcInfo.displayName + " (" + srcInfo.derivedUri + ")"
                     + " to " + dstInfo.displayName + " (" + dstInfo.derivedUri + ")");
 
             try {
-                processDocument(srcInfo, null, dstInfo);
+                if (dstInfo.equals(srcInfo) || isDescendentOf(srcInfo, dstInfo)) {
+                    Log.e(TAG, "Skipping recursive copy of " + srcInfo.derivedUri);
+                    onFileFailed(srcInfo);
+                } else {
+                    processDocument(srcInfo, null, dstInfo);
+                }
             } catch (ResourceException e) {
-                Log.e(TAG, e.toString());
+                Log.e(TAG, "Failed to copy " + srcInfo.derivedUri, e);
                 onFileFailed(srcInfo);
             }
         }
@@ -306,7 +300,7 @@
                     }
                 } catch (RemoteException | RuntimeException e) {
                     Log.e(TAG, "Provider side copy failed for: " + src.derivedUri
-                            + " due to an exception: " + e);
+                            + " due to an exception.", e);
                 }
                 // If optimized copy fails, then fallback to byte-by-byte copy.
                 if (DEBUG) Log.d(TAG, "Fallback to byte-by-byte copy for: " + src.derivedUri);
diff --git a/packages/DocumentsUI/src/com/android/documentsui/services/DeleteJob.java b/packages/DocumentsUI/src/com/android/documentsui/services/DeleteJob.java
index 8f45162..36a0f32 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/services/DeleteJob.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/services/DeleteJob.java
@@ -86,7 +86,7 @@
             try {
                 deleteDocument(doc, mSrcParent);
             } catch (ResourceException e) {
-                Log.e(TAG, "Failed to delete document @ " + doc.derivedUri);
+                Log.e(TAG, "Failed to delete document @ " + doc.derivedUri, e);
                 onFileFailed(doc);
             }
         }
diff --git a/packages/DocumentsUI/src/com/android/documentsui/services/MoveJob.java b/packages/DocumentsUI/src/com/android/documentsui/services/MoveJob.java
index aaa7596..1118171 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/services/MoveJob.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/services/MoveJob.java
@@ -98,7 +98,7 @@
                     }
                 } catch (RemoteException | RuntimeException e) {
                     Log.e(TAG, "Provider side move failed for: " + src.derivedUri
-                            + " due to an exception: " + e);
+                            + " due to an exception: ", e);
                 }
                 // If optimized move fails, then fallback to byte-by-byte copy.
                 if (DEBUG) Log.d(TAG, "Fallback to byte-by-byte move for: " + src.derivedUri);
diff --git a/packages/SettingsLib/src/com/android/settingslib/HelpUtils.java b/packages/SettingsLib/src/com/android/settingslib/HelpUtils.java
index 76ba0a7..5791168 100644
--- a/packages/SettingsLib/src/com/android/settingslib/HelpUtils.java
+++ b/packages/SettingsLib/src/com/android/settingslib/HelpUtils.java
@@ -24,6 +24,7 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.res.Resources.Theme;
+import android.content.res.TypedArray;
 import android.net.Uri;
 import android.text.TextUtils;
 import android.util.Log;
@@ -162,10 +163,9 @@
             intent.putExtra(EXTRA_CONTEXT, backupContext);
         }
         intent.putExtra(EXTRA_THEME, 1 /* Light, dark action bar */);
-        Theme theme = context.getTheme();
-        TypedValue typedValue = new TypedValue();
-        theme.resolveAttribute(android.R.attr.colorPrimary, typedValue, true);
-        intent.putExtra(EXTRA_PRIMARY_COLOR, context.getColor(typedValue.resourceId));
+        TypedArray array = context.obtainStyledAttributes(new int[]{android.R.attr.colorPrimary});
+        intent.putExtra(EXTRA_PRIMARY_COLOR, array.getColor(0, 0));
+        array.recycle();
     }
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java b/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
index 109d2c2..e9a03f2 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
@@ -72,6 +72,8 @@
     private QSCustomizer mCustomizePanel;
     private Record mDetailRecord;
 
+    private BrightnessMirrorController mBrightnessMirrorController;
+
     public QSPanel(Context context) {
         this(context, null);
     }
@@ -157,7 +159,7 @@
     }
 
     public void setBrightnessMirror(BrightnessMirrorController c) {
-        super.onFinishInflate();
+        mBrightnessMirrorController = c;
         ToggleSlider brightnessSlider = (ToggleSlider) findViewById(R.id.brightness_slider);
         ToggleSlider mirror = (ToggleSlider) c.getMirror().findViewById(R.id.brightness_slider);
         brightnessSlider.setMirror(mirror);
@@ -203,6 +205,11 @@
     protected void onConfigurationChanged(Configuration newConfig) {
         super.onConfigurationChanged(newConfig);
         mFooter.onConfigurationChanged();
+
+        if (mBrightnessMirrorController != null) {
+            // Reload the mirror in case it got reinflated but we didn't.
+            setBrightnessMirror(mBrightnessMirrorController);
+        }
     }
 
     public void onCollapse() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
index 91889d3..542b258 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
@@ -134,6 +134,7 @@
             = SystemProperties.getBoolean("debug.child_notifs", true);
     public static final boolean FORCE_REMOTE_INPUT_HISTORY =
             SystemProperties.getBoolean("debug.force_remoteinput_history", false);
+    private static boolean ENABLE_LOCK_SCREEN_ALLOW_REMOTE_INPUT = false;
 
     protected static final int MSG_SHOW_RECENT_APPS = 1019;
     protected static final int MSG_HIDE_RECENT_APPS = 1020;
@@ -704,10 +705,13 @@
                 Settings.Secure.getUriFor(Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS), false,
                 mSettingsObserver,
                 UserHandle.USER_ALL);
-        mContext.getContentResolver().registerContentObserver(
-                Settings.Secure.getUriFor(Settings.Secure.LOCK_SCREEN_ALLOW_REMOTE_INPUT), false,
-                mSettingsObserver,
-                UserHandle.USER_ALL);
+        if (ENABLE_LOCK_SCREEN_ALLOW_REMOTE_INPUT) {
+            mContext.getContentResolver().registerContentObserver(
+                    Settings.Secure.getUriFor(Settings.Secure.LOCK_SCREEN_ALLOW_REMOTE_INPUT),
+                    false,
+                    mSettingsObserver,
+                    UserHandle.USER_ALL);
+        }
 
         mContext.getContentResolver().registerContentObserver(
                 Settings.Secure.getUriFor(Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS),
@@ -2304,16 +2308,20 @@
         final boolean allowedByDpm = (dpmFlags
                 & DevicePolicyManager.KEYGUARD_DISABLE_SECURE_NOTIFICATIONS) == 0;
 
-        final boolean remoteInput = Settings.Secure.getIntForUser(mContext.getContentResolver(),
-                Settings.Secure.LOCK_SCREEN_ALLOW_REMOTE_INPUT,
-                0,
-                mCurrentUserId) != 0;
-        final boolean remoteInputDpm = (dpmFlags
-                & DevicePolicyManager.KEYGUARD_DISABLE_REMOTE_INPUT) == 0;
-
-
         setShowLockscreenNotifications(show && allowedByDpm);
-        setLockScreenAllowRemoteInput(remoteInput && remoteInputDpm);
+
+        if (ENABLE_LOCK_SCREEN_ALLOW_REMOTE_INPUT) {
+            final boolean remoteInput = Settings.Secure.getIntForUser(mContext.getContentResolver(),
+                    Settings.Secure.LOCK_SCREEN_ALLOW_REMOTE_INPUT,
+                    0,
+                    mCurrentUserId) != 0;
+            final boolean remoteInputDpm =
+                    (dpmFlags & DevicePolicyManager.KEYGUARD_DISABLE_REMOTE_INPUT) == 0;
+
+            setLockScreenAllowRemoteInput(remoteInput && remoteInputDpm);
+        } else {
+            setLockScreenAllowRemoteInput(false);
+        }
     }
 
     protected abstract void setAreThereNotifications();
diff --git a/proto/src/metrics_constants.proto b/proto/src/metrics_constants.proto
index 5527a41..4ed0913 100644
--- a/proto/src/metrics_constants.proto
+++ b/proto/src/metrics_constants.proto
@@ -2323,6 +2323,20 @@
     // Deletion helper encountered an error during photo and video deletion.
     ACTION_DELETION_HELPER_PHOTOS_VIDEOS_DELETION_FAIL = 473;
 
+    // OPEN: Settings (root page if there are multiple tabs)
+    // CATEGORY: SETTINGS
+    DASHBOARD_CONTAINER = 474;
+
+    // OPEN: Settings -> SUPPORT TAB
+    // CATEGORY: SETTINGS
+    SUPPORT_FRAGMENT = 475;
+
+    // ACTION: Settings -> Select summary tab.
+    ACTION_SELECT_SUMMARY=476;
+
+    // ACTION: Settings -> Select support tab.
+    ACTION_SELECT_SUPPORT_FRAGMENT = 477;
+
     // ---- End N-MR1 Constants, all N-MR1 constants go above this line ----
     // Add new aosp constants above this line.
     // END OF AOSP CONSTANTS
diff --git a/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java b/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
index 04a0990..feceb14 100644
--- a/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
+++ b/services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
@@ -20,6 +20,7 @@
 import static android.content.Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS;
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
 
+import android.annotation.UserIdInt;
 import android.app.AlarmManager;
 import android.app.AppGlobals;
 import android.app.AppOpsManager;
@@ -67,6 +68,7 @@
 import android.os.SystemClock;
 import android.os.UserHandle;
 import android.os.UserManager;
+import android.os.storage.StorageManager;
 import android.text.TextUtils;
 import android.util.ArraySet;
 import android.util.AtomicFile;
@@ -650,7 +652,7 @@
     }
 
     private void ensureGroupStateLoadedLocked(int userId, boolean enforceUserUnlockingOrUnlocked) {
-        if (enforceUserUnlockingOrUnlocked && !mUserManager.isUserUnlockingOrUnlocked(userId)) {
+        if (enforceUserUnlockingOrUnlocked && !isUserRunningAndUnlocked(userId)) {
             throw new IllegalStateException(
                     "User " + userId + " must be unlocked for widgets to be available");
         }
@@ -695,6 +697,10 @@
         loadGroupStateLocked(newProfileIds);
     }
 
+    private boolean isUserRunningAndUnlocked(@UserIdInt int userId) {
+        return mUserManager.isUserRunning(userId) && StorageManager.isUserKeyUnlocked(userId);
+    }
+
     @Override
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP,
@@ -3381,7 +3387,7 @@
             if (userInfo != null && userInfo.isManagedProfile()) {
                 UserInfo parentInfo = mUserManager.getProfileParent(userId);
                 if (parentInfo != null
-                        && !mUserManager.isUserUnlockingOrUnlocked(parentInfo.getUserHandle())) {
+                        && !isUserRunningAndUnlocked(parentInfo.getUserHandle().getIdentifier())) {
                     return true;
                 }
             }
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index 334b228..930c151b 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -2356,7 +2356,8 @@
             mConnecting = true;
             mConnectedAgent = null;
             try {
-                if (mActivityManager.bindBackupAgent(app, mode)) {
+                if (mActivityManager.bindBackupAgent(app.packageName, mode,
+                        UserHandle.USER_OWNER)) {
                     Slog.d(TAG, "awaiting agent for " + app);
 
                     // success; wait for the agent to arrive
diff --git a/services/core/java/com/android/server/DeviceIdleController.java b/services/core/java/com/android/server/DeviceIdleController.java
index bb966f7..afed5ef 100644
--- a/services/core/java/com/android/server/DeviceIdleController.java
+++ b/services/core/java/com/android/server/DeviceIdleController.java
@@ -212,7 +212,6 @@
 
     private int mActiveIdleOpCount;
     private PowerManager.WakeLock mActiveIdleWakeLock;
-    private IBinder mDownloadServiceActive;
     private boolean mJobsActive;
     private boolean mAlarmsActive;
     private boolean mReportedMaintenanceActivity;
@@ -607,7 +606,7 @@
          * This is the minimum amount of time that we will stay in maintenance mode after
          * a light doze.  We have this minimum to allow various things to respond to switching
          * in to maintenance mode and scheduling their work -- otherwise we may
-         * see there is nothing to do (no jobs or downloads pending) and go out of maintenance
+         * see there is nothing to do (no jobs pending) and go out of maintenance
          * mode immediately.
          * @see Settings.Global#DEVICE_IDLE_CONSTANTS
          * @see #KEY_MIN_LIGHT_MAINTENANCE_TIME
@@ -618,7 +617,7 @@
          * This is the minimum amount of time that we will stay in maintenance mode after
          * a full doze.  We have this minimum to allow various things to respond to switching
          * in to maintenance mode and scheduling their work -- otherwise we may
-         * see there is nothing to do (no jobs or downloads pending) and go out of maintenance
+         * see there is nothing to do (no jobs pending) and go out of maintenance
          * mode immediately.
          * @see Settings.Global#DEVICE_IDLE_CONSTANTS
          * @see #KEY_MIN_DEEP_MAINTENANCE_TIME
@@ -1220,28 +1219,6 @@
             }
         }
 
-        @Override public void downloadServiceActive(IBinder token) {
-            getContext().enforceCallingOrSelfPermission(
-                    "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS", null);
-            long ident = Binder.clearCallingIdentity();
-            try {
-                DeviceIdleController.this.downloadServiceActive(token);
-            } finally {
-                Binder.restoreCallingIdentity(ident);
-            }
-        }
-
-        @Override public void downloadServiceInactive() {
-            getContext().enforceCallingOrSelfPermission(
-                    "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS", null);
-            long ident = Binder.clearCallingIdentity();
-            try {
-                DeviceIdleController.this.downloadServiceInactive();
-            } finally {
-                Binder.restoreCallingIdentity(ident);
-            }
-        }
-
         @Override public boolean registerMaintenanceActivityListener(
                 IMaintenanceActivityListener listener) {
             return DeviceIdleController.this.registerMaintenanceActivityListener(listener);
@@ -2086,30 +2063,6 @@
         }
     }
 
-    void downloadServiceActive(IBinder token) {
-        synchronized (this) {
-            mDownloadServiceActive = token;
-            reportMaintenanceActivityIfNeededLocked();
-            try {
-                token.linkToDeath(new IBinder.DeathRecipient() {
-                    @Override public void binderDied() {
-                        downloadServiceInactive();
-                    }
-                }, 0);
-            } catch (RemoteException e) {
-                mDownloadServiceActive = null;
-            }
-        }
-    }
-
-    void downloadServiceInactive() {
-        synchronized (this) {
-            mDownloadServiceActive = null;
-            reportMaintenanceActivityIfNeededLocked();
-            exitMaintenanceEarlyIfNeededLocked();
-        }
-    }
-
     void setJobsActive(boolean active) {
         synchronized (this) {
             mJobsActive = active;
@@ -2143,7 +2096,7 @@
     }
 
     void reportMaintenanceActivityIfNeededLocked() {
-        boolean active = mJobsActive | (mDownloadServiceActive != null);
+        boolean active = mJobsActive;
         if (active == mReportedMaintenanceActivity) {
             return;
         }
@@ -2154,8 +2107,7 @@
     }
 
     boolean isOpsInactiveLocked() {
-        return mActiveIdleOpCount <= 0 && mDownloadServiceActive == null
-                && !mJobsActive && !mAlarmsActive;
+        return mActiveIdleOpCount <= 0 && !mJobsActive && !mAlarmsActive;
     }
 
     void exitMaintenanceEarlyIfNeededLocked() {
@@ -3053,9 +3005,6 @@
             if (mAlarmsActive) {
                 pw.print("  mAlarmsActive="); pw.println(mAlarmsActive);
             }
-            if (mDownloadServiceActive != null) {
-                pw.print("  mDownloadServiceActive="); pw.println(mDownloadServiceActive);
-            }
         }
     }
 
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 2c7ef7e..bfc9877 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -17041,11 +17041,22 @@
     // Cause the target app to be launched if necessary and its backup agent
     // instantiated.  The backup agent will invoke backupAgentCreated() on the
     // activity manager to announce its creation.
-    public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
-        if (DEBUG_BACKUP) Slog.v(TAG_BACKUP,
-                "bindBackupAgent: app=" + app + " mode=" + backupMode);
+    public boolean bindBackupAgent(String packageName, int backupMode, int userId) {
+        if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode);
         enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent");
 
+        IPackageManager pm = AppGlobals.getPackageManager();
+        ApplicationInfo app = null;
+        try {
+            app = pm.getApplicationInfo(packageName, 0, userId);
+        } catch (RemoteException e) {
+            // can't happen; package manager is process-local
+        }
+        if (app == null) {
+            Slog.w(TAG, "Unable to bind backup agent for " + packageName);
+            return false;
+        }
+
         synchronized(this) {
             // !!! TODO: currently no check here that we're already bound
             BatteryStatsImpl.Uid.Pkg.Serv ss = null;
@@ -18714,7 +18725,7 @@
                 starting = mainStack.topRunningActivityLocked();
             }
 
-            if (starting != null) {
+            if (starting != null && starting.state != ActivityState.STOPPED) {
                 kept = mainStack.ensureActivityConfigurationLocked(starting, changes, false);
                 // And we need to make sure at this point that all other activities
                 // are made visible with the correct configuration.
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index d83a750..0513b1a 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -1820,7 +1820,8 @@
             boolean stackVisibleBehind, ActivityRecord visibleBehind,
             boolean behindFullscreenActivity) {
 
-        if (!okToShowLocked(r)) {
+        if (!okToShowLocked(r)
+                || (mService.isSleepingOrShuttingDown() && r.voiceSession == null)) {
             return false;
         }
 
@@ -5177,7 +5178,8 @@
                 r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
                 (r.info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0, r.userId, r.info.configChanges,
                 task.voiceSession != null, r.mLaunchTaskBehind, bounds, task.mOverrideConfig,
-                task.mResizeMode, r.isAlwaysFocusable(), task.isHomeTask());
+                task.mResizeMode, r.isAlwaysFocusable(), task.isHomeTask(),
+                r.appInfo.targetSdkVersion);
         r.taskConfigOverride = task.mOverrideConfig;
     }
 
diff --git a/services/core/java/com/android/server/am/ActivityStarter.java b/services/core/java/com/android/server/am/ActivityStarter.java
index 793f411..a5a7db9 100644
--- a/services/core/java/com/android/server/am/ActivityStarter.java
+++ b/services/core/java/com/android/server/am/ActivityStarter.java
@@ -1494,14 +1494,23 @@
                                 intentActivity.task, mNoAnimation, mOptions,
                                 mStartActivity.appTimeTracker, "bringingFoundTaskToFront");
                         mMovedToFront = true;
-                    } else if ((launchStack.mStackId == DOCKED_STACK_ID
-                            || launchStack.mStackId == FULLSCREEN_WORKSPACE_STACK_ID)
-                            && (mLaunchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) != 0) {
-                        // If we want to launch adjacent and mTargetStack is not the computed
-                        // launch stack - move task to top of computed stack.
-                        mSupervisor.moveTaskToStackLocked(intentActivity.task.taskId,
-                                launchStack.mStackId, ON_TOP, FORCE_FOCUS, "launchToSide",
-                                ANIMATE);
+                    } else if (launchStack.mStackId == DOCKED_STACK_ID
+                            || launchStack.mStackId == FULLSCREEN_WORKSPACE_STACK_ID) {
+                        if ((mLaunchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) != 0) {
+                            // If we want to launch adjacent and mTargetStack is not the computed
+                            // launch stack - move task to top of computed stack.
+                            mSupervisor.moveTaskToStackLocked(intentActivity.task.taskId,
+                                    launchStack.mStackId, ON_TOP, FORCE_FOCUS, "launchToSide",
+                                    ANIMATE);
+                        } else {
+                            // TODO: This should be reevaluated in MW v2.
+                            // We choose to move task to front instead of launching it adjacent
+                            // when specific stack was requested explicitly and it appeared to be
+                            // adjacent stack, but FLAG_ACTIVITY_LAUNCH_ADJACENT was not set.
+                            mTargetStack.moveTaskToFrontLocked(intentActivity.task, mNoAnimation,
+                                    mOptions, mStartActivity.appTimeTracker,
+                                    "bringToFrontInsteadOfAdjacentLaunch");
+                        }
                         mMovedToFront = true;
                     }
                     mOptions = null;
diff --git a/services/core/java/com/android/server/job/JobSchedulerService.java b/services/core/java/com/android/server/job/JobSchedulerService.java
index 27b3aa2..8589de1 100644
--- a/services/core/java/com/android/server/job/JobSchedulerService.java
+++ b/services/core/java/com/android/server/job/JobSchedulerService.java
@@ -692,8 +692,13 @@
         boolean active = mPendingJobs.size() > 0;
         if (mPendingJobs.size() <= 0) {
             for (int i=0; i<mActiveServices.size(); i++) {
-                JobServiceContext jsc = mActiveServices.get(i);
-                if (jsc.getRunningJob() != null) {
+                final JobServiceContext jsc = mActiveServices.get(i);
+                final JobStatus job = jsc.getRunningJob();
+                if (job != null
+                        && (job.getJob().getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) == 0
+                        && !job.dozeWhitelisted) {
+                    // We will report active if we have a job running and it is not an exception
+                    // due to being in the foreground or whitelisted.
                     active = true;
                     break;
                 }
diff --git a/services/core/java/com/android/server/job/controllers/AppIdleController.java b/services/core/java/com/android/server/job/controllers/AppIdleController.java
index a23af35..2dbecbd 100644
--- a/services/core/java/com/android/server/job/controllers/AppIdleController.java
+++ b/services/core/java/com/android/server/job/controllers/AppIdleController.java
@@ -142,8 +142,11 @@
                 UserHandle.formatUid(pw, jobStatus.getSourceUid());
                 pw.print(": ");
                 pw.print(jobStatus.getSourcePackageName());
-                pw.print(", runnable=");
-                pw.println((jobStatus.satisfiedConstraints&JobStatus.CONSTRAINT_APP_NOT_IDLE) != 0);
+                if ((jobStatus.satisfiedConstraints&JobStatus.CONSTRAINT_APP_NOT_IDLE) != 0) {
+                    pw.println(" RUNNABLE");
+                } else {
+                    pw.println(" WAITING");
+                }
             }
         });
     }
diff --git a/services/core/java/com/android/server/job/controllers/DeviceIdleJobsController.java b/services/core/java/com/android/server/job/controllers/DeviceIdleJobsController.java
index bf1297f..f7706d7 100644
--- a/services/core/java/com/android/server/job/controllers/DeviceIdleJobsController.java
+++ b/services/core/java/com/android/server/job/controllers/DeviceIdleJobsController.java
@@ -157,8 +157,9 @@
     }
 
     private void updateTaskStateLocked(JobStatus task) {
-        boolean enableTask = !mDeviceIdleMode || isWhitelistedLocked(task);
-        task.setDeviceNotDozingConstraintSatisfied(enableTask);
+        final boolean whitelisted = isWhitelistedLocked(task);
+        final boolean enableTask = !mDeviceIdleMode || whitelisted;
+        task.setDeviceNotDozingConstraintSatisfied(enableTask, whitelisted);
     }
 
     @Override
@@ -186,9 +187,13 @@
                 UserHandle.formatUid(pw, jobStatus.getSourceUid());
                 pw.print(": ");
                 pw.print(jobStatus.getSourcePackageName());
-                pw.print(", runnable=");
-                pw.println((jobStatus.satisfiedConstraints
-                        & JobStatus.CONSTRAINT_DEVICE_NOT_DOZING) != 0);
+                pw.print((jobStatus.satisfiedConstraints
+                        & JobStatus.CONSTRAINT_DEVICE_NOT_DOZING) != 0
+                                ? " RUNNABLE" : " WAITING");
+                if (jobStatus.dozeWhitelisted) {
+                    pw.print(" WHITELISTED");
+                }
+                pw.println();
             }
         });
     }
diff --git a/services/core/java/com/android/server/job/controllers/JobStatus.java b/services/core/java/com/android/server/job/controllers/JobStatus.java
index ded7a2f..552c990 100644
--- a/services/core/java/com/android/server/job/controllers/JobStatus.java
+++ b/services/core/java/com/android/server/job/controllers/JobStatus.java
@@ -103,6 +103,9 @@
     final int requiredConstraints;
     int satisfiedConstraints = 0;
 
+    // Set to true if doze constraint was satisfied due to app being whitelisted.
+    public boolean dozeWhitelisted;
+
     // These are filled in by controllers when preparing for execution.
     public ArraySet<Uri> changedUris;
     public ArraySet<String> changedAuthorities;
@@ -403,7 +406,8 @@
         return setConstraintSatisfied(CONSTRAINT_CONTENT_TRIGGER, state);
     }
 
-    boolean setDeviceNotDozingConstraintSatisfied(boolean state) {
+    boolean setDeviceNotDozingConstraintSatisfied(boolean state, boolean whitelisted) {
+        dozeWhitelisted = whitelisted;
         return setConstraintSatisfied(CONSTRAINT_DEVICE_NOT_DOZING, state);
     }
 
@@ -651,6 +655,9 @@
             pw.print(prefix); pw.print("Unsatisfied constraints:");
             dumpConstraints(pw, (requiredConstraints & ~satisfiedConstraints));
             pw.println();
+            if (dozeWhitelisted) {
+                pw.print(prefix); pw.println("Doze whitelisted: true");
+            }
         }
         if (changedAuthorities != null) {
             pw.print(prefix); pw.println("Changed authorities:");
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index 0af0c73..d4ee02e 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -2614,17 +2614,18 @@
     private static void setPendingIntentWhitelistDuration(ActivityManagerInternal am, long duration,
             Bundle extras) {
         for (String key : extras.keySet()) {
-            setPendingIntentWhitelistDuration(am, duration, extras.getParcelable(key));
-            final Parcelable[] parcelableArray = extras.getParcelableArray(key);
-            if (parcelableArray != null) {
-                for (Parcelable parcelable: parcelableArray) {
+            final Object value = extras.get(key);
+            if (value instanceof Parcelable) {
+                setPendingIntentWhitelistDuration(am, duration, (Parcelable) value);
+            } else if (value instanceof Parcelable[]) {
+                for (Parcelable parcelable : (Parcelable[]) value) {
                     setPendingIntentWhitelistDuration(am, duration, parcelable);
                 }
-            }
-            final ArrayList<Parcelable> parcelableList = extras.getParcelableArrayList(key);
-            if (parcelableList != null) {
-                for (Parcelable parcelable: parcelableList) {
-                    setPendingIntentWhitelistDuration(am, duration, parcelable);
+            } else if (value instanceof List) {
+                for (Object element : (List <?>) value) {
+                    if (element instanceof Parcelable) {
+                        setPendingIntentWhitelistDuration(am, duration, (Parcelable) element);
+                    }
                 }
             }
         }
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index 0bf0cac..02a2b2c 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -2303,7 +2303,7 @@
      */
     @Override
     public UserInfo createRestrictedProfile(String name, int parentUserId) {
-        checkManageUsersPermission("setupRestrictedProfile");
+        checkManageOrCreateUsersPermission("setupRestrictedProfile");
         final UserInfo user = createProfileForUser(name, UserInfo.FLAG_RESTRICTED, parentUserId);
         if (user == null) {
             return null;
diff --git a/services/core/java/com/android/server/wm/AppWindowToken.java b/services/core/java/com/android/server/wm/AppWindowToken.java
index f57e83aa..b907da6 100644
--- a/services/core/java/com/android/server/wm/AppWindowToken.java
+++ b/services/core/java/com/android/server/wm/AppWindowToken.java
@@ -72,6 +72,7 @@
     int requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
     boolean layoutConfigChanges;
     boolean showForAllUsers;
+    int targetSdk;
 
     // The input dispatching timeout for this application token in nanoseconds.
     long inputDispatchingTimeoutNanos;
diff --git a/services/core/java/com/android/server/wm/DragState.java b/services/core/java/com/android/server/wm/DragState.java
index c4eca08..9d0fb61 100644
--- a/services/core/java/com/android/server/wm/DragState.java
+++ b/services/core/java/com/android/server/wm/DragState.java
@@ -28,6 +28,7 @@
 import android.graphics.Matrix;
 import android.graphics.Point;
 import android.hardware.input.InputManager;
+import android.os.Build;
 import android.os.IBinder;
 import android.os.Message;
 import android.os.Process;
@@ -289,7 +290,7 @@
         if (!targetWin.isPotentialDragTarget()) {
             return false;
         }
-        if ((mFlags & View.DRAG_FLAG_GLOBAL) == 0) {
+        if ((mFlags & View.DRAG_FLAG_GLOBAL) == 0 || !targetWindowSupportsGlobalDrag(targetWin)) {
             // Drag is limited to the current window.
             if (mLocalWin != targetWin.mClient.asBinder()) {
                 return false;
@@ -300,6 +301,13 @@
                 mSourceUserId == UserHandle.getUserId(targetWin.getOwningUid());
     }
 
+    private boolean targetWindowSupportsGlobalDrag(WindowState targetWin) {
+        // Global drags are limited to system windows, and windows for apps that are targeting N and
+        // above.
+        return targetWin.mAppToken == null
+                || targetWin.mAppToken.targetSdk >= Build.VERSION_CODES.N;
+    }
+
     /* helper - send a ACTION_DRAG_STARTED event only if the window has not
      * previously been notified, i.e. it became visible after the drag operation
      * was begun.  This is a rare case.
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 8474fcf..36875123 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -3420,7 +3420,7 @@
             int requestedOrientation, boolean fullscreen, boolean showForAllUsers, int userId,
             int configChanges, boolean voiceInteraction, boolean launchTaskBehind,
             Rect taskBounds, Configuration config, int taskResizeMode, boolean alwaysFocusable,
-            boolean homeTask) {
+            boolean homeTask, int targetSdkVersion) {
         if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
                 "addAppToken()")) {
             throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
@@ -3450,6 +3450,7 @@
             atoken.inputDispatchingTimeoutNanos = inputDispatchingTimeoutNanos;
             atoken.appFullscreen = fullscreen;
             atoken.showForAllUsers = showForAllUsers;
+            atoken.targetSdk = targetSdkVersion;
             atoken.requestedOrientation = requestedOrientation;
             atoken.layoutConfigChanges = (configChanges &
                     (ActivityInfo.CONFIG_SCREEN_SIZE | ActivityInfo.CONFIG_ORIENTATION)) != 0;
diff --git a/telephony/java/android/telephony/TelephonyHistogram.java b/telephony/java/android/telephony/TelephonyHistogram.java
index 9d9ce72..e1c3d7b 100644
--- a/telephony/java/android/telephony/TelephonyHistogram.java
+++ b/telephony/java/android/telephony/TelephonyHistogram.java
@@ -31,35 +31,35 @@
 public final class TelephonyHistogram implements Parcelable {
     // Type of Telephony histogram Eg: RIL histogram will have all timing data associated with
     // RIL calls. Similarly we can have any other Telephony histogram.
-    private final int category;
+    private final int mCategory;
 
     // Unique Id identifying a sample within particular category of histogram
-    private final int id;
+    private final int mId;
 
     // Min time taken in ms
-    private int minTimeMs;
+    private int mMinTimeMs;
 
     // Max time taken in ms
-    private int maxTimeMs;
+    private int mMaxTimeMs;
 
     // Average time taken in ms
-    private int averageTimeMs;
+    private int mAverageTimeMs;
 
     // Total count of samples
-    private int sampleCount;
+    private int mSampleCount;
 
     // Array storing time taken for first #RANGE_CALCULATION_COUNT samples of histogram.
-    private int[] initialTimings;
+    private int[] mInitialTimings;
 
     // Total number of time ranges expected (must be greater than 1)
-    private final int bucketCount;
+    private final int mBucketCount;
 
     // Array storing endpoints of range buckets. Calculated based on values of minTime & maxTime
     // after totalTimeCount is #RANGE_CALCULATION_COUNT.
-    private final int[] bucketEndPoints;
+    private final int[] mBucketEndPoints;
 
     // Array storing counts for each time range starting from smallest value range
-    private final int[] bucketCounters;
+    private final int[] mBucketCounters;
 
     /**
      * Constant for Telephony category
@@ -81,69 +81,85 @@
         if (bucketCount <= 1) {
             throw new IllegalArgumentException("Invalid number of buckets");
         }
-        this.category = category;
-        this.id = id;
-        this.minTimeMs = Integer.MAX_VALUE;
-        this.maxTimeMs = 0;
-        this.averageTimeMs = 0;
-        this.sampleCount = 0;
-        initialTimings = new int[RANGE_CALCULATION_COUNT];
-        this.bucketCount = bucketCount;
-        bucketEndPoints = new int[bucketCount - 1];
-        bucketCounters = new int[bucketCount];
+        mCategory = category;
+        mId = id;
+        mMinTimeMs = Integer.MAX_VALUE;
+        mMaxTimeMs = 0;
+        mAverageTimeMs = 0;
+        mSampleCount = 0;
+        mInitialTimings = new int[RANGE_CALCULATION_COUNT];
+        mBucketCount = bucketCount;
+        mBucketEndPoints = new int[bucketCount - 1];
+        mBucketCounters = new int[bucketCount];
     }
 
     public TelephonyHistogram(TelephonyHistogram th) {
-        category = th.getCategory();
-        id = th.getId();
-        minTimeMs = th.getMinTime();
-        maxTimeMs = th.getMaxTime();
-        averageTimeMs = th.getAverageTime();
-        sampleCount = th.getSampleCount();
-        initialTimings = th.getInitialTimings();
-        bucketCount = th.getBucketCount();
-        bucketEndPoints = th.getBucketEndPoints();
-        bucketCounters = th.getBucketCounters();
+        mCategory = th.getCategory();
+        mId = th.getId();
+        mMinTimeMs = th.getMinTime();
+        mMaxTimeMs = th.getMaxTime();
+        mAverageTimeMs = th.getAverageTime();
+        mSampleCount = th.getSampleCount();
+        mInitialTimings = th.getInitialTimings();
+        mBucketCount = th.getBucketCount();
+        mBucketEndPoints = th.getBucketEndPoints();
+        mBucketCounters = th.getBucketCounters();
     }
 
     public int getCategory() {
-        return category;
+        return mCategory;
     }
 
     public int getId() {
-        return id;
+        return mId;
     }
 
     public int getMinTime() {
-        return minTimeMs;
+        return mMinTimeMs;
     }
 
     public int getMaxTime() {
-        return maxTimeMs;
+        return mMaxTimeMs;
     }
 
     public int getAverageTime() {
-        return averageTimeMs;
+        return mAverageTimeMs;
     }
 
     public int getSampleCount () {
-        return sampleCount;
+        return mSampleCount;
     }
 
     private int[] getInitialTimings() {
-        return initialTimings;
+        return mInitialTimings;
     }
 
     public int getBucketCount() {
-        return bucketCount;
+        return mBucketCount;
     }
 
     public int[] getBucketEndPoints() {
-        return getDeepCopyOfArray(bucketEndPoints);
+        if (mSampleCount > 1 && mSampleCount < 10) {
+            int[] tempEndPoints = new int[mBucketCount - 1];
+            calculateBucketEndPoints(tempEndPoints);
+            return tempEndPoints;
+        } else {
+            return getDeepCopyOfArray(mBucketEndPoints);
+        }
     }
 
     public int[] getBucketCounters() {
-        return getDeepCopyOfArray(bucketCounters);
+        if (mSampleCount > 1 && mSampleCount < 10) {
+            int[] tempEndPoints = new int[mBucketCount - 1];
+            int[] tempBucketCounters = new int[mBucketCount];
+            calculateBucketEndPoints(tempEndPoints);
+            for (int j = 0; j < mSampleCount; j++) {
+                addToBucketCounter(tempEndPoints, tempBucketCounters, mInitialTimings[j]);
+            }
+            return tempBucketCounters;
+        } else {
+            return getDeepCopyOfArray(mBucketCounters);
+        }
     }
 
     private int[] getDeepCopyOfArray(int[] array) {
@@ -152,7 +168,7 @@
         return clone;
     }
 
-    private void addToBucketCounter(int time) {
+    private void addToBucketCounter(int[] bucketEndPoints, int[] bucketCounters, int time) {
         int i;
         for (i = 0; i < bucketEndPoints.length; i++) {
             if (time <= bucketEndPoints[i]) {
@@ -163,6 +179,13 @@
         bucketCounters[i]++;
     }
 
+    private void calculateBucketEndPoints(int[] bucketEndPoints) {
+        for (int i = 1; i < mBucketCount; i++) {
+            int endPt = mMinTimeMs + (i * (mMaxTimeMs - mMinTimeMs)) / mBucketCount;
+            bucketEndPoints[i - 1] = endPt;
+        }
+    }
+
     // Add new value of time taken
     // This function updates minTime, maxTime, averageTime & totalTimeCount every time it is
     // called. initialTimings[] is updated if totalTimeCount <= #RANGE_CALCULATION_COUNT. When
@@ -172,65 +195,62 @@
     public void addTimeTaken(int time) {
         // Initialize all fields if its first entry or if integer overflow is going to occur while
         // trying to calculate averageTime
-        if (sampleCount == 0 || (sampleCount == Integer.MAX_VALUE)) {
-            if (sampleCount == 0) {
-                minTimeMs = time;
-                maxTimeMs = time;
-                averageTimeMs = time;
+        if (mSampleCount == 0 || (mSampleCount == Integer.MAX_VALUE)) {
+            if (mSampleCount == 0) {
+                mMinTimeMs = time;
+                mMaxTimeMs = time;
+                mAverageTimeMs = time;
             } else {
-                initialTimings = new int[RANGE_CALCULATION_COUNT];
+                mInitialTimings = new int[RANGE_CALCULATION_COUNT];
             }
-            sampleCount = 1;
-            Arrays.fill(initialTimings, 0);
-            initialTimings[0] = time;
-            Arrays.fill(bucketEndPoints, 0);
-            Arrays.fill(bucketCounters, 0);
+            mSampleCount = 1;
+            Arrays.fill(mInitialTimings, 0);
+            mInitialTimings[0] = time;
+            Arrays.fill(mBucketEndPoints, 0);
+            Arrays.fill(mBucketCounters, 0);
         } else {
-            if (time < minTimeMs) {
-                minTimeMs = time;
+            if (time < mMinTimeMs) {
+                mMinTimeMs = time;
             }
-            if (time > maxTimeMs) {
-                maxTimeMs = time;
+            if (time > mMaxTimeMs) {
+                mMaxTimeMs = time;
             }
-            long totalTime = ((long)averageTimeMs) * sampleCount + time;
-            averageTimeMs = (int)(totalTime/++sampleCount);
+            long totalTime = ((long)mAverageTimeMs) * mSampleCount + time;
+            mAverageTimeMs = (int)(totalTime/++mSampleCount);
 
-            if (sampleCount < RANGE_CALCULATION_COUNT) {
-                initialTimings[sampleCount - 1] = time;
-            } else if (sampleCount == RANGE_CALCULATION_COUNT) {
-                initialTimings[sampleCount - 1] = time;
+            if (mSampleCount < RANGE_CALCULATION_COUNT) {
+                mInitialTimings[mSampleCount - 1] = time;
+            } else if (mSampleCount == RANGE_CALCULATION_COUNT) {
+                mInitialTimings[mSampleCount - 1] = time;
 
                 // Calculate bucket endpoints based on bucketCount expected
-                for (int i = 1; i < bucketCount; i++) {
-                    int endPt = minTimeMs + (i * (maxTimeMs - minTimeMs)) / bucketCount;
-                    bucketEndPoints[i - 1] = endPt;
-                }
+                calculateBucketEndPoints(mBucketEndPoints);
 
                 // Use values stored in initialTimings[] to update bucketCounters
                 for (int j = 0; j < RANGE_CALCULATION_COUNT; j++) {
-                    addToBucketCounter(initialTimings[j]);
+                    addToBucketCounter(mBucketEndPoints, mBucketCounters, mInitialTimings[j]);
                 }
-                initialTimings = null;
+                mInitialTimings = null;
             } else {
-                addToBucketCounter(time);
+                addToBucketCounter(mBucketEndPoints, mBucketCounters, time);
             }
 
         }
     }
 
     public String toString() {
-        String basic = " Histogram id = " + id + " Time(ms): min = " + minTimeMs + " max = "
-                + maxTimeMs + " avg = " + averageTimeMs + " Count = " + sampleCount;
-        if (sampleCount < RANGE_CALCULATION_COUNT) {
+        String basic = " Histogram id = " + mId + " Time(ms): min = " + mMinTimeMs + " max = "
+                + mMaxTimeMs + " avg = " + mAverageTimeMs + " Count = " + mSampleCount;
+        if (mSampleCount < RANGE_CALCULATION_COUNT) {
             return basic;
         } else {
             StringBuffer intervals = new StringBuffer(" Interval Endpoints:");
-            for (int i = 0; i < bucketEndPoints.length; i++) {
-                intervals.append(" " + bucketEndPoints[i]);
+            for (int i = 0; i < mBucketEndPoints.length; i++) {
+                intervals.append(" " + mBucketEndPoints[i]);
             }
             intervals.append(" Interval counters:");
-            for (int i = 0; i < bucketCounters.length; i++) {
-                intervals.append(" " + bucketCounters[i]);
+            for (int i = 0; i < mBucketCounters.length; i++) {
+                intervals.append(" " + mBucketCounters[i]);
             }
             return basic + intervals;
         }
@@ -251,39 +271,39 @@
             };
 
     public TelephonyHistogram(Parcel in) {
-        category = in.readInt();
-        id = in.readInt();
-        minTimeMs = in.readInt();
-        maxTimeMs = in.readInt();
-        averageTimeMs = in.readInt();
-        sampleCount = in.readInt();
+        mCategory = in.readInt();
+        mId = in.readInt();
+        mMinTimeMs = in.readInt();
+        mMaxTimeMs = in.readInt();
+        mAverageTimeMs = in.readInt();
+        mSampleCount = in.readInt();
         if (in.readInt() == PRESENT) {
-            initialTimings = new int[RANGE_CALCULATION_COUNT];
-            in.readIntArray(initialTimings);
+            mInitialTimings = new int[RANGE_CALCULATION_COUNT];
+            in.readIntArray(mInitialTimings);
         }
-        bucketCount = in.readInt();
-        bucketEndPoints = new int[bucketCount - 1];
-        in.readIntArray(bucketEndPoints);
-        bucketCounters = new int[bucketCount];
-        in.readIntArray(bucketCounters);
+        mBucketCount = in.readInt();
+        mBucketEndPoints = new int[mBucketCount - 1];
+        in.readIntArray(mBucketEndPoints);
+        mBucketCounters = new int[mBucketCount];
+        in.readIntArray(mBucketCounters);
     }
 
     public void writeToParcel(Parcel out, int flags) {
-        out.writeInt(category);
-        out.writeInt(id);
-        out.writeInt(minTimeMs);
-        out.writeInt(maxTimeMs);
-        out.writeInt(averageTimeMs);
-        out.writeInt(sampleCount);
-        if (initialTimings == null) {
+        out.writeInt(mCategory);
+        out.writeInt(mId);
+        out.writeInt(mMinTimeMs);
+        out.writeInt(mMaxTimeMs);
+        out.writeInt(mAverageTimeMs);
+        out.writeInt(mSampleCount);
+        if (mInitialTimings == null) {
             out.writeInt(ABSENT);
         } else {
             out.writeInt(PRESENT);
-            out.writeIntArray(initialTimings);
+            out.writeIntArray(mInitialTimings);
         }
-        out.writeInt(bucketCount);
-        out.writeIntArray(bucketEndPoints);
-        out.writeIntArray(bucketCounters);
+        out.writeInt(mBucketCount);
+        out.writeIntArray(mBucketEndPoints);
+        out.writeIntArray(mBucketCounters);
     }
 
     @Override
diff --git a/telephony/java/com/android/internal/telephony/ISms.aidl b/telephony/java/com/android/internal/telephony/ISms.aidl
index 70a8653..6115656 100644
--- a/telephony/java/com/android/internal/telephony/ISms.aidl
+++ b/telephony/java/com/android/internal/telephony/ISms.aidl
@@ -184,7 +184,7 @@
      */
     void sendTextForSubscriberWithSelfPermissions(in int subId, String callingPkg,
             in String destAddr, in String scAddr, in String text, in PendingIntent sentIntent,
-            in PendingIntent deliveryIntent);
+            in PendingIntent deliveryIntent, in boolean persistMessage);
 
     /**
      * Inject an SMS PDU into the android platform.
diff --git a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
index 0286506..a726a15 100644
--- a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
+++ b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
@@ -93,7 +93,7 @@
 
         try {
             mWm.addAppToken(0, null, 0, 0, 0, false, false, 0, 0, false, false, null,
-                    Configuration.EMPTY, 0, false, false);
+                    Configuration.EMPTY, 0, false, false, 0);
             fail("IWindowManager.addAppToken did not throw SecurityException as"
                     + " expected");
         } catch (SecurityException e) {
diff --git a/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java b/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java
index ceebdd5..04a59bc 100644
--- a/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java
+++ b/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java
@@ -78,7 +78,7 @@
     @Override
     public void addAppToken(int arg0, IApplicationToken arg1, int arg2, int arg3, int arg4,
             boolean arg5, boolean arg6, int arg7, int arg8, boolean arg9, boolean arg10,
-            Rect arg11, Configuration arg12, int arg13, boolean arg14, boolean arg15)
+            Rect arg11, Configuration arg12, int arg13, boolean arg14, boolean arg15, int arg16)
             throws RemoteException {
         // TODO Auto-generated method stub
     }
diff --git a/wifi/java/android/net/wifi/RttManager.java b/wifi/java/android/net/wifi/RttManager.java
index a404a90..590ff1b 100644
--- a/wifi/java/android/net/wifi/RttManager.java
+++ b/wifi/java/android/net/wifi/RttManager.java
@@ -691,7 +691,7 @@
 
         /**
          * spread (i.e. max - min) distance
-         * @deprecate Use {@link android.net.wifi.RttManager.RttResult#distanceSpread} API.
+         * @deprecated Use {@link android.net.wifi.RttManager.RttResult#distanceSpread} API.
          */
         @Deprecated
         public int distance_spread_cm;
diff --git a/wifi/java/android/net/wifi/WifiScanner.java b/wifi/java/android/net/wifi/WifiScanner.java
index 2ee1aef..2636c3f 100644
--- a/wifi/java/android/net/wifi/WifiScanner.java
+++ b/wifi/java/android/net/wifi/WifiScanner.java
@@ -141,7 +141,7 @@
     /**
      * reports {@link ScanListener#onResults} when underlying buffers are full
      * this is simply the lack of the {@link #REPORT_EVENT_AFTER_EACH_SCAN} flag
-     * @deprecated
+     * @deprecated It is not supported anymore.
      */
     @Deprecated
     public static final int REPORT_EVENT_AFTER_BUFFER_FULL = 0;