Merge "BatteryStats: Use English locale for dump and checkin data" into mnc-dev
diff --git a/Android.mk b/Android.mk
index 1de3625..a7a2ecb 100644
--- a/Android.mk
+++ b/Android.mk
@@ -285,7 +285,7 @@
 	core/java/com/android/internal/appwidget/IAppWidgetHost.aidl \
 	core/java/com/android/internal/backup/IBackupTransport.aidl \
 	core/java/com/android/internal/backup/IObbBackupService.aidl \
-	core/java/com/android/internal/policy/IKeyguardShowCallback.aidl \
+	core/java/com/android/internal/policy/IKeyguardDrawnCallback.aidl \
 	core/java/com/android/internal/policy/IKeyguardExitCallback.aidl \
 	core/java/com/android/internal/policy/IKeyguardService.aidl \
 	core/java/com/android/internal/policy/IKeyguardStateCallback.aidl \
@@ -668,7 +668,8 @@
 # FRAMEWORKS_BASE_SUBDIRS comes from build/core/pathmap.mk
 dirs_to_document := \
 	$(dirs_to_check_apis) \
-  $(addprefix ../../, $(FRAMEWORKS_SUPPORT_JAVA_SRC_DIRS))
+  $(addprefix ../../, $(FRAMEWORKS_DATA_BINDING_JAVA_SRC_DIRS)) \
+  $(addprefix ../../, $(FRAMEWORKS_SUPPORT_JAVA_SRC_DIRS)) \
 
 # These are relative to frameworks/base
 html_dirs := \
diff --git a/api/current.txt b/api/current.txt
index df9ea35..741ff9b 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -3466,6 +3466,7 @@
     method public final void setVolumeControlStream(int);
     method public boolean shouldShowRequestPermissionRationale(java.lang.String);
     method public boolean shouldUpRecreateTask(android.content.Intent);
+    method public boolean showAssist(android.os.Bundle);
     method public final deprecated void showDialog(int);
     method public final deprecated boolean showDialog(int, android.os.Bundle);
     method public void showLockTaskEscapeMessage();
@@ -3863,12 +3864,14 @@
     field public static final java.lang.String OPSTR_RECEIVE_WAP_PUSH = "android:receive_wap_push";
     field public static final java.lang.String OPSTR_RECORD_AUDIO = "android:record_audio";
     field public static final java.lang.String OPSTR_SEND_SMS = "android:send_sms";
+    field public static final java.lang.String OPSTR_SYSTEM_ALERT_WINDOW = "android:system_alert_window";
     field public static final java.lang.String OPSTR_USE_FINGERPRINT = "android:use_fingerprint";
     field public static final java.lang.String OPSTR_USE_SIP = "android:use_sip";
     field public static final java.lang.String OPSTR_WRITE_CALENDAR = "android:write_calendar";
     field public static final java.lang.String OPSTR_WRITE_CALL_LOG = "android:write_call_log";
     field public static final java.lang.String OPSTR_WRITE_CONTACTS = "android:write_contacts";
     field public static final java.lang.String OPSTR_WRITE_EXTERNAL_STORAGE = "android:write_external_storage";
+    field public static final java.lang.String OPSTR_WRITE_SETTINGS = "android:write_settings";
   }
 
   public static abstract interface AppOpsManager.OnOpChangedListener {
@@ -4772,9 +4775,9 @@
     field public int flags;
     field public android.app.PendingIntent fullScreenIntent;
     field public android.widget.RemoteViews headsUpContentView;
-    field public int icon;
+    field public deprecated int icon;
     field public int iconLevel;
-    field public android.graphics.Bitmap largeIcon;
+    field public deprecated android.graphics.Bitmap largeIcon;
     field public int ledARGB;
     field public int ledOffMS;
     field public int ledOnMS;
@@ -4790,20 +4793,22 @@
   }
 
   public static class Notification.Action implements android.os.Parcelable {
-    ctor public Notification.Action(int, java.lang.CharSequence, android.app.PendingIntent);
+    ctor public deprecated Notification.Action(int, java.lang.CharSequence, android.app.PendingIntent);
     method public android.app.Notification.Action clone();
     method public int describeContents();
     method public android.os.Bundle getExtras();
+    method public android.graphics.drawable.Icon getIcon();
     method public android.app.RemoteInput[] getRemoteInputs();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.app.Notification.Action> CREATOR;
     field public android.app.PendingIntent actionIntent;
-    field public int icon;
+    field public deprecated int icon;
     field public java.lang.CharSequence title;
   }
 
   public static final class Notification.Action.Builder {
-    ctor public Notification.Action.Builder(int, java.lang.CharSequence, android.app.PendingIntent);
+    ctor public deprecated Notification.Action.Builder(int, java.lang.CharSequence, android.app.PendingIntent);
+    ctor public Notification.Action.Builder(android.graphics.drawable.Icon, java.lang.CharSequence, android.app.PendingIntent);
     ctor public Notification.Action.Builder(android.app.Notification.Action);
     method public android.app.Notification.Action.Builder addExtras(android.os.Bundle);
     method public android.app.Notification.Action.Builder addRemoteInput(android.app.RemoteInput);
@@ -4851,7 +4856,7 @@
 
   public static class Notification.Builder {
     ctor public Notification.Builder(android.content.Context);
-    method public android.app.Notification.Builder addAction(int, java.lang.CharSequence, android.app.PendingIntent);
+    method public deprecated android.app.Notification.Builder addAction(int, java.lang.CharSequence, android.app.PendingIntent);
     method public android.app.Notification.Builder addAction(android.app.Notification.Action);
     method public android.app.Notification.Builder addExtras(android.os.Bundle);
     method public android.app.Notification.Builder addPerson(java.lang.String);
@@ -9440,6 +9445,7 @@
     method public java.lang.CharSequence loadDescription(android.content.pm.PackageManager);
     field public static final android.os.Parcelable.Creator<android.content.pm.PermissionInfo> CREATOR;
     field public static final int FLAG_COSTS_MONEY = 1; // 0x1
+    field public static final int FLAG_INSTALLED = 1073741824; // 0x40000000
     field public static final int PROTECTION_DANGEROUS = 1; // 0x1
     field public static final int PROTECTION_FLAG_APPOP = 64; // 0x40
     field public static final int PROTECTION_FLAG_DEVELOPMENT = 32; // 0x20
@@ -28534,14 +28540,13 @@
 package android.service.chooser {
 
   public final class ChooserTarget implements android.os.Parcelable {
-    ctor public ChooserTarget(java.lang.CharSequence, android.graphics.drawable.Icon, float, android.app.PendingIntent);
-    ctor public ChooserTarget(java.lang.CharSequence, android.graphics.drawable.Icon, float, android.content.IntentSender);
+    ctor public ChooserTarget(java.lang.CharSequence, android.graphics.drawable.Icon, float, android.content.ComponentName, android.os.Bundle);
     method public int describeContents();
+    method public android.content.ComponentName getComponentName();
     method public android.graphics.drawable.Icon getIcon();
-    method public android.content.IntentSender getIntentSender();
+    method public android.os.Bundle getIntentExtras();
     method public float getScore();
     method public java.lang.CharSequence getTitle();
-    method public boolean sendIntent(android.content.Context, android.content.Intent);
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.service.chooser.ChooserTarget> CREATOR;
   }
@@ -28785,11 +28790,13 @@
   public class VoiceInteractionService extends android.app.Service {
     ctor public VoiceInteractionService();
     method public final android.service.voice.AlwaysOnHotwordDetector createAlwaysOnHotwordDetector(java.lang.String, java.util.Locale, android.service.voice.AlwaysOnHotwordDetector.Callback);
+    method public int getDisabledShowContext();
     method public static boolean isActiveService(android.content.Context, android.content.ComponentName);
     method public android.os.IBinder onBind(android.content.Intent);
     method public void onLaunchVoiceAssistFromKeyguard();
     method public void onReady();
     method public void onShutdown();
+    method public void setDisabledShowContext(int);
     method public void showSession(android.os.Bundle, int);
     field public static final java.lang.String SERVICE_INTERFACE = "android.service.voice.VoiceInteractionService";
     field public static final java.lang.String SERVICE_META_DATA = "android.voice_interaction";
@@ -28801,7 +28808,9 @@
     method public void closeSystemDialogs();
     method public void finish();
     method public android.content.Context getContext();
+    method public int getDisabledShowContext();
     method public android.view.LayoutInflater getLayoutInflater();
+    method public int getUserDisabledShowContext();
     method public android.app.Dialog getWindow();
     method public void hide();
     method public void onAssistStructureFailure(java.lang.Throwable);
@@ -28817,6 +28826,7 @@
     method public void onHandleAssist(android.os.Bundle, android.app.assist.AssistStructure, android.app.assist.AssistContent);
     method public void onHandleScreenshot(android.graphics.Bitmap);
     method public void onHide();
+    method public void onLockscreenShown();
     method public boolean onKeyDown(int, android.view.KeyEvent);
     method public boolean onKeyLongPress(int, android.view.KeyEvent);
     method public boolean onKeyMultiple(int, int, android.view.KeyEvent);
@@ -28832,10 +28842,12 @@
     method public void onTaskStarted(android.content.Intent, int);
     method public void onTrimMemory(int);
     method public void setContentView(android.view.View);
+    method public void setDisabledShowContext(int);
     method public void setKeepAwake(boolean);
     method public void setTheme(int);
     method public void show(android.os.Bundle, int);
     method public void startVoiceActivity(android.content.Intent);
+    field public static final int SHOW_SOURCE_APPLICATION = 8; // 0x8
     field public static final int SHOW_SOURCE_ASSIST_GESTURE = 4; // 0x4
     field public static final int SHOW_WITH_ASSIST = 1; // 0x1
     field public static final int SHOW_WITH_SCREENSHOT = 2; // 0x2
@@ -28888,6 +28900,7 @@
     method public java.lang.String getCallingPackage();
     method public int getCallingUid();
     method public android.os.Bundle getExtras();
+    method public boolean isActive();
   }
 
   public abstract class VoiceInteractionSessionService extends android.app.Service {
diff --git a/api/system-current.txt b/api/system-current.txt
index eb1c431..4c2d7b1 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -104,6 +104,7 @@
     field public static final java.lang.String HARDWARE_TEST = "android.permission.HARDWARE_TEST";
     field public static final java.lang.String HDMI_CEC = "android.permission.HDMI_CEC";
     field public static final java.lang.String INJECT_EVENTS = "android.permission.INJECT_EVENTS";
+    field public static final java.lang.String INSTALL_GRANT_RUNTIME_PERMISSIONS = "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS";
     field public static final java.lang.String INSTALL_LOCATION_PROVIDER = "android.permission.INSTALL_LOCATION_PROVIDER";
     field public static final java.lang.String INSTALL_PACKAGES = "android.permission.INSTALL_PACKAGES";
     field public static final java.lang.String INSTALL_SHORTCUT = "com.android.launcher.permission.INSTALL_SHORTCUT";
@@ -181,6 +182,7 @@
     field public static final java.lang.String REQUEST_INSTALL_PACKAGES = "android.permission.REQUEST_INSTALL_PACKAGES";
     field public static final deprecated java.lang.String RESTART_PACKAGES = "android.permission.RESTART_PACKAGES";
     field public static final java.lang.String RETRIEVE_WINDOW_CONTENT = "android.permission.RETRIEVE_WINDOW_CONTENT";
+    field public static final java.lang.String REVOKE_RUNTIME_PERMISSIONS = "android.permission.REVOKE_RUNTIME_PERMISSIONS";
     field public static final java.lang.String SCORE_NETWORKS = "android.permission.SCORE_NETWORKS";
     field public static final java.lang.String SEND_RESPOND_VIA_MESSAGE = "android.permission.SEND_RESPOND_VIA_MESSAGE";
     field public static final java.lang.String SEND_SMS = "android.permission.SEND_SMS";
@@ -3567,6 +3569,7 @@
     method public final void setVolumeControlStream(int);
     method public boolean shouldShowRequestPermissionRationale(java.lang.String);
     method public boolean shouldUpRecreateTask(android.content.Intent);
+    method public boolean showAssist(android.os.Bundle);
     method public final deprecated void showDialog(int);
     method public final deprecated boolean showDialog(int, android.os.Bundle);
     method public void showLockTaskEscapeMessage();
@@ -3973,12 +3976,14 @@
     field public static final java.lang.String OPSTR_RECEIVE_WAP_PUSH = "android:receive_wap_push";
     field public static final java.lang.String OPSTR_RECORD_AUDIO = "android:record_audio";
     field public static final java.lang.String OPSTR_SEND_SMS = "android:send_sms";
+    field public static final java.lang.String OPSTR_SYSTEM_ALERT_WINDOW = "android:system_alert_window";
     field public static final java.lang.String OPSTR_USE_FINGERPRINT = "android:use_fingerprint";
     field public static final java.lang.String OPSTR_USE_SIP = "android:use_sip";
     field public static final java.lang.String OPSTR_WRITE_CALENDAR = "android:write_calendar";
     field public static final java.lang.String OPSTR_WRITE_CALL_LOG = "android:write_call_log";
     field public static final java.lang.String OPSTR_WRITE_CONTACTS = "android:write_contacts";
     field public static final java.lang.String OPSTR_WRITE_EXTERNAL_STORAGE = "android:write_external_storage";
+    field public static final java.lang.String OPSTR_WRITE_SETTINGS = "android:write_settings";
   }
 
   public static abstract interface AppOpsManager.OnOpChangedListener {
@@ -4888,9 +4893,9 @@
     field public int flags;
     field public android.app.PendingIntent fullScreenIntent;
     field public android.widget.RemoteViews headsUpContentView;
-    field public int icon;
+    field public deprecated int icon;
     field public int iconLevel;
-    field public android.graphics.Bitmap largeIcon;
+    field public deprecated android.graphics.Bitmap largeIcon;
     field public int ledARGB;
     field public int ledOffMS;
     field public int ledOnMS;
@@ -4906,20 +4911,22 @@
   }
 
   public static class Notification.Action implements android.os.Parcelable {
-    ctor public Notification.Action(int, java.lang.CharSequence, android.app.PendingIntent);
+    ctor public deprecated Notification.Action(int, java.lang.CharSequence, android.app.PendingIntent);
     method public android.app.Notification.Action clone();
     method public int describeContents();
     method public android.os.Bundle getExtras();
+    method public android.graphics.drawable.Icon getIcon();
     method public android.app.RemoteInput[] getRemoteInputs();
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.app.Notification.Action> CREATOR;
     field public android.app.PendingIntent actionIntent;
-    field public int icon;
+    field public deprecated int icon;
     field public java.lang.CharSequence title;
   }
 
   public static final class Notification.Action.Builder {
-    ctor public Notification.Action.Builder(int, java.lang.CharSequence, android.app.PendingIntent);
+    ctor public deprecated Notification.Action.Builder(int, java.lang.CharSequence, android.app.PendingIntent);
+    ctor public Notification.Action.Builder(android.graphics.drawable.Icon, java.lang.CharSequence, android.app.PendingIntent);
     ctor public Notification.Action.Builder(android.app.Notification.Action);
     method public android.app.Notification.Action.Builder addExtras(android.os.Bundle);
     method public android.app.Notification.Action.Builder addRemoteInput(android.app.RemoteInput);
@@ -4967,7 +4974,7 @@
 
   public static class Notification.Builder {
     ctor public Notification.Builder(android.content.Context);
-    method public android.app.Notification.Builder addAction(int, java.lang.CharSequence, android.app.PendingIntent);
+    method public deprecated android.app.Notification.Builder addAction(int, java.lang.CharSequence, android.app.PendingIntent);
     method public android.app.Notification.Builder addAction(android.app.Notification.Action);
     method public android.app.Notification.Builder addExtras(android.os.Bundle);
     method public android.app.Notification.Builder addPerson(java.lang.String);
@@ -9436,6 +9443,7 @@
     method public void setAppIcon(android.graphics.Bitmap);
     method public void setAppLabel(java.lang.CharSequence);
     method public void setAppPackageName(java.lang.String);
+    method public void setGrantedRuntimePermissions(java.lang.String[]);
     method public void setInstallLocation(int);
     method public void setOriginatingUri(android.net.Uri);
     method public void setReferrerUri(android.net.Uri);
@@ -9775,6 +9783,7 @@
     method public java.lang.CharSequence loadDescription(android.content.pm.PackageManager);
     field public static final android.os.Parcelable.Creator<android.content.pm.PermissionInfo> CREATOR;
     field public static final int FLAG_COSTS_MONEY = 1; // 0x1
+    field public static final int FLAG_INSTALLED = 1073741824; // 0x40000000
     field public static final int PROTECTION_DANGEROUS = 1; // 0x1
     field public static final int PROTECTION_FLAG_APPOP = 64; // 0x40
     field public static final int PROTECTION_FLAG_DEVELOPMENT = 32; // 0x20
@@ -30591,14 +30600,13 @@
 package android.service.chooser {
 
   public final class ChooserTarget implements android.os.Parcelable {
-    ctor public ChooserTarget(java.lang.CharSequence, android.graphics.drawable.Icon, float, android.app.PendingIntent);
-    ctor public ChooserTarget(java.lang.CharSequence, android.graphics.drawable.Icon, float, android.content.IntentSender);
+    ctor public ChooserTarget(java.lang.CharSequence, android.graphics.drawable.Icon, float, android.content.ComponentName, android.os.Bundle);
     method public int describeContents();
+    method public android.content.ComponentName getComponentName();
     method public android.graphics.drawable.Icon getIcon();
-    method public android.content.IntentSender getIntentSender();
+    method public android.os.Bundle getIntentExtras();
     method public float getScore();
     method public java.lang.CharSequence getTitle();
-    method public boolean sendIntent(android.content.Context, android.content.Intent);
     method public void writeToParcel(android.os.Parcel, int);
     field public static final android.os.Parcelable.Creator<android.service.chooser.ChooserTarget> CREATOR;
   }
@@ -30934,11 +30942,13 @@
   public class VoiceInteractionService extends android.app.Service {
     ctor public VoiceInteractionService();
     method public final android.service.voice.AlwaysOnHotwordDetector createAlwaysOnHotwordDetector(java.lang.String, java.util.Locale, android.service.voice.AlwaysOnHotwordDetector.Callback);
+    method public int getDisabledShowContext();
     method public static boolean isActiveService(android.content.Context, android.content.ComponentName);
     method public android.os.IBinder onBind(android.content.Intent);
     method public void onLaunchVoiceAssistFromKeyguard();
     method public void onReady();
     method public void onShutdown();
+    method public void setDisabledShowContext(int);
     method public void showSession(android.os.Bundle, int);
     field public static final java.lang.String SERVICE_INTERFACE = "android.service.voice.VoiceInteractionService";
     field public static final java.lang.String SERVICE_META_DATA = "android.voice_interaction";
@@ -30950,7 +30960,9 @@
     method public void closeSystemDialogs();
     method public void finish();
     method public android.content.Context getContext();
+    method public int getDisabledShowContext();
     method public android.view.LayoutInflater getLayoutInflater();
+    method public int getUserDisabledShowContext();
     method public android.app.Dialog getWindow();
     method public void hide();
     method public void onAssistStructureFailure(java.lang.Throwable);
@@ -30966,6 +30978,7 @@
     method public void onHandleAssist(android.os.Bundle, android.app.assist.AssistStructure, android.app.assist.AssistContent);
     method public void onHandleScreenshot(android.graphics.Bitmap);
     method public void onHide();
+    method public void onLockscreenShown();
     method public boolean onKeyDown(int, android.view.KeyEvent);
     method public boolean onKeyLongPress(int, android.view.KeyEvent);
     method public boolean onKeyMultiple(int, int, android.view.KeyEvent);
@@ -30981,10 +30994,12 @@
     method public void onTaskStarted(android.content.Intent, int);
     method public void onTrimMemory(int);
     method public void setContentView(android.view.View);
+    method public void setDisabledShowContext(int);
     method public void setKeepAwake(boolean);
     method public void setTheme(int);
     method public void show(android.os.Bundle, int);
     method public void startVoiceActivity(android.content.Intent);
+    field public static final int SHOW_SOURCE_APPLICATION = 8; // 0x8
     field public static final int SHOW_SOURCE_ASSIST_GESTURE = 4; // 0x4
     field public static final int SHOW_WITH_ASSIST = 1; // 0x1
     field public static final int SHOW_WITH_SCREENSHOT = 2; // 0x2
@@ -31037,6 +31052,7 @@
     method public java.lang.String getCallingPackage();
     method public int getCallingUid();
     method public android.os.Bundle getExtras();
+    method public boolean isActive();
   }
 
   public abstract class VoiceInteractionSessionService extends android.app.Service {
diff --git a/cmds/am/src/com/android/commands/am/Am.java b/cmds/am/src/com/android/commands/am/Am.java
index 9f4bc52..d952dfc 100644
--- a/cmds/am/src/com/android/commands/am/Am.java
+++ b/cmds/am/src/com/android/commands/am/Am.java
@@ -26,6 +26,7 @@
 import android.app.IActivityManager;
 import android.app.IInstrumentationWatcher;
 import android.app.Instrumentation;
+import android.app.IStopUserCallback;
 import android.app.ProfilerInfo;
 import android.app.UiAutomationConnection;
 import android.app.usage.ConfigurationStats;
@@ -133,7 +134,7 @@
                 "       am to-app-uri [INTENT]\n" +
                 "       am switch-user <USER_ID>\n" +
                 "       am start-user <USER_ID>\n" +
-                "       am stop-user <USER_ID>\n" +
+                "       am stop-user [-w] <USER_ID>\n" +
                 "       am stack start <DISPLAY_ID> <INTENT>\n" +
                 "       am stack movetask <TASK_ID> <STACK_ID> [true|false]\n" +
                 "       am stack resize <STACK_ID> <LEFT,TOP,RIGHT,BOTTOM>\n" +
@@ -257,6 +258,7 @@
                 "\n" +
                 "am stop-user: stop execution of USER_ID, not allowing it to run any\n" +
                 "  code until a later explicit start or switch to it.\n" +
+                "  -w: wait for stop-user to complete.\n" +
                 "\n" +
                 "am stack start: start a new activity on <DISPLAY_ID> using <INTENT>.\n" +
                 "\n" +
@@ -1303,9 +1305,45 @@
         }
     }
 
+    private static class StopUserCallback extends IStopUserCallback.Stub {
+        private boolean mFinished = false;
+
+        public synchronized void waitForFinish() {
+            try {
+                while (!mFinished) wait();
+            } catch (InterruptedException e) {
+                throw new IllegalStateException(e);
+            }
+        }
+
+        @Override
+        public synchronized void userStopped(int userId) {
+            mFinished = true;
+            notifyAll();
+        }
+
+        @Override
+        public synchronized void userStopAborted(int userId) {
+            mFinished = true;
+            notifyAll();
+        }
+    }
+
     private void runStopUser() throws Exception {
-        String user = nextArgRequired();
-        int res = mAm.stopUser(Integer.parseInt(user), null);
+        boolean wait = false;
+        String opt = null;
+        while ((opt = nextOption()) != null) {
+            if ("-w".equals(opt)) {
+                wait = true;
+            } else {
+                System.err.println("Error: unknown option: " + opt);
+                return;
+            }
+        }
+        int user = Integer.parseInt(nextArgRequired());
+        StopUserCallback callback = wait ? new StopUserCallback() : null;
+
+        int res = mAm.stopUser(user, callback);
         if (res != ActivityManager.USER_OP_SUCCESS) {
             String txt = "";
             switch (res) {
@@ -1317,6 +1355,8 @@
                     break;
             }
             System.err.println("Switch failed: " + res + txt);
+        } else if (callback != null) {
+            callback.waitForFinish();
         }
     }
 
diff --git a/cmds/pm/src/com/android/commands/pm/Pm.java b/cmds/pm/src/com/android/commands/pm/Pm.java
index 2dcd9cb..b39376c 100644
--- a/cmds/pm/src/com/android/commands/pm/Pm.java
+++ b/cmds/pm/src/com/android/commands/pm/Pm.java
@@ -16,6 +16,11 @@
 
 package com.android.commands.pm;
 
+import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
+import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
+import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
+import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
+
 import android.app.ActivityManager;
 import android.app.ActivityManagerNative;
 import android.app.IActivityManager;
@@ -212,6 +217,14 @@
             return runSetPermissionEnforced();
         }
 
+        if ("set-app-link".equals(op)) {
+            return runSetAppLink();
+        }
+
+        if ("get-app-link".equals(op)) {
+            return runGetAppLink();
+        }
+
         if ("set-install-location".equals(op)) {
             return runSetInstallLocation();
         }
@@ -827,6 +840,148 @@
         return Integer.toString(result);
     }
 
+    // pm set-app-link [--user USER_ID] PACKAGE {always|ask|never|undefined}
+    private int runSetAppLink() {
+        int userId = UserHandle.USER_OWNER;
+
+        String opt;
+        while ((opt = nextOption()) != null) {
+            if (opt.equals("--user")) {
+                userId = Integer.parseInt(nextOptionData());
+                if (userId < 0) {
+                    System.err.println("Error: user must be >= 0");
+                    return 1;
+                }
+            } else {
+                System.err.println("Error: unknown option: " + opt);
+                showUsage();
+                return 1;
+            }
+        }
+
+        // Package name to act on; required
+        final String pkg = nextArg();
+        if (pkg == null) {
+            System.err.println("Error: no package specified.");
+            showUsage();
+            return 1;
+        }
+
+        // State to apply; {always|ask|never|undefined}, required
+        final String modeString = nextArg();
+        if (modeString == null) {
+            System.err.println("Error: no app link state specified.");
+            showUsage();
+            return 1;
+        }
+
+        final int newMode;
+        switch (modeString.toLowerCase()) {
+            case "undefined":
+                newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
+                break;
+
+            case "always":
+                newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
+                break;
+
+            case "ask":
+                newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
+                break;
+
+            case "never":
+                newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
+                break;
+
+            default:
+                System.err.println("Error: unknown app link state '" + modeString + "'");
+                return 1;
+        }
+
+        try {
+            final PackageInfo info = mPm.getPackageInfo(pkg, 0, userId);
+            if (info == null) {
+                System.err.println("Error: package " + pkg + " not found.");
+                return 1;
+            }
+
+            if ((info.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) == 0) {
+                System.err.println("Error: package " + pkg + " does not handle web links.");
+                return 1;
+            }
+
+            if (!mPm.updateIntentVerificationStatus(pkg, newMode, userId)) {
+                System.err.println("Error: unable to update app link status for " + pkg);
+                return 1;
+            }
+        } catch (Exception e) {
+            System.err.println(e.toString());
+            System.err.println(PM_NOT_RUNNING_ERR);
+            return 1;
+        }
+
+        return 0;
+    }
+
+    // pm get-app-link [--user USER_ID] PACKAGE
+    private int runGetAppLink() {
+        int userId = UserHandle.USER_OWNER;
+
+        String opt;
+        while ((opt = nextOption()) != null) {
+            if (opt.equals("--user")) {
+                userId = Integer.parseInt(nextOptionData());
+                if (userId < 0) {
+                    System.err.println("Error: user must be >= 0");
+                    return 1;
+                }
+            } else {
+                System.err.println("Error: unknown option: " + opt);
+                showUsage();
+                return 1;
+            }
+        }
+
+        // Package name to act on; required
+        final String pkg = nextArg();
+        if (pkg == null) {
+            System.err.println("Error: no package specified.");
+            showUsage();
+            return 1;
+        }
+
+        try {
+            final PackageInfo info = mPm.getPackageInfo(pkg, 0, userId);
+            if (info == null) {
+                System.err.println("Error: package " + pkg + " not found.");
+                return 1;
+            }
+
+            if ((info.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) == 0) {
+                System.err.println("Error: package " + pkg + " does not handle web links.");
+                return 1;
+            }
+
+            System.out.println(linkStateToString(mPm.getIntentVerificationStatus(pkg, userId)));
+        } catch (Exception e) {
+            System.err.println(e.toString());
+            System.err.println(PM_NOT_RUNNING_ERR);
+            return 1;
+        }
+
+        return 0;
+    }
+
+    private String linkStateToString(int state) {
+        switch (state) {
+            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: return "undefined";
+            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: return "ask";
+            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS: return "always";
+            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER: return "never";
+        }
+        return "Unknown link state: " + state;
+    }
+
     private int runSetInstallLocation() {
         int loc;
 
@@ -1936,6 +2091,8 @@
         System.err.println("       pm grant [--user USER_ID] PACKAGE PERMISSION");
         System.err.println("       pm revoke [--user USER_ID] PACKAGE PERMISSION");
         System.err.println("       pm reset-permissions");
+        System.err.println("       pm set-app-link [--user USER_ID] PACKAGE {always|ask|never|undefined}");
+        System.err.println("       pm get-app-link [--user USER_ID] PACKAGE");
         System.err.println("       pm set-install-location [0/auto] [1/internal] [2/external]");
         System.err.println("       pm get-install-location");
         System.err.println("       pm set-permission-enforced PERMISSION [true|false]");
diff --git a/cmds/sm/src/com/android/commands/sm/Sm.java b/cmds/sm/src/com/android/commands/sm/Sm.java
index 0dad4dc..0a1ba4d1 100644
--- a/cmds/sm/src/com/android/commands/sm/Sm.java
+++ b/cmds/sm/src/com/android/commands/sm/Sm.java
@@ -81,6 +81,8 @@
             runUnmount();
         } else if ("format".equals(op)) {
             runFormat();
+        } else if ("benchmark".equals(op)) {
+            runBenchmark();
         } else if ("forget".equals(op)) {
             runForget();
         } else {
@@ -89,9 +91,12 @@
     }
 
     public void runListDisks() throws RemoteException {
+        final boolean onlyAdoptable = "adoptable".equals(nextArg());
         final DiskInfo[] disks = mSm.getDisks();
         for (DiskInfo disk : disks) {
-            System.out.println(disk.getId());
+            if (!onlyAdoptable || disk.isAdoptable()) {
+                System.out.println(disk.getId());
+            }
         }
     }
 
@@ -161,6 +166,11 @@
         mSm.format(volId);
     }
 
+    public void runBenchmark() throws RemoteException {
+        final String volId = nextArg();
+        mSm.benchmark(volId);
+    }
+
     public void runForget() throws RemoteException{
         final String fsUuid = nextArg();
         if ("all".equals(fsUuid)) {
@@ -180,7 +190,7 @@
     }
 
     private static int showUsage() {
-        System.err.println("usage: sm list-disks");
+        System.err.println("usage: sm list-disks [adoptable]");
         System.err.println("       sm list-volumes [public|private|emulated|all]");
         System.err.println("       sm has-adoptable");
         System.err.println("       sm get-primary-storage-uuid");
@@ -190,6 +200,7 @@
         System.err.println("       sm mount VOLUME");
         System.err.println("       sm unmount VOLUME");
         System.err.println("       sm format VOLUME");
+        System.err.println("       sm benchmark VOLUME");
         System.err.println("");
         System.err.println("       sm forget [UUID|all]");
         System.err.println("");
diff --git a/core/java/android/app/ActionBar.java b/core/java/android/app/ActionBar.java
index 4d34349..72f8c77 100644
--- a/core/java/android/app/ActionBar.java
+++ b/core/java/android/app/ActionBar.java
@@ -1057,6 +1057,11 @@
     }
 
     /** @hide */
+    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
+        return false;
+    }
+
+    /** @hide */
     public boolean collapseActionView() {
         return false;
     }
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index d07238a..e49acfa 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -1545,6 +1545,24 @@
     }
 
     /**
+     * Ask to have the current assistant shown to the user.  This only works if the calling
+     * activity is the current foreground activity.  It is the same as calling
+     * {@link android.service.voice.VoiceInteractionService#showSession
+     * VoiceInteractionService.showSession} and requesting all of the possible context.
+     * The receiver will always see
+     * {@link android.service.voice.VoiceInteractionSession#SHOW_SOURCE_APPLICATION} set.
+     * @return Returns true if the assistant was successfully invoked, else false.  For example
+     * false will be returned if the caller is not the current top activity.
+     */
+    public boolean showAssist(Bundle args) {
+        try {
+            return ActivityManagerNative.getDefault().showAssistFromActivity(mToken, args);
+        } catch (RemoteException e) {
+        }
+        return false;
+    }
+
+    /**
      * Called when you are no longer visible to the user.  You will next
      * receive either {@link #onRestart}, {@link #onDestroy}, or nothing,
      * depending on later user activity.
@@ -2469,7 +2487,9 @@
      * @return True if the key shortcut was handled.
      */
     public boolean onKeyShortcut(int keyCode, KeyEvent event) {
-        return false;
+        // Let the Action Bar have a chance at handling the shortcut.
+        ActionBar actionBar = getActionBar();
+        return (actionBar != null && actionBar.onKeyShortcut(keyCode, event));
     }
 
     /**
@@ -3769,6 +3789,11 @@
     /**
      * Callback for the result from requesting permissions. This method
      * is invoked for every call on {@link #requestPermissions(String[], int)}.
+     * <p>
+     * <strong>Note:</strong> It is possible that the permissions request interaction
+     * with the user is interrupted. In this case you will receive empty permissions
+     * and results arrays which should be treated as a cancellation.
+     * </p>
      *
      * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
      * @param permissions The requested permissions. Never null.
@@ -3975,16 +4000,24 @@
      * as intermediaries that dispatch their intent to the target the user selects -- to
      * do this, they must perform all security checks including permission grants as if
      * their launch had come from the original activity.
+     * @param intent The Intent to start.
+     * @param options ActivityOptions or null.
+     * @param ignoreTargetSecurity If true, the activity manager will not check whether the
+     * caller it is doing the start is, is actually allowed to start the target activity.
+     * If you set this to true, you must set an explicit component in the Intent and do any
+     * appropriate security checks yourself.
+     * @param userId The user the new activity should run as.
      * @hide
      */
-    public void startActivityAsCaller(Intent intent, @Nullable Bundle options, int userId) {
+    public void startActivityAsCaller(Intent intent, @Nullable Bundle options,
+            boolean ignoreTargetSecurity, int userId) {
         if (mParent != null) {
             throw new RuntimeException("Can't be called from a child");
         }
         Instrumentation.ActivityResult ar =
                 mInstrumentation.execStartActivityAsCaller(
                         this, mMainThread.getApplicationThread(), mToken, this,
-                        intent, -1, options, userId);
+                        intent, -1, options, ignoreTargetSecurity, userId);
         if (ar != null) {
             mMainThread.sendActivityResult(
                 mToken, mEmbeddedID, -1, ar.getResultCode(),
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index 9ca206a..55b2fd9 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -2807,7 +2807,7 @@
 
     /**
      * Request that the system start watching for the calling process to exceed a pss
-     * size as given here.  Once called, the system will look for any occassions where it
+     * size as given here.  Once called, the system will look for any occasions where it
      * sees the associated process with a larger pss size and, when this happens, automatically
      * pull a heap dump from it and allow the user to share the data.  Note that this request
      * continues running even if the process is killed and restarted.  To remove the watch,
diff --git a/core/java/android/app/ActivityManagerNative.java b/core/java/android/app/ActivityManagerNative.java
index fc408a8..b758a7a 100644
--- a/core/java/android/app/ActivityManagerNative.java
+++ b/core/java/android/app/ActivityManagerNative.java
@@ -206,9 +206,11 @@
                     ? ProfilerInfo.CREATOR.createFromParcel(data) : null;
             Bundle options = data.readInt() != 0
                     ? Bundle.CREATOR.createFromParcel(data) : null;
+            boolean ignoreTargetSecurity = data.readInt() != 0;
             int userId = data.readInt();
             int result = startActivityAsCaller(app, callingPackage, intent, resolvedType,
-                    resultTo, resultWho, requestCode, startFlags, profilerInfo, options, userId);
+                    resultTo, resultWho, requestCode, startFlags, profilerInfo, options,
+                    ignoreTargetSecurity, userId);
             reply.writeNoException();
             reply.writeInt(result);
             return true;
@@ -2191,8 +2193,10 @@
             data.enforceInterface(IActivityManager.descriptor);
             int requestType = data.readInt();
             IResultReceiver receiver = IResultReceiver.Stub.asInterface(data.readStrongBinder());
-            requestAssistContextExtras(requestType, receiver);
+            IBinder activityToken = data.readStrongBinder();
+            boolean res = requestAssistContextExtras(requestType, receiver, activityToken);
             reply.writeNoException();
+            reply.writeInt(res ? 1 : 0);
             return true;
         }
 
@@ -2223,7 +2227,17 @@
 
         case IS_SCREEN_CAPTURE_ALLOWED_ON_CURRENT_ACTIVITY_TRANSACTION: {
             data.enforceInterface(IActivityManager.descriptor);
-            boolean res = isScreenCaptureAllowedOnCurrentActivity();
+            boolean res = isAssistDataAllowedOnCurrentActivity();
+            reply.writeNoException();
+            reply.writeInt(res ? 1 : 0);
+            return true;
+        }
+
+        case SHOW_ASSIST_FROM_ACTIVITY_TRANSACTION: {
+            data.enforceInterface(IActivityManager.descriptor);
+            IBinder token = data.readStrongBinder();
+            Bundle args = data.readBundle();
+            boolean res = showAssistFromActivity(token, args);
             reply.writeNoException();
             reply.writeInt(res ? 1 : 0);
             return true;
@@ -2675,7 +2689,8 @@
     }
     public int startActivityAsCaller(IApplicationThread caller, String callingPackage,
             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
-            int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) throws RemoteException {
+            int startFlags, ProfilerInfo profilerInfo, Bundle options, boolean ignoreTargetSecurity,
+            int userId) throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
         data.writeInterfaceToken(IActivityManager.descriptor);
@@ -2699,6 +2714,7 @@
         } else {
             data.writeInt(0);
         }
+        data.writeInt(ignoreTargetSecurity ? 1 : 0);
         data.writeInt(userId);
         mRemote.transact(START_ACTIVITY_AS_CALLER_TRANSACTION, data, reply, 0);
         reply.readException();
@@ -5373,17 +5389,20 @@
         return res;
     }
 
-    public void requestAssistContextExtras(int requestType, IResultReceiver receiver)
-            throws RemoteException {
+    public boolean requestAssistContextExtras(int requestType, IResultReceiver receiver,
+            IBinder activityToken) throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
         data.writeInterfaceToken(IActivityManager.descriptor);
         data.writeInt(requestType);
         data.writeStrongBinder(receiver.asBinder());
+        data.writeStrongBinder(activityToken);
         mRemote.transact(REQUEST_ASSIST_CONTEXT_EXTRAS_TRANSACTION, data, reply, 0);
         reply.readException();
+        boolean res = reply.readInt() != 0;
         data.recycle();
         reply.recycle();
+        return res;
     }
 
     public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure,
@@ -5425,7 +5444,7 @@
         return res;
     }
 
-    public boolean isScreenCaptureAllowedOnCurrentActivity() throws RemoteException {
+    public boolean isAssistDataAllowedOnCurrentActivity() throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
         data.writeInterfaceToken(IActivityManager.descriptor);
@@ -5437,6 +5456,20 @@
         return res;
     }
 
+    public boolean showAssistFromActivity(IBinder token, Bundle args) throws RemoteException {
+        Parcel data = Parcel.obtain();
+        Parcel reply = Parcel.obtain();
+        data.writeInterfaceToken(IActivityManager.descriptor);
+        data.writeStrongBinder(token);
+        data.writeBundle(args);
+        mRemote.transact(SHOW_ASSIST_FROM_ACTIVITY_TRANSACTION, data, reply, 0);
+        reply.readException();
+        boolean res = reply.readInt() != 0;
+        data.recycle();
+        reply.recycle();
+        return res;
+    }
+
     public void killUid(int uid, String reason) throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index 849253b..976830fc 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -325,6 +325,12 @@
     /** Write external storage. */
     public static final String OPSTR_WRITE_EXTERNAL_STORAGE
             = "android:write_external_storage";
+    /** Required to draw on top of other apps. */
+    public static final String OPSTR_SYSTEM_ALERT_WINDOW
+            = "android:system_alert_window";
+    /** Required to write/modify/update system settingss. */
+    public static final String OPSTR_WRITE_SETTINGS
+            = "android:write_settings";
 
     /**
      * This maps each operation to the operation that serves as the
@@ -427,8 +433,8 @@
             OPSTR_SEND_SMS,
             null,
             null,
-            null,
-            null,
+            OPSTR_WRITE_SETTINGS,
+            OPSTR_SYSTEM_ALERT_WINDOW,
             null,
             OPSTR_CAMERA,
             OPSTR_RECORD_AUDIO,
@@ -773,7 +779,7 @@
             AppOpsManager.MODE_ALLOWED,
             AppOpsManager.MODE_ALLOWED,
             AppOpsManager.MODE_ALLOWED,
-            AppOpsManager.MODE_ALLOWED,
+            AppOpsManager.MODE_DEFAULT, // OP_SYSTEM_ALERT_WINDOW
             AppOpsManager.MODE_ALLOWED,
             AppOpsManager.MODE_ALLOWED,
             AppOpsManager.MODE_ALLOWED,
diff --git a/core/java/android/app/BackStackRecord.java b/core/java/android/app/BackStackRecord.java
index 13030ca..84cbea9 100644
--- a/core/java/android/app/BackStackRecord.java
+++ b/core/java/android/app/BackStackRecord.java
@@ -1094,8 +1094,10 @@
                         container.getViewTreeObserver().removeOnPreDrawListener(this);
 
                         // Don't include any newly-hidden fragments in the transition.
-                        excludeHiddenFragments(hiddenFragmentViews, inFragment.mContainerId,
-                                overallTransition);
+                        if (inFragment != null) {
+                            excludeHiddenFragments(hiddenFragmentViews, inFragment.mContainerId,
+                                    overallTransition);
+                        }
 
                         ArrayMap<String, View> namedViews = null;
                         if (sharedElementTransition != null) {
@@ -1692,7 +1694,7 @@
 
     private static void setNameOverrides(TransitionState state, ArrayList<String> sourceNames,
             ArrayList<String> targetNames) {
-        if (sourceNames != null) {
+        if (sourceNames != null && targetNames != null) {
             for (int i = 0; i < sourceNames.size(); i++) {
                 String source = sourceNames.get(i);
                 String target = targetNames.get(i);
@@ -1703,7 +1705,9 @@
 
     private void setBackNameOverrides(TransitionState state, ArrayMap<String, View> namedViews,
             boolean isEnd) {
-        int count = mSharedElementTargetNames == null ? 0 : mSharedElementTargetNames.size();
+        int targetCount = mSharedElementTargetNames == null ? 0 : mSharedElementTargetNames.size();
+        int sourceCount = mSharedElementSourceNames == null ? 0 : mSharedElementSourceNames.size();
+        final int count = Math.min(targetCount, sourceCount);
         for (int i = 0; i < count; i++) {
             String source = mSharedElementSourceNames.get(i);
             String originalTarget = mSharedElementTargetNames.get(i);
diff --git a/core/java/android/app/ExitTransitionCoordinator.java b/core/java/android/app/ExitTransitionCoordinator.java
index ad104a4..7fbb99a 100644
--- a/core/java/android/app/ExitTransitionCoordinator.java
+++ b/core/java/android/app/ExitTransitionCoordinator.java
@@ -25,6 +25,7 @@
 import android.graphics.RectF;
 import android.graphics.drawable.ColorDrawable;
 import android.graphics.drawable.Drawable;
+import android.os.Build.VERSION_CODES;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
@@ -238,8 +239,12 @@
             if (decorView != null && decorView.getBackground() == null) {
                 getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));
             }
+            final boolean targetsM = decorView == null || decorView.getContext()
+                    .getApplicationInfo().targetSdkVersion >= VERSION_CODES.MNC;
+            ArrayList<String> sharedElementNames = targetsM ? mSharedElementNames :
+                    mAllSharedElementNames;
             ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(mActivity, this,
-                    mSharedElementNames, resultCode, data);
+                    sharedElementNames, resultCode, data);
             mActivity.convertToTranslucent(new Activity.TranslucentConversionListener() {
                 @Override
                 public void onTranslucentConversionComplete(boolean drawComplete) {
diff --git a/core/java/android/app/Fragment.java b/core/java/android/app/Fragment.java
index 5490fe7..82206ea 100644
--- a/core/java/android/app/Fragment.java
+++ b/core/java/android/app/Fragment.java
@@ -1213,6 +1213,11 @@
     /**
      * Callback for the result from requesting permissions. This method
      * is invoked for every call on {@link #requestPermissions(String[], int)}.
+     * <p>
+     * <strong>Note:</strong> It is possible that the permissions request interaction
+     * with the user is interrupted. In this case you will receive empty permissions
+     * and results arrays which should be treated as a cancellation.
+     * </p>
      *
      * @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
      * @param permissions The requested permissions. Never null.
@@ -1249,7 +1254,8 @@
      */
     public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
         if (mHost != null) {
-            mHost.getContext().getPackageManager().shouldShowRequestPermissionRationale(permission);
+            return mHost.getContext().getPackageManager()
+                    .shouldShowRequestPermissionRationale(permission);
         }
         return false;
     }
diff --git a/core/java/android/app/IActivityManager.java b/core/java/android/app/IActivityManager.java
index 1d87d77..9ebbb9b 100644
--- a/core/java/android/app/IActivityManager.java
+++ b/core/java/android/app/IActivityManager.java
@@ -72,7 +72,8 @@
             ProfilerInfo profilerInfo, Bundle options, int userId) throws RemoteException;
     public int startActivityAsCaller(IApplicationThread caller, String callingPackage,
             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
-            int flags, ProfilerInfo profilerInfo, Bundle options, int userId) throws RemoteException;
+            int flags, ProfilerInfo profilerInfo, Bundle options, boolean ignoreTargetSecurity,
+            int userId) throws RemoteException;
     public WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
             Intent intent, String resolvedType, IBinder resultTo, String resultWho,
             int requestCode, int flags, ProfilerInfo profilerInfo, Bundle options,
@@ -433,8 +434,8 @@
 
     public Bundle getAssistContextExtras(int requestType) throws RemoteException;
 
-    public void requestAssistContextExtras(int requestType, IResultReceiver receiver)
-            throws RemoteException;
+    public boolean requestAssistContextExtras(int requestType, IResultReceiver receiver,
+            IBinder activityToken) throws RemoteException;
 
     public void reportAssistContextExtras(IBinder token, Bundle extras,
             AssistStructure structure, AssistContent content, Uri referrer) throws RemoteException;
@@ -442,7 +443,9 @@
     public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
             Bundle args) throws RemoteException;
 
-    public boolean isScreenCaptureAllowedOnCurrentActivity() throws RemoteException;
+    public boolean isAssistDataAllowedOnCurrentActivity() throws RemoteException;
+
+    public boolean showAssistFromActivity(IBinder token, Bundle args) throws RemoteException;
 
     public void killUid(int uid, String reason) throws RemoteException;
 
@@ -857,4 +860,5 @@
     int UNREGISTER_UID_OBSERVER_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+298;
     int IS_SCREEN_CAPTURE_ALLOWED_ON_CURRENT_ACTIVITY_TRANSACTION
             = IBinder.FIRST_CALL_TRANSACTION+299;
+    int SHOW_ASSIST_FROM_ACTIVITY_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+300;
 }
diff --git a/core/java/android/app/Instrumentation.java b/core/java/android/app/Instrumentation.java
index 653f1b6..c2d901d 100644
--- a/core/java/android/app/Instrumentation.java
+++ b/core/java/android/app/Instrumentation.java
@@ -1701,7 +1701,8 @@
      */
     public ActivityResult execStartActivityAsCaller(
             Context who, IBinder contextThread, IBinder token, Activity target,
-            Intent intent, int requestCode, Bundle options, int userId) {
+            Intent intent, int requestCode, Bundle options, boolean ignoreTargetSecurity,
+            int userId) {
         IApplicationThread whoThread = (IApplicationThread) contextThread;
         if (mActivityMonitors != null) {
             synchronized (mSync) {
@@ -1725,7 +1726,7 @@
                 .startActivityAsCaller(whoThread, who.getBasePackageName(), intent,
                         intent.resolveTypeIfNeeded(who.getContentResolver()),
                         token, target != null ? target.mEmbeddedID : null,
-                        requestCode, 0, null, options, userId);
+                        requestCode, 0, null, options, ignoreTargetSecurity, userId);
             checkStartActivityResult(result, intent);
         } catch (RemoteException e) {
             throw new RuntimeException("Failure from system", e);
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index c3dece8..b0d8541 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -166,8 +166,10 @@
 
     /**
      * The resource id of a drawable to use as the icon in the status bar.
-     * This is required; notifications with an invalid icon resource will not be shown.
+     *
+     * @deprecated Use {@link Builder#setSmallIcon(Icon)} instead.
      */
+    @Deprecated
     @DrawableRes
     public int icon;
 
@@ -269,8 +271,11 @@
     public RemoteViews headsUpContentView;
 
     /**
-     * The bitmap that may escape the bounds of the panel and bar.
+     * A large bitmap to be shown in the notification content area.
+     *
+     * @deprecated Use {@link Builder#setLargeIcon(Icon)} instead.
      */
+    @Deprecated
     public Bitmap largeIcon;
 
     /**
@@ -900,11 +905,15 @@
      */
     public static class Action implements Parcelable {
         private final Bundle mExtras;
+        private Icon mIcon;
         private final RemoteInput[] mRemoteInputs;
 
         /**
          * Small icon representing the action.
+         *
+         * @deprecated Use {@link Action#getIcon()} instead.
          */
+        @Deprecated
         public int icon;
 
         /**
@@ -919,7 +928,12 @@
         public PendingIntent actionIntent;
 
         private Action(Parcel in) {
-            icon = in.readInt();
+            if (in.readInt() != 0) {
+                mIcon = Icon.CREATOR.createFromParcel(in);
+            }
+            if (mIcon.getType() == Icon.TYPE_RESOURCE) {
+                icon = mIcon.getResId();
+            }
             title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
             if (in.readInt() == 1) {
                 actionIntent = PendingIntent.CREATOR.createFromParcel(in);
@@ -929,15 +943,16 @@
         }
 
         /**
-         * Use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}.
+         * @deprecated Use {@link android.app.Notification.Action.Builder}.
          */
+        @Deprecated
         public Action(int icon, CharSequence title, PendingIntent intent) {
-            this(icon, title, intent, new Bundle(), null);
+            this(Icon.createWithResource("", icon), title, intent, new Bundle(), null);
         }
 
-        private Action(int icon, CharSequence title, PendingIntent intent, Bundle extras,
+        private Action(Icon icon, CharSequence title, PendingIntent intent, Bundle extras,
                 RemoteInput[] remoteInputs) {
-            this.icon = icon;
+            this.mIcon = icon;
             this.title = title;
             this.actionIntent = intent;
             this.mExtras = extras != null ? extras : new Bundle();
@@ -945,6 +960,17 @@
         }
 
         /**
+         * Return an icon representing the action.
+         */
+        public Icon getIcon() {
+            if (mIcon == null && icon != 0) {
+                // you snuck an icon in here without using the builder; let's try to keep it
+                mIcon = Icon.createWithResource("", icon);
+            }
+            return mIcon;
+        }
+
+        /**
          * Get additional metadata carried around with this Action.
          */
         public Bundle getExtras() {
@@ -963,7 +989,7 @@
          * Builder class for {@link Action} objects.
          */
         public static final class Builder {
-            private final int mIcon;
+            private final Icon mIcon;
             private final CharSequence mTitle;
             private final PendingIntent mIntent;
             private final Bundle mExtras;
@@ -975,7 +1001,18 @@
              * @param title the title of the action
              * @param intent the {@link PendingIntent} to fire when users trigger this action
              */
+            @Deprecated
             public Builder(int icon, CharSequence title, PendingIntent intent) {
+                this(Icon.createWithResource("", icon), title, intent, new Bundle(), null);
+            }
+
+            /**
+             * Construct a new builder for {@link Action} object.
+             * @param icon icon to show for this action
+             * @param title the title of the action
+             * @param intent the {@link PendingIntent} to fire when users trigger this action
+             */
+            public Builder(Icon icon, CharSequence title, PendingIntent intent) {
                 this(icon, title, intent, new Bundle(), null);
             }
 
@@ -985,11 +1022,11 @@
              * @param action the action to read fields from.
              */
             public Builder(Action action) {
-                this(action.icon, action.title, action.actionIntent, new Bundle(action.mExtras),
+                this(action.getIcon(), action.title, action.actionIntent, new Bundle(action.mExtras),
                         action.getRemoteInputs());
             }
 
-            private Builder(int icon, CharSequence title, PendingIntent intent, Bundle extras,
+            private Builder(Icon icon, CharSequence title, PendingIntent intent, Bundle extras,
                     RemoteInput[] remoteInputs) {
                 mIcon = icon;
                 mTitle = title;
@@ -1063,7 +1100,7 @@
         @Override
         public Action clone() {
             return new Action(
-                    icon,
+                    getIcon(),
                     title,
                     actionIntent, // safe to alias
                     new Bundle(mExtras),
@@ -1075,7 +1112,13 @@
         }
         @Override
         public void writeToParcel(Parcel out, int flags) {
-            out.writeInt(icon);
+            final Icon ic = getIcon();
+            if (ic != null) {
+                out.writeInt(1);
+                ic.writeToParcel(out, 0);
+            } else {
+                out.writeInt(0);
+            }
             TextUtils.writeToParcel(title, out, flags);
             if (actionIntent != null) {
                 out.writeInt(1);
@@ -2725,7 +2768,10 @@
          * @param icon Resource ID of a drawable that represents the action.
          * @param title Text describing the action.
          * @param intent PendingIntent to be fired when the action is invoked.
+         *
+         * @deprecated Use {@link #addAction(Action)} instead.
          */
+        @Deprecated
         public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
             mActions.add(new Action(icon, safeCharSequence(title), intent));
             return this;
@@ -3122,7 +3168,7 @@
 
         private RemoteViews generateActionButton(Action action) {
             final boolean tombstone = (action.actionIntent == null);
-            RemoteViews button = new RemoteViews(mContext.getPackageName(),
+            RemoteViews button = new BuilderRemoteViews(mContext.getApplicationInfo(),
                     tombstone ? getActionTombstoneLayoutResource()
                               : getActionLayoutResource());
             button.setTextViewCompoundDrawablesRelative(R.id.action0, action.icon, 0, 0, 0);
@@ -4265,7 +4311,7 @@
      *
      * In the expanded form, {@link Notification#bigContentView}, up to 5
      * {@link Notification.Action}s specified with
-     * {@link Notification.Builder#addAction(int, CharSequence, PendingIntent) addAction} will be
+     * {@link Notification.Builder#addAction(Action) addAction} will be
      * shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to
      * {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will be
      * treated as album artwork.
@@ -4391,7 +4437,7 @@
 
         private RemoteViews generateMediaActionButton(Action action) {
             final boolean tombstone = (action.actionIntent == null);
-            RemoteViews button = new RemoteViews(mBuilder.mContext.getPackageName(),
+            RemoteViews button = new BuilderRemoteViews(mBuilder.mContext.getApplicationInfo(),
                     R.layout.notification_material_media_action);
             button.setImageViewResource(R.id.action0, action.icon);
             button.setDrawableParameters(R.id.action0, false, -1,
diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java
index 10e8a53..01a1c18 100644
--- a/core/java/android/app/SystemServiceRegistry.java
+++ b/core/java/android/app/SystemServiceRegistry.java
@@ -691,6 +691,9 @@
             @Override
             public MidiManager createService(ContextImpl ctx) {
                 IBinder b = ServiceManager.getService(Context.MIDI_SERVICE);
+                if (b == null) {
+                    return null;
+                }
                 return new MidiManager(IMidiManager.Stub.asInterface(b));
             }});
 
diff --git a/core/java/android/app/assist/AssistStructure.java b/core/java/android/app/assist/AssistStructure.java
index 9673c98..40126d6 100644
--- a/core/java/android/app/assist/AssistStructure.java
+++ b/core/java/android/app/assist/AssistStructure.java
@@ -812,7 +812,7 @@
          * Returns true if assist data has been blocked starting at this node in the hierarchy.
          */
         public boolean isAssistBlocked() {
-            return (mFlags&ViewNode.FLAGS_ASSIST_BLOCKED) == 0;
+            return (mFlags&ViewNode.FLAGS_ASSIST_BLOCKED) != 0;
         }
 
         /**
diff --git a/core/java/android/bluetooth/le/BluetoothLeScanner.java b/core/java/android/bluetooth/le/BluetoothLeScanner.java
index e09ab56..2ba87744 100644
--- a/core/java/android/bluetooth/le/BluetoothLeScanner.java
+++ b/core/java/android/bluetooth/le/BluetoothLeScanner.java
@@ -79,6 +79,10 @@
      * delivered through {@code callback}.
      * <p>
      * Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
+     * An app must hold
+     * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION ACCESS_COARSE_LOCATION} or
+     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission
+     * in order to get results.
      *
      * @param callback Callback used to deliver scan results.
      * @throws IllegalArgumentException If {@code callback} is null.
@@ -95,6 +99,10 @@
      * Start Bluetooth LE scan. The scan results will be delivered through {@code callback}.
      * <p>
      * Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
+     * An app must hold
+     * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION ACCESS_COARSE_LOCATION} or
+     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission
+     * in order to get results.
      *
      * @param filters {@link ScanFilter}s for finding exact BLE devices.
      * @param settings Settings for the scan.
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index c9f9b56..f786d2f 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -1023,7 +1023,7 @@
      *
      * <p>Note: if you app targets {@link android.os.Build.VERSION_CODES#MNC MNC}
      * and above and declares as using the {@link android.Manifest.permission#CALL_PHONE}
-     * permission which is not granted, then atempting to use this action will
+     * permission which is not granted, then attempting to use this action will
      * result in a {@link java.lang.SecurityException}.
      */
     @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
@@ -3094,6 +3094,13 @@
     @SdkConstant(SdkConstantType.INTENT_CATEGORY)
     public static final String CATEGORY_HOME = "android.intent.category.HOME";
     /**
+     * This is the setup wizard activity, that is the first activity that is displayed
+     * when the user sets up the device for the first time.
+     * @hide
+     */
+    @SdkConstant(SdkConstantType.INTENT_CATEGORY)
+    public static final String CATEGORY_SETUP_WIZARD = "android.intent.category.SETUP_WIZARD";
+    /**
      * This activity is a preference panel.
      */
     @SdkConstant(SdkConstantType.INTENT_CATEGORY)
diff --git a/core/java/android/content/pm/PackageInstaller.java b/core/java/android/content/pm/PackageInstaller.java
index b7ee82d..9341be1 100644
--- a/core/java/android/content/pm/PackageInstaller.java
+++ b/core/java/android/content/pm/PackageInstaller.java
@@ -18,8 +18,10 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.annotation.RequiresPermission;
 import android.annotation.SdkConstant;
 import android.annotation.SdkConstant.SdkConstantType;
+import android.annotation.SystemApi;
 import android.app.ActivityManager;
 import android.content.Context;
 import android.content.Intent;
@@ -889,6 +891,8 @@
         public String abiOverride;
         /** {@hide} */
         public String volumeUuid;
+        /** {@hide} */
+        public String[] grantedRuntimePermissions;
 
         /**
          * Construct parameters for a new package install session.
@@ -914,6 +918,7 @@
             referrerUri = source.readParcelable(null);
             abiOverride = source.readString();
             volumeUuid = source.readString();
+            grantedRuntimePermissions = source.readStringArray();
         }
 
         /**
@@ -987,6 +992,23 @@
             this.referrerUri = referrerUri;
         }
 
+        /**
+         * Sets which runtime permissions to be granted to the package at installation.
+         * Using this API requires holding {@link android.Manifest.permission
+         * #INSTALL_GRANT_RUNTIME_PERMISSIONS}
+         *
+         * @param permissions The permissions to grant or null to grant all runtime
+         *     permissions.
+         *
+         * @hide
+         */
+        @SystemApi
+        @RequiresPermission(android.Manifest.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS)
+        public void setGrantedRuntimePermissions(String[] permissions) {
+            installFlags |= PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS;
+            this.grantedRuntimePermissions = permissions;
+        }
+
         /** {@hide} */
         public void setInstallFlagsInternal() {
             installFlags |= PackageManager.INSTALL_INTERNAL;
@@ -1012,6 +1034,7 @@
             pw.printPair("referrerUri", referrerUri);
             pw.printPair("abiOverride", abiOverride);
             pw.printPair("volumeUuid", volumeUuid);
+            pw.printPair("grantedRuntimePermissions", grantedRuntimePermissions);
             pw.println();
         }
 
@@ -1033,6 +1056,7 @@
             dest.writeParcelable(referrerUri, flags);
             dest.writeString(abiOverride);
             dest.writeString(volumeUuid);
+            dest.writeStringArray(grantedRuntimePermissions);
         }
 
         public static final Parcelable.Creator<SessionParams>
diff --git a/core/java/android/content/pm/PermissionInfo.java b/core/java/android/content/pm/PermissionInfo.java
index 2828d83..d514513 100644
--- a/core/java/android/content/pm/PermissionInfo.java
+++ b/core/java/android/content/pm/PermissionInfo.java
@@ -145,12 +145,10 @@
     public static final int FLAG_COSTS_MONEY = 1<<0;
 
     /**
-     * Flag for {@link #protectionLevel}, corresponding
-     * to the <code>hide</code> value of
-     * {@link android.R.attr#permissionFlags}.
-     * @hide
+     * Flag for {@link #flags}, indicating that this permission has been
+     * installed into the system's globally defined permissions.
      */
-    public static final int PROTECTION_FLAG_HIDE = 1<<1;
+    public static final int FLAG_INSTALLED = 1<<30;
 
     /**
      * Additional flags about this permission as given by
@@ -210,6 +208,15 @@
         if ((level&PermissionInfo.PROTECTION_FLAG_PRE23) != 0) {
             protLevel += "|pre23";
         }
+        if ((level&PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0) {
+            protLevel += "|installer";
+        }
+        if ((level&PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0) {
+            protLevel += "|verifier";
+        }
+        if ((level&PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0) {
+            protLevel += "|preinstalled";
+        }
         return protLevel;
     }
 
diff --git a/core/java/android/content/res/DrawableCache.java b/core/java/android/content/res/DrawableCache.java
index fc70bc60..ba00134 100644
--- a/core/java/android/content/res/DrawableCache.java
+++ b/core/java/android/content/res/DrawableCache.java
@@ -52,6 +52,6 @@
 
     @Override
     public boolean shouldInvalidateEntry(Drawable.ConstantState entry, int configChanges) {
-        return false;
+        return Configuration.needNewResources(configChanges, entry.getChangingConfigurations());
     }
 }
diff --git a/core/java/android/hardware/camera2/CameraCaptureSession.java b/core/java/android/hardware/camera2/CameraCaptureSession.java
index 46cafad..46ffe36 100644
--- a/core/java/android/hardware/camera2/CameraCaptureSession.java
+++ b/core/java/android/hardware/camera2/CameraCaptureSession.java
@@ -138,6 +138,45 @@
      */
     public abstract void prepare(@NonNull Surface surface) throws CameraAccessException;
 
+
+    /**
+     * <p>Free all buffers allocated for an output Surface.</p>
+     *
+     * <p>Normally, once allocated, the image buffers for a given output Surface remain allocated
+     * for the lifetime of the capture session, to minimize latency of captures and to reduce
+     * memory allocation overhead.</p>
+     *
+     * <p>However, in some cases, it may be desirable for allocated buffers to be freed to reduce
+     * the application's memory consumption, if the particular output Surface will not be used by
+     * the application for some time.</p>
+     *
+     * <p>The tearDown() method can be used to perform this operation. After the call finishes, all
+     * unfilled image buffers will have been freed. Any future use of the target Surface may require
+     * allocation of additional buffers, as if the session had just been created.  Buffers being
+     * held by the application (either explicitly as Image objects from ImageReader, or implicitly
+     * as the current texture in a SurfaceTexture or the current contents of a RS Allocation, will
+     * remain valid and allocated even when tearDown is invoked.</p>
+     *
+     * <p>A Surface that has had tearDown() called on it is eligible to have prepare() invoked on it
+     * again even if it was used as a request target before the tearDown() call, as long as it
+     * doesn't get used as a target of a request between the tearDown() and prepare() calls.</p>
+     *
+     * @param surface the output Surface for which buffers should be freed. Must be one of the
+     * the output Surfaces used to create this session.
+     *
+     * @throws CameraAccessException if the camera device is no longer connected or has
+     *                               encountered a fatal error.
+     * @throws IllegalStateException if this session is no longer active, either because the session
+     *                               was explicitly closed, a new session has been created
+     *                               or the camera device has been closed.
+     * @throws IllegalArgumentException if the Surface is invalid, not part of this Session, or has
+     *                                  already been used as a target of a CaptureRequest in this
+     *                                  session or immediately prior sessions.
+     *
+     * @hide
+     */
+    public abstract void tearDown(@NonNull Surface surface) throws CameraAccessException;
+
     /**
      * <p>Submit a request for an image to be captured by the camera device.</p>
      *
diff --git a/core/java/android/hardware/camera2/CameraMetadata.java b/core/java/android/hardware/camera2/CameraMetadata.java
index c36683b..af1367c 100644
--- a/core/java/android/hardware/camera2/CameraMetadata.java
+++ b/core/java/android/hardware/camera2/CameraMetadata.java
@@ -1994,8 +1994,9 @@
     public static final int EDGE_MODE_OFF = 0;
 
     /**
-     * <p>Apply edge enhancement at a quality level that does not slow down frame rate relative to sensor
-     * output</p>
+     * <p>Apply edge enhancement at a quality level that does not slow down frame rate
+     * relative to sensor output. It may be the same as OFF if edge enhancement will
+     * slow down frame rate relative to sensor.</p>
      * @see CaptureRequest#EDGE_MODE
      */
     public static final int EDGE_MODE_FAST = 1;
@@ -2117,7 +2118,8 @@
 
     /**
      * <p>Noise reduction is applied without reducing frame rate relative to sensor
-     * output.</p>
+     * output. It may be the same as OFF if noise reduction will reduce frame rate
+     * relative to sensor.</p>
      * @see CaptureRequest#NOISE_REDUCTION_MODE
      */
     public static final int NOISE_REDUCTION_MODE_FAST = 1;
diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java
index a136d0f..e965d65 100644
--- a/core/java/android/hardware/camera2/CaptureRequest.java
+++ b/core/java/android/hardware/camera2/CaptureRequest.java
@@ -1584,8 +1584,9 @@
      * will be applied. HIGH_QUALITY mode indicates that the
      * camera device will use the highest-quality enhancement algorithms,
      * even if it slows down capture rate. FAST means the camera device will
-     * not slow down capture rate when applying edge enhancement. Every output stream will
-     * have a similar amount of enhancement applied.</p>
+     * not slow down capture rate when applying edge enhancement. FAST may be the same as OFF if
+     * edge enhancement will slow down capture rate. Every output stream will have a similar
+     * amount of enhancement applied.</p>
      * <p>ZERO_SHUTTER_LAG is meant to be used by applications that maintain a continuous circular
      * buffer of high-resolution images during preview and reprocess image(s) from that buffer
      * into a final capture when triggered by the user. In this mode, the camera device applies
@@ -1594,7 +1595,7 @@
      * since those will be reprocessed later if necessary.</p>
      * <p>For YUV_REPROCESSING, these FAST/HIGH_QUALITY modes both mean that the camera
      * device will apply FAST/HIGH_QUALITY YUV-domain edge enhancement, respectively.
-     * The camera device may adjust its internal noise reduction parameters for best
+     * The camera device may adjust its internal edge enhancement parameters for best
      * image quality based on the {@link CaptureRequest#REPROCESS_EFFECTIVE_EXPOSURE_FACTOR android.reprocess.effectiveExposureFactor}, if it is set.</p>
      * <p><b>Possible values:</b>
      * <ul>
@@ -2003,8 +2004,9 @@
      * will be applied. HIGH_QUALITY mode indicates that the camera device
      * will use the highest-quality noise filtering algorithms,
      * even if it slows down capture rate. FAST means the camera device will not
-     * slow down capture rate when applying noise filtering. Every output stream will
-     * have a similar amount of enhancement applied.</p>
+     * slow down capture rate when applying noise filtering. FAST may be the same as MINIMAL if
+     * MINIMAL is listed, or the same as OFF if any noise filtering will slow down capture rate.
+     * Every output stream will have a similar amount of enhancement applied.</p>
      * <p>ZERO_SHUTTER_LAG is meant to be used by applications that maintain a continuous circular
      * buffer of high-resolution images during preview and reprocess image(s) from that buffer
      * into a final capture when triggered by the user. In this mode, the camera device applies
diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java
index f7cf1850..d5511c1 100644
--- a/core/java/android/hardware/camera2/CaptureResult.java
+++ b/core/java/android/hardware/camera2/CaptureResult.java
@@ -2095,8 +2095,9 @@
      * will be applied. HIGH_QUALITY mode indicates that the
      * camera device will use the highest-quality enhancement algorithms,
      * even if it slows down capture rate. FAST means the camera device will
-     * not slow down capture rate when applying edge enhancement. Every output stream will
-     * have a similar amount of enhancement applied.</p>
+     * not slow down capture rate when applying edge enhancement. FAST may be the same as OFF if
+     * edge enhancement will slow down capture rate. Every output stream will have a similar
+     * amount of enhancement applied.</p>
      * <p>ZERO_SHUTTER_LAG is meant to be used by applications that maintain a continuous circular
      * buffer of high-resolution images during preview and reprocess image(s) from that buffer
      * into a final capture when triggered by the user. In this mode, the camera device applies
@@ -2105,7 +2106,7 @@
      * since those will be reprocessed later if necessary.</p>
      * <p>For YUV_REPROCESSING, these FAST/HIGH_QUALITY modes both mean that the camera
      * device will apply FAST/HIGH_QUALITY YUV-domain edge enhancement, respectively.
-     * The camera device may adjust its internal noise reduction parameters for best
+     * The camera device may adjust its internal edge enhancement parameters for best
      * image quality based on the {@link CaptureRequest#REPROCESS_EFFECTIVE_EXPOSURE_FACTOR android.reprocess.effectiveExposureFactor}, if it is set.</p>
      * <p><b>Possible values:</b>
      * <ul>
@@ -2786,8 +2787,9 @@
      * will be applied. HIGH_QUALITY mode indicates that the camera device
      * will use the highest-quality noise filtering algorithms,
      * even if it slows down capture rate. FAST means the camera device will not
-     * slow down capture rate when applying noise filtering. Every output stream will
-     * have a similar amount of enhancement applied.</p>
+     * slow down capture rate when applying noise filtering. FAST may be the same as MINIMAL if
+     * MINIMAL is listed, or the same as OFF if any noise filtering will slow down capture rate.
+     * Every output stream will have a similar amount of enhancement applied.</p>
      * <p>ZERO_SHUTTER_LAG is meant to be used by applications that maintain a continuous circular
      * buffer of high-resolution images during preview and reprocess image(s) from that buffer
      * into a final capture when triggered by the user. In this mode, the camera device applies
diff --git a/core/java/android/hardware/camera2/ICameraDeviceUser.aidl b/core/java/android/hardware/camera2/ICameraDeviceUser.aidl
index 1574f93..7cb3673 100644
--- a/core/java/android/hardware/camera2/ICameraDeviceUser.aidl
+++ b/core/java/android/hardware/camera2/ICameraDeviceUser.aidl
@@ -100,4 +100,6 @@
     int flush(out LongParcelable lastFrameNumber);
 
     int prepare(int streamId);
+
+    int tearDown(int streamId);
 }
diff --git a/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java
index 3c19cd2..d325c77 100644
--- a/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java
@@ -146,6 +146,11 @@
     }
 
     @Override
+    public void tearDown(Surface surface) throws CameraAccessException {
+        mDeviceImpl.tearDown(surface);
+    }
+
+    @Override
     public synchronized int capture(CaptureRequest request, CaptureCallback callback,
             Handler handler) throws CameraAccessException {
         if (request == null) {
diff --git a/core/java/android/hardware/camera2/impl/CameraConstrainedHighSpeedCaptureSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraConstrainedHighSpeedCaptureSessionImpl.java
index d732535..a920e2b 100644
--- a/core/java/android/hardware/camera2/impl/CameraConstrainedHighSpeedCaptureSessionImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraConstrainedHighSpeedCaptureSessionImpl.java
@@ -169,6 +169,11 @@
     }
 
     @Override
+    public void tearDown(Surface surface) throws CameraAccessException {
+        mSessionImpl.tearDown(surface);
+    }
+
+    @Override
     public int capture(CaptureRequest request, CaptureCallback listener, Handler handler)
             throws CameraAccessException {
         throw new UnsupportedOperationException("Constrained high speed session doesn't support"
diff --git a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
index c594228..91d623e 100644
--- a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
+++ b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java
@@ -679,6 +679,31 @@
         }
     }
 
+    public void tearDown(Surface surface) throws CameraAccessException {
+        if (surface == null) throw new IllegalArgumentException("Surface is null");
+
+        synchronized(mInterfaceLock) {
+            int streamId = -1;
+            for (int i = 0; i < mConfiguredOutputs.size(); i++) {
+                if (surface == mConfiguredOutputs.valueAt(i).getSurface()) {
+                    streamId = mConfiguredOutputs.keyAt(i);
+                    break;
+                }
+            }
+            if (streamId == -1) {
+                throw new IllegalArgumentException("Surface is not part of this session");
+            }
+            try {
+                mRemoteDevice.tearDown(streamId);
+            } catch (CameraRuntimeException e) {
+                throw e.asChecked();
+            } catch (RemoteException e) {
+                // impossible
+                return;
+            }
+        }
+    }
+
     public int capture(CaptureRequest request, CaptureCallback callback, Handler handler)
             throws CameraAccessException {
         if (DEBUG) {
diff --git a/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java b/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
index f5314da..e20eaa7 100644
--- a/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
+++ b/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
@@ -636,6 +636,20 @@
         return CameraBinderDecorator.NO_ERROR;
     }
 
+    public int tearDown(int streamId) {
+        if (DEBUG) {
+            Log.d(TAG, "tearDown called.");
+        }
+        if (mLegacyDevice.isClosed()) {
+            Log.e(TAG, "Cannot tear down stream, device has been closed.");
+            return CameraBinderDecorator.ENODEV;
+        }
+
+        // LEGACY doesn't support actual teardown, so just a no-op
+
+        return CameraBinderDecorator.NO_ERROR;
+    }
+
     @Override
     public IBinder asBinder() {
         // This is solely intended to be used for in-process binding.
diff --git a/core/java/android/hardware/fingerprint/FingerprintManager.java b/core/java/android/hardware/fingerprint/FingerprintManager.java
index c5f142a..ee37047 100644
--- a/core/java/android/hardware/fingerprint/FingerprintManager.java
+++ b/core/java/android/hardware/fingerprint/FingerprintManager.java
@@ -321,6 +321,14 @@
          * Called when a fingerprint is valid but not recognized.
          */
         public void onAuthenticationFailed() { }
+
+        /**
+         * Called when a fingerprint image has been acquired, but wasn't processed yet.
+         *
+         * @param acquireInfo one of FINGERPRINT_ACQUIRED_* constants
+         * @hide
+         */
+        public void onAuthenticationAcquired(int acquireInfo) {}
     };
 
     /**
@@ -737,9 +745,13 @@
         }
 
         private void sendAcquiredResult(long deviceId, int acquireInfo) {
+            if (mAuthenticationCallback != null) {
+                mAuthenticationCallback.onAuthenticationAcquired(acquireInfo);
+            }
             final String msg = getAcquiredString(acquireInfo);
-            if (msg == null) return;
-
+            if (msg == null) {
+                return;
+            }
             if (mEnrollmentCallback != null) {
                 mEnrollmentCallback.onEnrollmentHelp(acquireInfo, msg);
             } else if (mAuthenticationCallback != null) {
diff --git a/core/java/android/inputmethodservice/ExtractEditText.java b/core/java/android/inputmethodservice/ExtractEditText.java
index b039fc7..a2c1d18 100644
--- a/core/java/android/inputmethodservice/ExtractEditText.java
+++ b/core/java/android/inputmethodservice/ExtractEditText.java
@@ -103,8 +103,12 @@
     }
 
     @Override public boolean onTextContextMenuItem(int id) {
-        // Select all shouldn't be handled by the original edit text, but by the extracted one.
-        if (id != android.R.id.selectAll && mIME != null && mIME.onExtractTextContextMenuItem(id)) {
+        // Select all and Replace text shouldn't be handled by the original edit text, but by the
+        // extracted one.
+        if (id == android.R.id.selectAll || id == android.R.id.replaceText) {
+            return super.onTextContextMenuItem(id);
+        }
+        if (mIME != null && mIME.onExtractTextContextMenuItem(id)) {
             // Mode was started on Extracted, needs to be stopped here.
             // Cut will change the text, which stops selection mode.
             if (id == android.R.id.copy || id == android.R.id.paste) stopTextActionMode();
diff --git a/core/java/android/os/FileUtils.java b/core/java/android/os/FileUtils.java
index 864225a..af4c2bc 100644
--- a/core/java/android/os/FileUtils.java
+++ b/core/java/android/os/FileUtils.java
@@ -16,6 +16,7 @@
 
 package android.os;
 
+import android.annotation.NonNull;
 import android.provider.DocumentsContract.Document;
 import android.system.ErrnoException;
 import android.system.Os;
@@ -69,6 +70,8 @@
     /** Regular expression for safe filenames: no spaces or metacharacters */
     private static final Pattern SAFE_FILENAME_PATTERN = Pattern.compile("[\\w%+,./=_-]+");
 
+    private static final File[] EMPTY = new File[0];
+
     /**
      * Set owner and mode of of given {@link File}.
      *
@@ -634,4 +637,13 @@
             return new File(parent, name + "." + ext);
         }
     }
+
+    public static @NonNull File[] listFilesOrEmpty(File dir) {
+        File[] res = dir.listFiles();
+        if (res != null) {
+            return res;
+        } else {
+            return EMPTY;
+        }
+    }
 }
diff --git a/core/java/android/os/IDeviceIdleController.aidl b/core/java/android/os/IDeviceIdleController.aidl
index b768852..d3eec1e 100644
--- a/core/java/android/os/IDeviceIdleController.aidl
+++ b/core/java/android/os/IDeviceIdleController.aidl
@@ -29,5 +29,6 @@
     boolean isPowerSaveWhitelistApp(String name);
     void addPowerSaveTempWhitelistApp(String name, long duration, int userId, String reason);
     long addPowerSaveTempWhitelistAppForMms(String name, int userId, String reason);
+    long addPowerSaveTempWhitelistAppForSms(String name, int userId, String reason);
     void exitIdle(String reason);
 }
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index b104135..79fb805 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -45,7 +45,9 @@
     private final Context mContext;
 
     /**
-     * Specifies if a user is disallowed from adding and removing accounts.
+     * Specifies if a user is disallowed from adding and removing accounts, unless they are
+     * {@link android.accounts.AccountManager#addAccountExplicitly programmatically} added by
+     * Authenticator.
      * The default value is <code>false</code>.
      *
      * <p/>Key for user restrictions.
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index 2b75f31..b2cec60 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -860,8 +860,23 @@
         final IMountService mountService = IMountService.Stub.asInterface(
                 ServiceManager.getService("mount"));
         try {
-            final String packageName = ActivityThread.currentOpPackageName();
+            String packageName = ActivityThread.currentOpPackageName();
+            if (packageName == null) {
+                // Package name can be null if the activity thread is running but the app
+                // hasn't bound yet. In this case we fall back to the first package in the
+                // current UID. This works for runtime permissions as permission state is
+                // per UID and permission realted app ops are updated for all UID packages.
+                String[] packageNames = ActivityThread.getPackageManager().getPackagesForUid(
+                        android.os.Process.myUid());
+                if (packageNames == null || packageNames.length <= 0) {
+                    return new StorageVolume[0];
+                }
+                packageName = packageNames[0];
+            }
             final int uid = ActivityThread.getPackageManager().getPackageUid(packageName, userId);
+            if (uid <= 0) {
+                return new StorageVolume[0];
+            }
             return mountService.getVolumeList(uid, packageName);
         } catch (RemoteException e) {
             throw e.rethrowAsRuntimeException();
diff --git a/core/java/android/provider/CalendarContract.java b/core/java/android/provider/CalendarContract.java
index d743484..aa22041 100644
--- a/core/java/android/provider/CalendarContract.java
+++ b/core/java/android/provider/CalendarContract.java
@@ -2393,7 +2393,7 @@
             intent.setData(ContentUris.withAppendedId(CalendarContract.CONTENT_URI, alarmTime));
             intent.putExtra(ALARM_TIME, alarmTime);
             PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
-            manager.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pi);
+            manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, alarmTime, pi);
         }
 
         /**
diff --git a/core/java/android/provider/ContactsContract.java b/core/java/android/provider/ContactsContract.java
index d547a60..8ce1cbf 100644
--- a/core/java/android/provider/ContactsContract.java
+++ b/core/java/android/provider/ContactsContract.java
@@ -5957,9 +5957,7 @@
              */
             public static final CharSequence getTypeLabel(Resources res, int type,
                     CharSequence label) {
-                if (type == TYPE_CUSTOM) {
-                    return (label != null ? label : "");
-                } else if (type == TYPE_ASSISTANT && !TextUtils.isEmpty(label)) {
+                if ((type == TYPE_CUSTOM || type == TYPE_ASSISTANT) && !TextUtils.isEmpty(label)) {
                     return label;
                 } else {
                     final int labelRes = getTypeLabelResource(type);
diff --git a/core/java/android/provider/VoicemailContract.java b/core/java/android/provider/VoicemailContract.java
index e1b5a6d..76eaea9 100644
--- a/core/java/android/provider/VoicemailContract.java
+++ b/core/java/android/provider/VoicemailContract.java
@@ -314,11 +314,16 @@
             contentValues.put(Voicemails.IS_READ, voicemail.isRead() ? 1 : 0);
 
             PhoneAccountHandle phoneAccount = voicemail.getPhoneAccount();
-            if (voicemail.getPhoneAccount() != null) {
+            if (phoneAccount != null) {
                 contentValues.put(Voicemails.PHONE_ACCOUNT_COMPONENT_NAME,
                         phoneAccount.getComponentName().flattenToString());
                 contentValues.put(Voicemails.PHONE_ACCOUNT_ID, phoneAccount.getId());
             }
+
+            if (voicemail.getTranscription() != null) {
+                contentValues.put(Voicemails.TRANSCRIPTION, voicemail.getTranscription());
+            }
+
             return contentValues;
         }
     }
diff --git a/core/java/android/security/keymaster/KeymasterDefs.java b/core/java/android/security/keymaster/KeymasterDefs.java
index bae5455..04d5952 100644
--- a/core/java/android/security/keymaster/KeymasterDefs.java
+++ b/core/java/android/security/keymaster/KeymasterDefs.java
@@ -51,6 +51,7 @@
     public static final int KM_TAG_DIGEST = KM_ENUM_REP | 5;
     public static final int KM_TAG_PADDING = KM_ENUM_REP | 6;
     public static final int KM_TAG_CALLER_NONCE = KM_BOOL | 7;
+    public static final int KM_TAG_MIN_MAC_LENGTH = KM_UINT | 8;
 
     public static final int KM_TAG_RESCOPING_ADD = KM_ENUM_REP | 101;
     public static final int KM_TAG_RESCOPING_DEL = KM_ENUM_REP | 102;
@@ -194,6 +195,9 @@
     public static final int KM_ERROR_KEY_RATE_LIMIT_EXCEEDED = -54;
     public static final int KM_ERROR_CALLER_NONCE_PROHIBITED = -55;
     public static final int KM_ERROR_KEY_MAX_OPS_EXCEEDED = -56;
+    public static final int KM_ERROR_INVALID_MAC_LENGTH = -57;
+    public static final int KM_ERROR_MISSING_MIN_MAC_LENGTH = -58;
+    public static final int KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH = -59;
     public static final int KM_ERROR_UNIMPLEMENTED = -100;
     public static final int KM_ERROR_VERSION_MISMATCH = -101;
     public static final int KM_ERROR_UNKNOWN_ERROR = -1000;
@@ -237,6 +241,8 @@
         sErrorCodeToString.put(KM_ERROR_INVALID_NONCE, "Invalid IV");
         sErrorCodeToString.put(KM_ERROR_CALLER_NONCE_PROHIBITED,
                 "Caller-provided IV not permitted");
+        sErrorCodeToString.put(KM_ERROR_INVALID_MAC_LENGTH,
+                "Invalid MAC or authentication tag length");
         sErrorCodeToString.put(KM_ERROR_UNIMPLEMENTED, "Not implemented");
         sErrorCodeToString.put(KM_ERROR_UNKNOWN_ERROR, "Unknown error");
     }
diff --git a/core/java/android/service/chooser/ChooserTarget.java b/core/java/android/service/chooser/ChooserTarget.java
index 50c435a..c2f70cc 100644
--- a/core/java/android/service/chooser/ChooserTarget.java
+++ b/core/java/android/service/chooser/ChooserTarget.java
@@ -17,20 +17,14 @@
 
 package android.service.chooser;
 
-import android.app.Activity;
-import android.app.PendingIntent;
+import android.annotation.Nullable;
 import android.content.ComponentName;
-import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.content.IntentSender;
-import android.graphics.Bitmap;
 import android.graphics.drawable.Icon;
 import android.os.Bundle;
 import android.os.Parcel;
 import android.os.Parcelable;
-import android.os.UserHandle;
-import android.util.Log;
 
 /**
  * A ChooserTarget represents a deep-link into an application as returned by a
@@ -62,11 +56,16 @@
     private Icon mIcon;
 
     /**
-     * The IntentSender that will be used to deliver the intent to the target.
-     * It will be {@link android.content.Intent#fillIn(android.content.Intent, int)} filled in}
-     * by the real intent sent by the application.
+     * The ComponentName of the Activity to be invoked. Must be part of the target creator's
+     * own package or an Activity exported by its package.
      */
-    private IntentSender mIntentSender;
+    private ComponentName mComponentName;
+
+    /**
+     * A Bundle to merge with the extras of the intent sent to this target.
+     * Any extras here will override the extras from the original intent.
+     */
+    private Bundle mIntentExtras;
 
     /**
      * The score given to this item. It can be normalized.
@@ -86,61 +85,23 @@
      * Scores should be in the range from 0.0f (unlikely match) to 1.0f (very relevant match).
      * Scores for a set of targets do not need to sum to 1.</p>
      *
-     * <p>Before being sent, the PendingIntent supplied will be
-     * {@link Intent#fillIn(Intent, int) filled in} by the Intent originally supplied
-     * to the chooser. When constructing a PendingIntent for use in a ChooserTarget, make sure
-     * that you permit the relevant fields to be filled in using the appropriate flags such as
-     * {@link Intent#FILL_IN_ACTION}, {@link Intent#FILL_IN_CATEGORIES},
-     * {@link Intent#FILL_IN_DATA} and {@link Intent#FILL_IN_CLIP_DATA}. Note that
-     * {@link Intent#FILL_IN_CLIP_DATA} is required to appropriately receive URI permission grants
-     * for {@link Intent#ACTION_SEND} intents.</p>
+     * <p>The ComponentName must be the name of an Activity component in the creator's own
+     * package, or an exported component from any other package. You may provide an optional
+     * Bundle of extras that will be merged into the final intent before it is sent to the
+     * target Activity; use this to add any additional data about the deep link that the target
+     * activity will read. e.g. conversation IDs, email addresses, etc.</p>
      *
      * <p>Take care not to place custom {@link android.os.Parcelable} types into
-     * the PendingIntent as extras, as the system will not be able to unparcel it to merge
-     * additional extras.</p>
+     * the extras bundle, as the system will not be able to unparcel them to merge them.</p>
      *
      * @param title title of this target that will be shown to a user
      * @param icon icon to represent this target
      * @param score ranking score for this target between 0.0f and 1.0f, inclusive
-     * @param pendingIntent PendingIntent to fill in and send if the user chooses this target
+     * @param componentName Name of the component to be launched if this target is chosen
+     * @param intentExtras Bundle of extras to merge with the extras of the launched intent
      */
     public ChooserTarget(CharSequence title, Icon icon, float score,
-            PendingIntent pendingIntent) {
-        this(title, icon, score, pendingIntent.getIntentSender());
-    }
-
-    /**
-     * Construct a deep link target for presentation by a chooser UI.
-     *
-     * <p>A target is composed of a title and an icon for presentation to the user.
-     * The UI presenting this target may truncate the title if it is too long to be presented
-     * in the available space, as well as crop, resize or overlay the supplied icon.</p>
-     *
-     * <p>The creator of a target may supply a ranking score. This score is assumed to be relative
-     * to the other targets supplied by the same
-     * {@link ChooserTargetService#onGetChooserTargets(ComponentName, IntentFilter) query}.
-     * Scores should be in the range from 0.0f (unlikely match) to 1.0f (very relevant match).
-     * Scores for a set of targets do not need to sum to 1.</p>
-     *
-     * <p>Before being sent, the IntentSender supplied will be
-     * {@link Intent#fillIn(Intent, int) filled in} by the Intent originally supplied
-     * to the chooser. When constructing an IntentSender for use in a ChooserTarget, make sure
-     * that you permit the relevant fields to be filled in using the appropriate flags such as
-     * {@link Intent#FILL_IN_ACTION}, {@link Intent#FILL_IN_CATEGORIES},
-     * {@link Intent#FILL_IN_DATA} and {@link Intent#FILL_IN_CLIP_DATA}. Note that
-     * {@link Intent#FILL_IN_CLIP_DATA} is required to appropriately receive URI permission grants
-     * for {@link Intent#ACTION_SEND} intents.</p>
-     *
-     * <p>Take care not to place custom {@link android.os.Parcelable} types into
-     * the IntentSender as extras, as the system will not be able to unparcel it to merge
-     * additional extras.</p>
-     *
-     * @param title title of this target that will be shown to a user
-     * @param icon icon to represent this target
-     * @param score ranking score for this target between 0.0f and 1.0f, inclusive
-     * @param intentSender IntentSender to fill in and send if the user chooses this target
-     */
-    public ChooserTarget(CharSequence title, Icon icon, float score, IntentSender intentSender) {
+            ComponentName componentName, @Nullable Bundle intentExtras) {
         mTitle = title;
         mIcon = icon;
         if (score > 1.f || score < 0.f) {
@@ -148,7 +109,8 @@
                     + "must be between 0.0f and 1.0f");
         }
         mScore = score;
-        mIntentSender = intentSender;
+        mComponentName = componentName;
+        mIntentExtras = intentExtras;
     }
 
     ChooserTarget(Parcel in) {
@@ -159,7 +121,8 @@
             mIcon = null;
         }
         mScore = in.readFloat();
-        mIntentSender = IntentSender.readIntentSenderOrNullFromParcel(in);
+        mComponentName = ComponentName.readFromParcel(in);
+        mIntentExtras = in.readBundle();
     }
 
     /**
@@ -194,49 +157,29 @@
     }
 
     /**
-     * Returns the raw IntentSender supplied by the ChooserTarget's creator.
-     * This may be null if the creator specified a regular Intent instead.
+     * Returns the ComponentName of the Activity that should be launched for this ChooserTarget.
      *
-     * <p>To fill in and send the intent, see {@link #sendIntent(Context, Intent)}.</p>
-     *
-     * @return the IntentSender supplied by the ChooserTarget's creator
+     * @return the name of the target Activity to launch
      */
-    public IntentSender getIntentSender() {
-        return mIntentSender;
+    public ComponentName getComponentName() {
+        return mComponentName;
     }
 
     /**
-     * Fill in the IntentSender supplied by the ChooserTarget's creator and send it.
+     * Returns the Bundle of extras to be added to an intent launched to this target.
      *
-     * @param context the sending Context; generally the Activity presenting the chooser UI
-     * @param fillInIntent the Intent provided to the Chooser to be sent to a selected target
-     * @return true if sending the Intent was successful
+     * @return the extras to merge with the extras of the intent being launched
      */
-    public boolean sendIntent(Context context, Intent fillInIntent) {
-        if (fillInIntent != null) {
-            fillInIntent.migrateExtraStreamToClipData();
-            fillInIntent.prepareToLeaveProcess();
-        }
-        if (mIntentSender != null) {
-            try {
-                mIntentSender.sendIntent(context, 0, fillInIntent, null, null);
-                return true;
-            } catch (IntentSender.SendIntentException e) {
-                Log.e(TAG, "sendIntent " + this + " failed", e);
-                return false;
-            }
-        } else {
-            Log.e(TAG, "sendIntent " + this + " failed - no IntentSender to send");
-            return false;
-        }
+    public Bundle getIntentExtras() {
+        return mIntentExtras;
     }
 
     @Override
     public String toString() {
         return "ChooserTarget{"
-                + (mIntentSender != null ? mIntentSender.getCreatorPackage() : null)
-                + ", "
-                + "'" + mTitle
+                + mComponentName
+                + ", " + mIntentExtras
+                + ", '" + mTitle
                 + "', " + mScore + "}";
     }
 
@@ -255,7 +198,8 @@
             dest.writeInt(0);
         }
         dest.writeFloat(mScore);
-        IntentSender.writeIntentSenderOrNullToParcel(mIntentSender, dest);
+        ComponentName.writeToParcel(mComponentName, dest);
+        dest.writeBundle(mIntentExtras);
     }
 
     public static final Creator<ChooserTarget> CREATOR
diff --git a/core/java/android/service/chooser/ChooserTargetService.java b/core/java/android/service/chooser/ChooserTargetService.java
index a3bfece..e054185 100644
--- a/core/java/android/service/chooser/ChooserTargetService.java
+++ b/core/java/android/service/chooser/ChooserTargetService.java
@@ -105,9 +105,8 @@
      * can handle an intent.
      *
      * <p>The returned list should be sorted such that the most relevant targets appear first.
-     * Any PendingIntents used to construct the resulting ChooserTargets should always be prepared
-     * to have the relevant data fields filled in by the sender. See
-     * {@link ChooserTarget#ChooserTarget(CharSequence, android.graphics.drawable.Icon, float, android.app.PendingIntent) ChooserTarget}.</p>
+     * The score for each ChooserTarget will be combined with the system's score for the original
+     * target Activity to sort and filter targets presented to the user.</p>
      *
      * <p><em>Important:</em> Calls to this method from other applications will occur on
      * a binder thread, not on your app's main thread. Make sure that access to relevant data
diff --git a/core/java/android/service/chooser/IChooserTargetResult.aidl b/core/java/android/service/chooser/IChooserTargetResult.aidl
index dbd7cbd..6c648a2 100644
--- a/core/java/android/service/chooser/IChooserTargetResult.aidl
+++ b/core/java/android/service/chooser/IChooserTargetResult.aidl
@@ -21,7 +21,7 @@
 /**
  * @hide
  */
-interface IChooserTargetResult
+oneway interface IChooserTargetResult
 {
     void sendResult(in List<ChooserTarget> targets);
 }
diff --git a/core/java/android/service/voice/IVoiceInteractionSession.aidl b/core/java/android/service/voice/IVoiceInteractionSession.aidl
index 8fe84e1..dbc28f7 100644
--- a/core/java/android/service/voice/IVoiceInteractionSession.aidl
+++ b/core/java/android/service/voice/IVoiceInteractionSession.aidl
@@ -35,5 +35,6 @@
     void taskStarted(in Intent intent, int taskId);
     void taskFinished(in Intent intent, int taskId);
     void closeSystemDialogs();
+    void onLockscreenShown();
     void destroy();
 }
diff --git a/core/java/android/service/voice/VoiceInteractionService.java b/core/java/android/service/voice/VoiceInteractionService.java
index 549c93e..479c9e2 100644
--- a/core/java/android/service/voice/VoiceInteractionService.java
+++ b/core/java/android/service/voice/VoiceInteractionService.java
@@ -37,7 +37,6 @@
 import java.io.PrintWriter;
 import java.util.Locale;
 
-
 /**
  * Top-level service of the current global voice interactor, which is providing
  * support for hotwording, the back-end of a {@link android.app.VoiceInteractor}, etc.
@@ -154,11 +153,39 @@
     }
 
     /**
+     * Set contextual options you would always like to have disabled when a session
+     * is shown.  The flags may be any combination of
+     * {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST} and
+     * {@link VoiceInteractionSession#SHOW_WITH_SCREENSHOT
+     * VoiceInteractionSession.SHOW_WITH_SCREENSHOT}.
+     */
+    public void setDisabledShowContext(int flags) {
+        try {
+            mSystemService.setDisabledShowContext(flags);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Return the value set by {@link #setDisabledShowContext}.
+     */
+    public int getDisabledShowContext() {
+        try {
+            return mSystemService.getDisabledShowContext();
+        } catch (RemoteException e) {
+            return 0;
+        }
+    }
+
+    /**
      * Request that the associated {@link android.service.voice.VoiceInteractionSession} be
      * shown to the user, starting it if necessary.
      * @param args Arbitrary arguments that will be propagated to the session.
      * @param flags Indicates additional optional behavior that should be performed.  May
-     * be {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST}
+     * be any combination of
+     * {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST} and
+     * {@link VoiceInteractionSession#SHOW_WITH_SCREENSHOT
+      * VoiceInteractionSession.SHOW_WITH_SCREENSHOT}
      * to request that the system generate and deliver assist data on the current foreground
      * app as part of showing the session UI.
      */
diff --git a/core/java/android/service/voice/VoiceInteractionSession.java b/core/java/android/service/voice/VoiceInteractionSession.java
index e408b36..f647aa6 100644
--- a/core/java/android/service/voice/VoiceInteractionSession.java
+++ b/core/java/android/service/voice/VoiceInteractionSession.java
@@ -91,6 +91,12 @@
      */
     public static final int SHOW_SOURCE_ASSIST_GESTURE = 1<<2;
 
+    /**
+     * Flag for use with {@link #onShow}: indicates that the application itself has invoked
+     * the assistant.
+     */
+    public static final int SHOW_SOURCE_APPLICATION = 1<<3;
+
     final Context mContext;
     final HandlerCaller mHandlerCaller;
 
@@ -259,6 +265,11 @@
         }
 
         @Override
+        public void onLockscreenShown() {
+            mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_ON_LOCKSCREEN_SHOWN));
+        }
+
+        @Override
         public void destroy() {
             mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_DESTROY));
         }
@@ -316,6 +327,22 @@
             return mExtras;
         }
 
+        /**
+         * Check whether this request is currently active.  A request becomes inactive after
+         * calling {@link #cancel} or a final result method that completes the request.  After
+         * this point, further interactions with the request will result in
+         * {@link java.lang.IllegalStateException} errors; you should not catch these errors,
+         * but can use this method if you need to determine the state of the request.  Returns
+         * true if the request is still active.
+         */
+        public boolean isActive() {
+            VoiceInteractionSession session = mSession.get();
+            if (session == null) {
+                return false;
+            }
+            return session.isRequestActive(mInterface.asBinder());
+        }
+
         void finishRequest() {
             VoiceInteractionSession session = mSession.get();
             if (session == null) {
@@ -332,6 +359,7 @@
 
         /**
          * Ask the app to cancel this current request.
+         * This also finishes the request (it is no longer active).
          */
         public void cancel() {
             try {
@@ -383,6 +411,7 @@
          * in a call to
          * {@link android.app.VoiceInteractor.ConfirmationRequest#onConfirmationResult
          * VoiceInteractor.ConfirmationRequest.onConfirmationResult}.
+         * This finishes the request (it is no longer active).
          */
         public void sendConfirmationResult(boolean confirmed, Bundle result) {
             try {
@@ -469,6 +498,7 @@
          * and resulting in a call to
          * {@link android.app.VoiceInteractor.PickOptionRequest#onPickOptionResult
          * VoiceInteractor.PickOptionRequest.onPickOptionResult} with false for finished.
+         * This finishes the request (it is no longer active).
          */
         public void sendPickOptionResult(
                 VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) {
@@ -516,6 +546,7 @@
          * in a call to
          * {@link android.app.VoiceInteractor.CompleteVoiceRequest#onCompleteResult
          * VoiceInteractor.CompleteVoiceRequest.onCompleteResult}.
+         * This finishes the request (it is no longer active).
          */
         public void sendCompleteResult(Bundle result) {
             try {
@@ -564,7 +595,8 @@
          * Report that the voice interactor has finished aborting the voice operation, resulting
          * in a call to
          * {@link android.app.VoiceInteractor.AbortVoiceRequest#onAbortResult
-         * VoiceInteractor.AbortVoiceRequest.onAbortResult}.
+         * VoiceInteractor.AbortVoiceRequest.onAbortResult}.  This finishes the request (it
+         * is no longer active).
          */
         public void sendAbortResult(Bundle result) {
             try {
@@ -624,6 +656,7 @@
          * Report the final result of the request, completing the request and resulting in a call to
          * {@link android.app.VoiceInteractor.CommandRequest#onCommandResult
          * VoiceInteractor.CommandRequest.onCommandResult} with true for isCompleted.
+         * This finishes the request (it is no longer active).
          */
         public void sendResult(Bundle result) {
             sendCommandResult(true, result);
@@ -646,11 +679,12 @@
     static final int MSG_HANDLE_SCREENSHOT = 105;
     static final int MSG_SHOW = 106;
     static final int MSG_HIDE = 107;
+    static final int MSG_ON_LOCKSCREEN_SHOWN = 108;
 
     class MyCallbacks implements HandlerCaller.Callback, SoftInputWindow.Callback {
         @Override
         public void executeMessage(Message msg) {
-            SomeArgs args;
+            SomeArgs args = null;
             switch (msg.what) {
                 case MSG_START_CONFIRMATION:
                     if (DEBUG) Log.d(TAG, "onConfirm: req=" + msg.obj);
@@ -676,6 +710,8 @@
                     args = (SomeArgs)msg.obj;
                     if (DEBUG) Log.d(TAG, "onGetSupportedCommands: cmds=" + args.arg1);
                     args.arg1 = onGetSupportedCommands((String[]) args.arg1);
+                    args.complete();
+                    args = null;
                     break;
                 case MSG_CANCEL:
                     if (DEBUG) Log.d(TAG, "onCancel: req=" + ((Request)msg.obj));
@@ -722,6 +758,13 @@
                     if (DEBUG) Log.d(TAG, "doHide");
                     doHide();
                     break;
+                case MSG_ON_LOCKSCREEN_SHOWN:
+                    if (DEBUG) Log.d(TAG, "onLockscreenShown");
+                    onLockscreenShown();
+                    break;
+            }
+            if (args != null) {
+                args.recycle();
             }
         }
 
@@ -809,7 +852,15 @@
     }
 
     void addRequest(Request req) {
-        mActiveRequests.put(req.mInterface.asBinder(), req);
+        synchronized (this) {
+            mActiveRequests.put(req.mInterface.asBinder(), req);
+        }
+    }
+
+    boolean isRequestActive(IBinder reqInterface) {
+        synchronized (this) {
+            return mActiveRequests.containsKey(reqInterface);
+        }
     }
 
     Request removeRequest(IBinder reqInterface) {
@@ -908,12 +959,55 @@
     }
 
     /**
+     * Equivalent to {@link VoiceInteractionService#setDisabledShowContext
+     * VoiceInteractionService.setDisabledShowContext(int)}.
+     */
+    public void setDisabledShowContext(int flags) {
+        try {
+            mSystemService.setDisabledShowContext(flags);
+        } catch (RemoteException e) {
+        }
+    }
+
+    /**
+     * Equivalent to {@link VoiceInteractionService#getDisabledShowContext
+     * VoiceInteractionService.getDisabledShowContext}.
+     */
+    public int getDisabledShowContext() {
+        try {
+            return mSystemService.getDisabledShowContext();
+        } catch (RemoteException e) {
+            return 0;
+        }
+    }
+
+    /**
+     * Return which show context flags have been disabled by the user through the system
+     * settings UI, so the session will never get this data.  Returned flags are any combination of
+     * {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST} and
+     * {@link VoiceInteractionSession#SHOW_WITH_SCREENSHOT
+     * VoiceInteractionSession.SHOW_WITH_SCREENSHOT}.  Note that this only tells you about
+     * global user settings, not about restrictions that may be applied contextual based on
+     * the current application the user is in or other transient states.
+     */
+    public int getUserDisabledShowContext() {
+        try {
+            return mSystemService.getUserDisabledShowContext();
+        } catch (RemoteException e) {
+            return 0;
+        }
+    }
+
+    /**
      * Show the UI for this session.  This asks the system to go through the process of showing
      * your UI, which will eventually culminate in {@link #onShow}.  This is similar to calling
      * {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}.
      * @param args Arbitrary arguments that will be propagated {@link #onShow}.
      * @param flags Indicates additional optional behavior that should be performed.  May
-     * be {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST}
+     * be any combination of
+     * {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST} and
+     * {@link VoiceInteractionSession#SHOW_WITH_SCREENSHOT
+     * VoiceInteractionSession.SHOW_WITH_SCREENSHOT}
      * to request that the system generate and deliver assist data on the current foreground
      * app as part of showing the session UI.
      */
@@ -1148,23 +1242,33 @@
 
     /**
      * Called to receive data from the application that the user was currently viewing when
-     * an assist session is started.
+     * an assist session is started.  If the original show request did not specify
+     * {@link #SHOW_WITH_ASSIST}, this method will not be called.
      *
      * @param data Arbitrary data supplied by the app through
      * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
+     * May be null if assist data has been disabled by the user or device policy.
      * @param structure If available, the structure definition of all windows currently
-     * displayed by the app; if structure has been turned off by the user, will be null.
+     * displayed by the app.  May be null if assist data has been disabled by the user
+     * or device policy; will be an empty stub if the application has disabled assist
+     * by marking its window as secure.
      * @param content Additional content data supplied by the app through
      * {@link android.app.Activity#onProvideAssistContent Activity.onProvideAssistContent}.
+     * May be null if assist data has been disabled by the user or device policy; will
+     * not be automatically filled in with data from the app if the app has marked its
+     * window as secure.
      */
-    public void onHandleAssist(Bundle data, AssistStructure structure, AssistContent content) {
+    public void onHandleAssist(@Nullable Bundle data, @Nullable AssistStructure structure,
+            @Nullable AssistContent content) {
     }
 
     /**
      * Called to receive a screenshot of what the user was currently viewing when an assist
-     * session is started.  Will be null if screenshots are disabled by the user.
+     * session is started.  May be null if screenshots are disabled by the user, policy,
+     * or application.  If the original show request did not specify
+     * {@link #SHOW_WITH_SCREENSHOT}, this method will not be called.
      */
-    public void onHandleScreenshot(Bitmap screenshot) {
+    public void onHandleScreenshot(@Nullable Bitmap screenshot) {
     }
 
     public boolean onKeyDown(int keyCode, KeyEvent event) {
@@ -1202,6 +1306,13 @@
         hide();
     }
 
+    /**
+     * Called when the lockscreen was shown.
+     */
+    public void onLockscreenShown() {
+        hide();
+    }
+
     @Override
     public void onConfigurationChanged(Configuration newConfig) {
     }
diff --git a/core/java/android/text/BidiFormatter.java b/core/java/android/text/BidiFormatter.java
index 7ea9da1..5c088cd 100644
--- a/core/java/android/text/BidiFormatter.java
+++ b/core/java/android/text/BidiFormatter.java
@@ -173,7 +173,7 @@
 
         /**
          * Specifies whether the BidiFormatter to be built should also "reset" directionality before
-         * a string being bidi-wrapped, not just after it. The default is false.
+         * a string being bidi-wrapped, not just after it. The default is true.
          */
         public Builder stereoReset(boolean stereoReset) {
             if (stereoReset) {
@@ -363,12 +363,13 @@
      * If {@code isolate}, directionally isolates the string so that it does not garble its
      * surroundings. Currently, this is done by "resetting" the directionality after the string by
      * appending a trailing Unicode bidi mark matching the context directionality (LRM or RLM) when
-     * either the overall directionality or the exit directionality of the string is opposite to that
-     * of the context. If the formatter was built using {@link Builder#stereoReset(boolean)} and
-     * passing "true" as an argument, also prepends a Unicode bidi mark matching the context
-     * directionality when either the overall directionality or the entry directionality of the
-     * string is opposite to that of the context. Note that as opposed to the overall
-     * directionality, the entry and exit directionalities are determined from the string itself.
+     * either the overall directionality or the exit directionality of the string is opposite to
+     * that of the context. Unless the formatter was built using
+     * {@link Builder#stereoReset(boolean)} with a {@code false} argument, also prepends a Unicode
+     * bidi mark matching the context directionality when either the overall directionality or the
+     * entry directionality of the string is opposite to that of the context. Note that as opposed
+     * to the overall directionality, the entry and exit directionalities are determined from the
+     * string itself.
      * <p>
      * Does *not* do HTML-escaping.
      *
diff --git a/core/java/android/text/TextLine.java b/core/java/android/text/TextLine.java
index 605b91d..39e8694 100644
--- a/core/java/android/text/TextLine.java
+++ b/core/java/android/text/TextLine.java
@@ -741,11 +741,11 @@
 
         if (needWidth || (c != null && (wp.bgColor != 0 || wp.underlineColor != 0 || runIsRtl))) {
             if (mCharsValid) {
-                ret = wp.getRunAdvance(mChars, start, contextEnd, contextStart, contextEnd,
+                ret = wp.getRunAdvance(mChars, start, end, contextStart, contextEnd,
                         runIsRtl, end);
             } else {
                 int delta = mStart;
-                ret = wp.getRunAdvance(mText, delta + start, delta + contextEnd,
+                ret = wp.getRunAdvance(mText, delta + start, delta + end,
                         delta + contextStart, delta + contextEnd, runIsRtl, delta + end);
             }
         }
diff --git a/core/java/android/text/format/Formatter.java b/core/java/android/text/format/Formatter.java
index 82689b9..b5068b2 100644
--- a/core/java/android/text/format/Formatter.java
+++ b/core/java/android/text/format/Formatter.java
@@ -16,12 +16,18 @@
 
 package android.text.format;
 
+import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.content.Context;
 import android.content.res.Resources;
+import android.text.BidiFormatter;
+import android.text.TextUtils;
+import android.view.View;
 import android.net.NetworkUtils;
 import android.net.TrafficStats;
 
+import java.util.Locale;
+
 /**
  * Utility class to aid in formatting common values that are not covered
  * by the {@link java.util.Formatter} class in {@link java.util}
@@ -46,8 +52,23 @@
         }
     }
 
+    /* Wraps the source string in bidi formatting characters in RTL locales */
+    private static String bidiWrap(@NonNull Context context, String source) {
+        final Locale locale = context.getResources().getConfiguration().locale;
+        if (TextUtils.getLayoutDirectionFromLocale(locale) == View.LAYOUT_DIRECTION_RTL) {
+            return BidiFormatter.getInstance(true /* RTL*/).unicodeWrap(source);
+        } else {
+            return source;
+        }
+    }
+
     /**
-     * Formats a content size to be in the form of bytes, kilobytes, megabytes, etc
+     * Formats a content size to be in the form of bytes, kilobytes, megabytes, etc.
+     *
+     * If the context has a right-to-left locale, the returned string is wrapped in bidi formatting
+     * characters to make sure it's displayed correctly if inserted inside a right-to-left string.
+     * (This is useful in cases where the unit strings, like "MB", are left-to-right, but the
+     * locale is right-to-left.)
      *
      * @param context Context to use to load the localized units
      * @param sizeBytes size value to be formatted, in bytes
@@ -58,8 +79,8 @@
             return "";
         }
         final BytesResult res = formatBytes(context.getResources(), sizeBytes, 0);
-        return context.getString(com.android.internal.R.string.fileSizeSuffix,
-                res.value, res.units);
+        return bidiWrap(context, context.getString(com.android.internal.R.string.fileSizeSuffix,
+                res.value, res.units));
     }
 
     /**
@@ -71,8 +92,8 @@
             return "";
         }
         final BytesResult res = formatBytes(context.getResources(), sizeBytes, FLAG_SHORTER);
-        return context.getString(com.android.internal.R.string.fileSizeSuffix,
-                res.value, res.units);
+        return bidiWrap(context, context.getString(com.android.internal.R.string.fileSizeSuffix,
+                res.value, res.units));
     }
 
     /** {@hide} */
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index b2b98db..ed858e7 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -1556,13 +1556,6 @@
         if (accessibilityId == getAccessibilityViewId()) {
             return this;
         }
-        // If the data changed the children are invalid since the data model changed.
-        // Hence, we pretend they do not exist. After a layout the children will sync
-        // with the model at which point we notify that the accessibility state changed,
-        // so a service will be able to re-fetch the views.
-        if (mDataChanged) {
-            return null;
-        }
         return super.findViewByAccessibilityIdTraversal(accessibilityId);
     }
 
@@ -2409,18 +2402,6 @@
 
     class ListItemAccessibilityDelegate extends AccessibilityDelegate {
         @Override
-        public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) {
-            // If the data changed the children are invalid since the data model changed.
-            // Hence, we pretend they do not exist. After a layout the children will sync
-            // with the model at which point we notify that the accessibility state changed,
-            // so a service will be able to re-fetch the views.
-            if (mDataChanged) {
-                return null;
-            }
-            return super.createAccessibilityNodeInfo(host);
-        }
-
-        @Override
         public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
             super.onInitializeAccessibilityNodeInfo(host, info);
 
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index d897f49..15d13ae 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -3225,7 +3225,8 @@
         }
 
         private void updateReplaceItem(Menu menu) {
-            boolean canReplace = mTextView.isSuggestionsEnabled() && shouldOfferToShowSuggestions();
+            boolean canReplace = mTextView.isSuggestionsEnabled() && shouldOfferToShowSuggestions()
+                    && !(mTextView.isInExtractedMode() && mTextView.hasSelection());
             boolean replaceItemExists = menu.findItem(TextView.ID_REPLACE) != null;
             if (canReplace && !replaceItemExists) {
                 menu.add(Menu.NONE, TextView.ID_REPLACE, MENU_ITEM_ORDER_REPLACE,
diff --git a/core/java/android/widget/RelativeLayout.java b/core/java/android/widget/RelativeLayout.java
index dac02fa..6a561e6 100644
--- a/core/java/android/widget/RelativeLayout.java
+++ b/core/java/android/widget/RelativeLayout.java
@@ -731,7 +731,8 @@
         // Negative values in a mySize value in RelativeLayout
         // measurement is code for, "we got an unspecified mode in the
         // RelativeLayout's measure spec."
-        if (mySize < 0 && !mAllowBrokenMeasureSpecs) {
+        final boolean isUnspecified = mySize < 0;
+        if (isUnspecified && !mAllowBrokenMeasureSpecs) {
             if (childStart != VALUE_NOT_SET && childEnd != VALUE_NOT_SET) {
                 // Constraints fixed both edges, so child has an exact size.
                 childSpecSize = Math.max(0, childEnd - childStart);
@@ -767,7 +768,7 @@
 
         if (childStart != VALUE_NOT_SET && childEnd != VALUE_NOT_SET) {
             // Constraints fixed both edges, so child must be an exact size.
-            childSpecMode = MeasureSpec.EXACTLY;
+            childSpecMode = isUnspecified ? MeasureSpec.UNSPECIFIED : MeasureSpec.EXACTLY;
             childSpecSize = Math.max(0, maxAvailable);
         } else {
             if (childSize >= 0) {
@@ -784,7 +785,7 @@
             } else if (childSize == LayoutParams.MATCH_PARENT) {
                 // Child wanted to be as big as possible. Give all available
                 // space.
-                childSpecMode = MeasureSpec.EXACTLY;
+                childSpecMode = isUnspecified ? MeasureSpec.UNSPECIFIED : MeasureSpec.EXACTLY;
                 childSpecSize = Math.max(0, maxAvailable);
             } else if (childSize == LayoutParams.WRAP_CONTENT) {
                 // Child wants to wrap content. Use AT_MOST to communicate
diff --git a/core/java/android/widget/SimpleMonthView.java b/core/java/android/widget/SimpleMonthView.java
index acf1df9..6e04eac 100644
--- a/core/java/android/widget/SimpleMonthView.java
+++ b/core/java/android/widget/SimpleMonthView.java
@@ -42,6 +42,7 @@
 import com.android.internal.R;
 import com.android.internal.widget.ExploreByTouchHelper;
 
+import java.text.NumberFormat;
 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.Locale;
@@ -73,6 +74,7 @@
 
     private final SimpleDateFormat mTitleFormatter;
     private final SimpleDateFormat mDayOfWeekFormatter;
+    private final NumberFormat mDayFormatter;
 
     // Desired dimensions.
     private final int mDesiredMonthHeight;
@@ -162,6 +164,7 @@
         final String titleFormat = DateFormat.getBestDateTimePattern(locale, DEFAULT_TITLE_FORMAT);
         mTitleFormatter = new SimpleDateFormat(titleFormat, locale);
         mDayOfWeekFormatter = new SimpleDateFormat(DAY_OF_WEEK_FORMAT, locale);
+        mDayFormatter = NumberFormat.getIntegerInstance(locale);
 
         initPaints(res);
     }
@@ -454,7 +457,7 @@
             }
             p.setColor(dayTextColor);
 
-            canvas.drawText(Integer.toString(day), colCenterRtl, rowCenter - halfLineHeight, p);
+            canvas.drawText(mDayFormatter.format(day), colCenterRtl, rowCenter - halfLineHeight, p);
 
             col++;
 
@@ -866,7 +869,7 @@
          */
         private CharSequence getDayText(int id) {
             if (isValidDayOfMonth(id)) {
-                return Integer.toString(id);
+                return mDayFormatter.format(id);
             }
 
             return null;
diff --git a/core/java/com/android/internal/app/AssistUtils.java b/core/java/com/android/internal/app/AssistUtils.java
index 6ba09c9..d552e54 100644
--- a/core/java/com/android/internal/app/AssistUtils.java
+++ b/core/java/com/android/internal/app/AssistUtils.java
@@ -23,6 +23,7 @@
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.os.Bundle;
+import android.os.IBinder;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.provider.Settings;
@@ -45,18 +46,24 @@
                 ServiceManager.getService(Context.VOICE_INTERACTION_MANAGER_SERVICE));
     }
 
-    public void showSessionForActiveService(Bundle args,
-            IVoiceInteractionSessionShowCallback showCallback) {
+    public boolean showSessionForActiveService(Bundle args, int sourceFlags,
+            IVoiceInteractionSessionShowCallback showCallback, IBinder activityToken) {
         try {
-            mVoiceInteractionManagerService.showSessionForActiveService(args, showCallback);
+            if (mVoiceInteractionManagerService != null) {
+                return mVoiceInteractionManagerService.showSessionForActiveService(args,
+                        sourceFlags, showCallback, activityToken);
+            }
         } catch (RemoteException e) {
             Log.w(TAG, "Failed to call showSessionForActiveService", e);
         }
+        return false;
     }
 
     public void launchVoiceAssistFromKeyguard() {
         try {
-            mVoiceInteractionManagerService.launchVoiceAssistFromKeyguard();
+            if (mVoiceInteractionManagerService != null) {
+                mVoiceInteractionManagerService.launchVoiceAssistFromKeyguard();
+            }
         } catch (RemoteException e) {
             Log.w(TAG, "Failed to call launchVoiceAssistFromKeyguard", e);
         }
@@ -84,7 +91,11 @@
 
     public ComponentName getActiveServiceComponentName() {
         try {
-            return mVoiceInteractionManagerService.getActiveServiceComponentName();
+            if (mVoiceInteractionManagerService != null) {
+                return mVoiceInteractionManagerService.getActiveServiceComponentName();
+            } else {
+                return null;
+            }
         } catch (RemoteException e) {
             Log.w(TAG, "Failed to call getActiveServiceComponentName", e);
             return null;
@@ -103,12 +114,24 @@
 
     public void hideCurrentSession() {
         try {
-            mVoiceInteractionManagerService.hideCurrentSession();
+            if (mVoiceInteractionManagerService != null) {
+                mVoiceInteractionManagerService.hideCurrentSession();
+            }
         } catch (RemoteException e) {
             Log.w(TAG, "Failed to call hideCurrentSession", e);
         }
     }
 
+    public void onLockscreenShown() {
+        try {
+            if (mVoiceInteractionManagerService != null) {
+                mVoiceInteractionManagerService.onLockscreenShown();
+            }
+        } catch (RemoteException e) {
+            Log.w(TAG, "Failed to call onLockscreenShown", e);
+        }
+    }
+
     public ComponentName getAssistComponentForUser(int userId) {
         final String setting = Settings.Secure.getStringForUser(mContext.getContentResolver(),
                 Settings.Secure.ASSISTANT, userId);
diff --git a/core/java/com/android/internal/app/ChooserActivity.java b/core/java/com/android/internal/app/ChooserActivity.java
index c4f57c7..6af2e8b 100644
--- a/core/java/com/android/internal/app/ChooserActivity.java
+++ b/core/java/com/android/internal/app/ChooserActivity.java
@@ -471,6 +471,36 @@
         return false;
     }
 
+    void filterServiceTargets(String packageName, List<ChooserTarget> targets) {
+        if (targets == null) {
+            return;
+        }
+
+        final PackageManager pm = getPackageManager();
+        for (int i = targets.size() - 1; i >= 0; i--) {
+            final ChooserTarget target = targets.get(i);
+            final ComponentName targetName = target.getComponentName();
+            if (packageName != null && packageName.equals(targetName.getPackageName())) {
+                // Anything from the original target's package is fine.
+                continue;
+            }
+
+            boolean remove;
+            try {
+                final ActivityInfo ai = pm.getActivityInfo(targetName, 0);
+                remove = !ai.exported || ai.permission != null;
+            } catch (NameNotFoundException e) {
+                Log.e(TAG, "Target " + target + " returned by " + packageName
+                        + " component not found");
+                remove = true;
+            }
+
+            if (remove) {
+                targets.remove(i);
+            }
+        }
+    }
+
     @Override
     ResolveListAdapter createAdapter(Context context, List<Intent> payloadIntents,
             Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid,
@@ -554,11 +584,11 @@
             return null;
         }
 
-        private Intent getFillInIntent() {
+        private Intent getBaseIntentToSend() {
             Intent result = mSourceInfo != null
                     ? mSourceInfo.getResolvedIntent() : getTargetIntent();
             if (result == null) {
-                Log.e(TAG, "ChooserTargetInfo#getFillInIntent: no fillIn intent available");
+                Log.e(TAG, "ChooserTargetInfo: no base intent available to send");
             } else {
                 result = new Intent(result);
                 if (mFillInIntent != null) {
@@ -571,31 +601,24 @@
 
         @Override
         public boolean start(Activity activity, Bundle options) {
-            final Intent intent = getFillInIntent();
-            if (intent == null) {
-                return false;
-            }
-            return mChooserTarget.sendIntent(activity, intent);
+            throw new RuntimeException("ChooserTargets should be started as caller.");
         }
 
         @Override
         public boolean startAsCaller(Activity activity, Bundle options, int userId) {
-            final Intent intent = getFillInIntent();
+            final Intent intent = getBaseIntentToSend();
             if (intent == null) {
                 return false;
             }
-            // ChooserTargets will launch with their IntentSender's identity
-            return mChooserTarget.sendIntent(activity, intent);
+            intent.setComponent(mChooserTarget.getComponentName());
+            intent.putExtras(mChooserTarget.getIntentExtras());
+            activity.startActivityAsCaller(intent, options, true, userId);
+            return true;
         }
 
         @Override
         public boolean startAsUser(Activity activity, Bundle options, UserHandle user) {
-            final Intent intent = getFillInIntent();
-            if (intent == null) {
-                return false;
-            }
-            // ChooserTargets will launch with their IntentSender's identity
-            return mChooserTarget.sendIntent(activity, intent);
+            throw new RuntimeException("ChooserTargets should be started as caller.");
         }
 
         @Override
@@ -998,6 +1021,8 @@
         private final IChooserTargetResult mChooserTargetResult = new IChooserTargetResult.Stub() {
             @Override
             public void sendResult(List<ChooserTarget> targets) throws RemoteException {
+                filterServiceTargets(mOriginalTarget.getResolveInfo().activityInfo.packageName,
+                        targets);
                 final Message msg = Message.obtain();
                 msg.what = CHOOSER_TARGET_SERVICE_RESULT;
                 msg.obj = new ServiceResultInfo(mOriginalTarget, targets,
diff --git a/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl b/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
index 7f54f50..1a963f3 100644
--- a/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
+++ b/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
@@ -37,6 +37,9 @@
     void setKeepAwake(IBinder token, boolean keepAwake);
     void closeSystemDialogs(IBinder token);
     void finish(IBinder token);
+    void setDisabledShowContext(int flags);
+    int getDisabledShowContext();
+    int getUserDisabledShowContext();
 
     /**
      * Gets the registered Sound model for keyphrase detection for the current user.
@@ -94,10 +97,12 @@
      * affordances.
      *
      * @param args the bundle to pass as arguments to the voice interaction session
-     * @param showCallback callback to be notified when the session was shown
+     * @param sourceFlags flags indicating the source of this show
+     * @param showCallback optional callback to be notified when the session was shown
+     * @param activityToken optional token of activity that needs to be on top
      */
-    void showSessionForActiveService(in Bundle args,
-            IVoiceInteractionSessionShowCallback showCallback);
+    boolean showSessionForActiveService(in Bundle args, int sourceFlags,
+            IVoiceInteractionSessionShowCallback showCallback, IBinder activityToken);
 
     /**
      * Hides the session from the active service, if it is showing.
@@ -126,4 +131,9 @@
      * from the lockscreen.
      */
     boolean activeServiceSupportsLaunchFromKeyguard();
+
+    /**
+     * Called when the lockscreen got shown.
+     */
+    void onLockscreenShown();
 }
diff --git a/core/java/com/android/internal/app/IntentForwarderActivity.java b/core/java/com/android/internal/app/IntentForwarderActivity.java
index 233bee3..39b66aa 100644
--- a/core/java/com/android/internal/app/IntentForwarderActivity.java
+++ b/core/java/com/android/internal/app/IntentForwarderActivity.java
@@ -103,7 +103,7 @@
                     || ChooserActivity.class.getName().equals(ri.activityInfo.name));
 
             try {
-                startActivityAsCaller(newIntent, null, targetUserId);
+                startActivityAsCaller(newIntent, null, false, targetUserId);
             } catch (RuntimeException e) {
                 int launchedFromUid = -1;
                 String launchedFromPackage = "?";
diff --git a/core/java/com/android/internal/app/ResolverActivity.java b/core/java/com/android/internal/app/ResolverActivity.java
index 7bc18f3..1bf17e6 100644
--- a/core/java/com/android/internal/app/ResolverActivity.java
+++ b/core/java/com/android/internal/app/ResolverActivity.java
@@ -19,14 +19,11 @@
 import android.annotation.Nullable;
 import android.app.Activity;
 import android.app.ActivityThread;
-import android.app.VoiceInteractor;
 import android.app.VoiceInteractor.PickOptionRequest;
 import android.app.VoiceInteractor.PickOptionRequest.Option;
 import android.app.VoiceInteractor.Prompt;
-import android.app.VoiceInteractor.Request;
 import android.os.AsyncTask;
 import android.provider.Settings;
-import android.service.chooser.ChooserTarget;
 import android.text.TextUtils;
 import android.util.Slog;
 import android.widget.AbsListView;
@@ -973,7 +970,7 @@
 
         @Override
         public boolean startAsCaller(Activity activity, Bundle options, int userId) {
-            activity.startActivityAsCaller(mResolvedIntent, options, userId);
+            activity.startActivityAsCaller(mResolvedIntent, options, false, userId);
             return true;
         }
 
diff --git a/core/java/com/android/internal/app/ToolbarActionBar.java b/core/java/com/android/internal/app/ToolbarActionBar.java
index 2b162af..c1b184e 100644
--- a/core/java/com/android/internal/app/ToolbarActionBar.java
+++ b/core/java/com/android/internal/app/ToolbarActionBar.java
@@ -463,6 +463,18 @@
         return true;
     }
 
+    @Override
+    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
+        Menu menu = mDecorToolbar.getMenu();
+        if (menu != null) {
+            menu.performShortcut(keyCode, event, 0);
+        }
+        // This action bar always returns true for handling keyboard shortcuts.
+        // This will block the window from preparing a temporary panel to handle
+        // keyboard shortcuts.
+        return true;
+    }
+
     public void addOnMenuVisibilityListener(OnMenuVisibilityListener listener) {
         mMenuVisibilityListeners.add(listener);
     }
diff --git a/core/java/com/android/internal/logging/MetricsLogger.java b/core/java/com/android/internal/logging/MetricsLogger.java
index cbe535f..91ae27b 100644
--- a/core/java/com/android/internal/logging/MetricsLogger.java
+++ b/core/java/com/android/internal/logging/MetricsLogger.java
@@ -27,7 +27,20 @@
  */
 public class MetricsLogger implements MetricsConstants {
     // Temporary constants go here, to await migration to MetricsConstants.
-    // next value is 227;
+    // next value is 238;
+
+    public static final int TUNER = 227;
+    public static final int TUNER_QS = 228;
+    public static final int TUNER_DEMO_MODE = 229;
+
+    public static final int TUNER_QS_REORDER = 230;
+    public static final int TUNER_QS_ADD = 231;
+    public static final int TUNER_QS_REMOVE = 232;
+    public static final int TUNER_STATUS_BAR_ENABLE = 233;
+    public static final int TUNER_STATUS_BAR_DISABLE = 234;
+    public static final int TUNER_DEMO_MODE_ENABLED = 235;
+    public static final int TUNER_DEMO_MODE_ON = 236;
+    public static final int TUNER_BATTERY_PERCENTAGE = 237;
 
     public static void visible(Context context, int category) throws IllegalArgumentException {
         if (Build.IS_DEBUGGABLE && category == VIEW_UNKNOWN) {
diff --git a/core/java/com/android/internal/os/KernelWakelockReader.java b/core/java/com/android/internal/os/KernelWakelockReader.java
index 768d586..0369c3f 100644
--- a/core/java/com/android/internal/os/KernelWakelockReader.java
+++ b/core/java/com/android/internal/os/KernelWakelockReader.java
@@ -68,12 +68,12 @@
         try {
             FileInputStream is;
             try {
-                is = new FileInputStream(sWakeupSourceFile);
-                wakeup_sources = true;
+                is = new FileInputStream(sWakelockFile);
+                wakeup_sources = false;
             } catch (java.io.FileNotFoundException e) {
                 try {
-                    is = new FileInputStream(sWakelockFile);
-                    wakeup_sources = false;
+                    is = new FileInputStream(sWakeupSourceFile);
+                    wakeup_sources = true;
                 } catch (java.io.FileNotFoundException e2) {
                     return null;
                 }
diff --git a/core/java/com/android/internal/os/SomeArgs.java b/core/java/com/android/internal/os/SomeArgs.java
index b0d24fd..c05e0d8 100644
--- a/core/java/com/android/internal/os/SomeArgs.java
+++ b/core/java/com/android/internal/os/SomeArgs.java
@@ -73,6 +73,16 @@
         }
     }
 
+    public void complete() {
+        synchronized (this) {
+            if (mWaitState != WAIT_WAITING) {
+                throw new IllegalStateException("Not waiting");
+            }
+            mWaitState = WAIT_FINISHED;
+            notifyAll();
+        }
+    }
+
     public void recycle() {
         if (mInPool) {
             throw new IllegalStateException("Already recycled.");
diff --git a/core/java/com/android/internal/policy/IKeyguardShowCallback.aidl b/core/java/com/android/internal/policy/IKeyguardDrawnCallback.aidl
similarity index 89%
rename from core/java/com/android/internal/policy/IKeyguardShowCallback.aidl
rename to core/java/com/android/internal/policy/IKeyguardDrawnCallback.aidl
index a2784d9..ef8478c 100644
--- a/core/java/com/android/internal/policy/IKeyguardShowCallback.aidl
+++ b/core/java/com/android/internal/policy/IKeyguardDrawnCallback.aidl
@@ -15,6 +15,6 @@
  */
 package com.android.internal.policy;
 
-oneway interface IKeyguardShowCallback {
-    void onShown(IBinder windowToken);
+oneway interface IKeyguardDrawnCallback {
+    void onDrawn();
 }
diff --git a/core/java/com/android/internal/policy/IKeyguardService.aidl b/core/java/com/android/internal/policy/IKeyguardService.aidl
index 7ab4651..79af452 100644
--- a/core/java/com/android/internal/policy/IKeyguardService.aidl
+++ b/core/java/com/android/internal/policy/IKeyguardService.aidl
@@ -15,7 +15,7 @@
  */
 package com.android.internal.policy;
 
-import com.android.internal.policy.IKeyguardShowCallback;
+import com.android.internal.policy.IKeyguardDrawnCallback;
 import com.android.internal.policy.IKeyguardStateCallback;
 import com.android.internal.policy.IKeyguardExitCallback;
 
@@ -57,7 +57,13 @@
     /**
      * Called when the device has started waking up.
      */
-    void onStartedWakingUp(IKeyguardShowCallback callback);
+    void onStartedWakingUp();
+
+    /**
+     * Called when the device screen is turning on.
+     */
+    void onScreenTurningOn(IKeyguardDrawnCallback callback);
+
     void setKeyguardEnabled(boolean enabled);
     void onSystemReady();
     void doKeyguardTimeout(in Bundle options);
diff --git a/core/java/com/android/internal/util/XmlUtils.java b/core/java/com/android/internal/util/XmlUtils.java
index 32746c2..6393fba 100644
--- a/core/java/com/android/internal/util/XmlUtils.java
+++ b/core/java/com/android/internal/util/XmlUtils.java
@@ -20,6 +20,7 @@
 import android.graphics.BitmapFactory;
 import android.graphics.Bitmap.CompressFormat;
 import android.net.Uri;
+import android.text.TextUtils;
 import android.util.ArrayMap;
 import android.util.Base64;
 import android.util.Xml;
@@ -45,6 +46,8 @@
 /** {@hide} */
 public class XmlUtils {
 
+    private static final String STRING_ARRAY_SEPARATOR = ":";
+
     public static void skipCurrentTag(XmlPullParser parser)
             throws XmlPullParserException, IOException {
         int outerDepth = parser.getDepth();
diff --git a/core/java/com/android/internal/widget/FloatingToolbar.java b/core/java/com/android/internal/widget/FloatingToolbar.java
index b3f688b..ca6fe61 100644
--- a/core/java/com/android/internal/widget/FloatingToolbar.java
+++ b/core/java/com/android/internal/widget/FloatingToolbar.java
@@ -285,7 +285,6 @@
 
         private final Context mContext;
         private final View mParent;
-        private final int[] mParentPositionOnScreen = new int[2];
         private final PopupWindow mPopupWindow;
         private final ViewGroup mContentContainer;
         private final int mMarginHorizontal;
@@ -339,7 +338,8 @@
         };
 
         private final Rect mViewPortOnScreen = new Rect();
-        private final Point mCoordsOnScreen = new Point();
+        private final Point mCoordsOnWindow = new Point();
+        private final int[] mTmpCoords = new int[2];
         private final Rect mTmpRect = new Rect();
 
         private final Region mTouchableRegion = new Region();
@@ -450,13 +450,11 @@
             }
             refreshCoordinatesAndOverflowDirection(contentRectOnScreen);
             preparePopupContent();
-            // We need to specify the offset relative to mParent.
+            // We need to specify the position in window coordinates.
             // TODO: Consider to use PopupWindow.setLayoutInScreenEnabled(true) so that we can
             // specify the popup poision in screen coordinates.
-            mParent.getLocationOnScreen(mParentPositionOnScreen);
-            final int relativeX = mCoordsOnScreen.x - mParentPositionOnScreen[0];
-            final int relativeY = mCoordsOnScreen.y - mParentPositionOnScreen[1];
-            mPopupWindow.showAtLocation(mParent, Gravity.NO_GRAVITY, relativeX, relativeY);
+            mPopupWindow.showAtLocation(mParent, Gravity.NO_GRAVITY, mCoordsOnWindow.x,
+                    mCoordsOnWindow.y);
             setTouchableSurfaceInsetsComputer();
             runShowAnimation();
         }
@@ -519,13 +517,10 @@
             cancelOverflowAnimations();
             refreshCoordinatesAndOverflowDirection(contentRectOnScreen);
             preparePopupContent();
-            // We need to specify the offset relative to mParent.
+            // We need to specify the position in window coordinates.
             // TODO: Consider to use PopupWindow.setLayoutInScreenEnabled(true) so that we can
             // specify the popup poision in screen coordinates.
-            mParent.getLocationOnScreen(mParentPositionOnScreen);
-            final int relativeX = mCoordsOnScreen.x - mParentPositionOnScreen[0];
-            final int relativeY = mCoordsOnScreen.y - mParentPositionOnScreen[1];
-            mPopupWindow.update(relativeX, relativeY, getWidth(), getHeight());
+            mPopupWindow.update(mCoordsOnWindow.x, mCoordsOnWindow.y, getWidth(), getHeight());
         }
 
         /**
@@ -624,7 +619,22 @@
                 mOverflowPanel.setOverflowDirection(mOverflowDirection);
             }
 
-            mCoordsOnScreen.set(x, y);
+            // We later specify the location of PopupWindow relative to the attached window.
+            // The idea here is that 1) we can get the location of a View in both window coordinates
+            // and screen coordiantes, where the offset between them should be equal to the window
+            // origin, and 2) we can use an arbitrary for this calculation while calculating the
+            // location of the rootview is supposed to be least expensive.
+            // TODO: Consider to use PopupWindow.setLayoutInScreenEnabled(true) so that we can avoid
+            // the following calculation.
+            mParent.getRootView().getLocationOnScreen(mTmpCoords);
+            int rootViewLeftOnScreen = mTmpCoords[0];
+            int rootViewTopOnScreen = mTmpCoords[1];
+            mParent.getRootView().getLocationInWindow(mTmpCoords);
+            int rootViewLeftOnWindow = mTmpCoords[0];
+            int rootViewTopOnWindow = mTmpCoords[1];
+            int windowLeftOnScreen = rootViewLeftOnScreen - rootViewLeftOnWindow;
+            int windowTopOnScreen = rootViewTopOnScreen - rootViewTopOnWindow;
+            mCoordsOnWindow.set(x - windowLeftOnScreen, y - windowTopOnScreen);
         }
 
         private int getToolbarHeightWithVerticalMargin() {
diff --git a/core/java/com/android/internal/widget/IRemoteViewsAdapterConnection.aidl b/core/java/com/android/internal/widget/IRemoteViewsAdapterConnection.aidl
index 7eb2aef..7294124 100644
--- a/core/java/com/android/internal/widget/IRemoteViewsAdapterConnection.aidl
+++ b/core/java/com/android/internal/widget/IRemoteViewsAdapterConnection.aidl
@@ -19,7 +19,7 @@
 import android.os.IBinder;
 
 /** {@hide} */
-interface IRemoteViewsAdapterConnection {
+oneway interface IRemoteViewsAdapterConnection {
     void onServiceConnected(IBinder service);
     void onServiceDisconnected();
 }
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 062ae27..92862f5 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -331,7 +331,7 @@
 
     <!-- Used for runtime permissions related to user's contacts and profile. -->
     <permission-group android:name="android.permission-group.CONTACTS"
-        android:icon="@drawable/perm_group_social_info"
+        android:icon="@drawable/perm_group_contacts"
         android:label="@string/permgrouplab_contacts"
         android:description="@string/permgroupdesc_contacts"
         android:priority="100" />
@@ -391,7 +391,7 @@
 
     <!-- Used for runtime permissions related to user's SMS messages. -->
     <permission-group android:name="android.permission-group.SMS"
-        android:icon="@drawable/perm_group_messages"
+        android:icon="@drawable/perm_group_sms"
         android:label="@string/permgrouplab_sms"
         android:description="@string/permgroupdesc_sms"
         android:priority="300" />
@@ -729,6 +729,7 @@
     <!-- Used for permissions that are associated with accessing
          camera or capturing images/video from the device. -->
     <permission-group android:name="android.permission-group.SENSORS"
+        android:icon="@drawable/perm_group_sensors"
         android:label="@string/permgrouplab_sensors"
         android:description="@string/permgroupdesc_sensors"
         android:priority="800" />
@@ -1535,7 +1536,9 @@
     <permission android:name="android.permission.CHANGE_CONFIGURATION"
         android:protectionLevel="signature|privileged|development" />
 
-    <!-- Allows an application to read or write the system settings. -->
+    <!-- Allows an application to read or write the system settings.
+         <p>Protection level: signature
+    -->
     <permission android:name="android.permission.WRITE_SETTINGS"
         android:label="@string/permlab_writeSettings"
         android:description="@string/permdesc_writeSettings"
@@ -2052,10 +2055,24 @@
     <permission android:name="android.permission.CHANGE_COMPONENT_ENABLED_STATE"
         android:protectionLevel="signature|privileged" />
 
-    <!-- @hide Allows an application to grant or revoke specific permissions. -->
-    <permission android:name="android.permission.GRANT_REVOKE_PERMISSIONS"
+    <!-- Allows an application to grant specific permissions.
+         @hide -->
+    <permission android:name="android.permission.GRANT_RUNTIME_PERMISSIONS"
         android:protectionLevel="signature|installer" />
 
+    <!-- Allows an app that has this permission and the permissions to install packages
+         to request certain runtime permissions to be granted at installation.
+         @hide
+         @SystemApi -->
+    <permission android:name="android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS"
+        android:protectionLevel="signature|installer|verifier" />
+
+    <!-- Allows an application to revoke specific permissions.
+        @hide
+        @SystemApi -->
+    <permission android:name="android.permission.REVOKE_RUNTIME_PERMISSIONS"
+         android:protectionLevel="signature|installer|verifier" />
+
     <!-- @hide Allows an application to observe permission changes. -->
     <permission android:name="android.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS"
         android:protectionLevel="signature|privileged" />
@@ -2539,12 +2556,6 @@
     <permission android:name="android.permission.ACCESS_VOICE_INTERACTION_SERVICE"
         android:protectionLevel="signature" />
 
-    <!-- Allows an app that has this permission and a permissions to install packages
-         to request all runtime permissions to be granted at installation.
-     @hide -->
-    <permission android:name="android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS"
-        android:protectionLevel="signature" />
-
     <!-- The system process that is allowed to bind to services in carrier apps will
          have this permission. Carrier apps should use this permission to protect
          their services that only the system is allowed to bind to.
diff --git a/core/res/res/drawable/ic_more_items.xml b/core/res/res/drawable/ic_more_items.xml
new file mode 100644
index 0000000..5fdcdce
--- /dev/null
+++ b/core/res/res/drawable/ic_more_items.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+    Copyright (C) 2015 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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:fillColor="#000000"
+        android:pathData="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7
+7v2h14V7H7z" />
+    <path
+        android:pathData="M0 0h24v24H0z" />
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/perm_group_calendar.xml b/core/res/res/drawable/perm_group_calendar.xml
index a0f9dd2..4dc7b37 100644
--- a/core/res/res/drawable/perm_group_calendar.xml
+++ b/core/res/res/drawable/perm_group_calendar.xml
@@ -1,3 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
 <!--
     Copyright (C) 2015 The Android Open Source Project
 
@@ -14,11 +15,15 @@
     limitations under the License.
 -->
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="48.0"
-        android:viewportHeight="48.0">
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
     <path
-        android:fillColor="#FF000000"
-        android:pathData="M34.0,24.0L24.0,24.0l0.0,10.0l10.0,0.0L34.0,24.0zM32.0,2.0l0.0,4.0L16.0,6.0L16.0,2.0l-4.0,0.0l0.0,4.0l-2.0,0.0c-2.21,0.0 -3.98,1.79 -3.98,4.0L6.0,38.0c0.0,2.21 1.79,4.0 4.0,4.0l28.0,0.0c2.21,0.0 4.0,-1.79 4.0,-4.0L42.0,10.0c0.0,-2.21 -1.79,-4.0 -4.0,-4.0l-2.0,0.0L36.0,2.0l-4.0,0.0zm6.0,36.0L10.0,38.0L10.0,16.0l28.0,0.0l0.0,22.0z"/>
-</vector>
+        android:fillColor="#000000"
+        android:pathData="M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.11 0-1.99 .9 -1.99 2L3 19c0 1.1 .89 2 2
+2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 18H5V8h14v11z" />
+    <path
+        android:pathData="M0 0h24v24H0z" />
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/perm_group_camera.xml b/core/res/res/drawable/perm_group_camera.xml
index 30d31ce..741a40e 100644
--- a/core/res/res/drawable/perm_group_camera.xml
+++ b/core/res/res/drawable/perm_group_camera.xml
@@ -1,3 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
 <!--
     Copyright (C) 2015 The Android Open Source Project
 
@@ -14,11 +15,19 @@
     limitations under the License.
 -->
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="48.0"
-        android:viewportHeight="48.0">
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
     <path
-        android:fillColor="#FF000000"
-        android:pathData="M18.8,21.0l9.53,-16.51C26.94,4.18 25.49,4.0 24.0,4.0c-4.8,0.0 -9.19,1.69 -12.64,4.51l7.33,12.6 0.11,-0.2zm24.28,-3.0c-1.84,-5.85 -6.3,-10.52 -11.99,-12.68L23.77,18.0l19.31,0.0zm0.52,2.0L28.62,20.0l0.58,1.0 9.53,16.5C41.99,33.94 44.0,29.21 44.0,24.0c0.0,-1.37 -0.14,-2.71 -0.4,-4.0zm-26.53,4.0l-7.8,-13.5C6.01,14.06 4.0,18.79 4.0,24.0c0.0,1.3 0.14,2.7 0.4,4.0l14.98,0.0l-2.31,-4.0zM4.92,30.0c1.84,5.85 6.3,10.52 11.99,12.68L24.23,30.0L4.92,30.0zm22.54,0.0l-7.8,13.51c1.0,0.31 2.8,0.49 4.3,0.49 4.8,0.0 9.19,-1.69 12.64,-4.51L29.31,26.8 27.46,30.0z"/>
-</vector>
+        android:fillColor="#000000"
+        android:pathData="M 12 8.8 C 13.7673111995 8.8 15.2 10.2326888005 15.2 12 C 15.2 13.7673111995 13.7673111995 15.2 12 15.2 C 10.2326888005 15.2 8.8 13.7673111995 8.8 12 C 8.8 10.2326888005 10.2326888005 8.8 12 8.8 Z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1 .9 2 2 2h16c1.1 0 2-.9
+2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5
+5-2.24 5-5 5z" />
+    <path
+        android:pathData="M0 0h24v24H0z" />
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/perm_group_contacts.xml b/core/res/res/drawable/perm_group_contacts.xml
new file mode 100644
index 0000000..d698fd1
--- /dev/null
+++ b/core/res/res/drawable/perm_group_contacts.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+    Copyright (C) 2015 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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:pathData="M0 0h24v24H0zm0 0h24v24H0zm0 0h24v24H0z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M20 0H4v2h16V0zM4 24h16v-2H4v2zM20 4H4c-1.1 0-2 .9-2 2v12c0 1.1 .9 2 2 2h16c1.1
+0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 2.75c1.24 0 2.25 1.01 2.25 2.25s-1.01 2.25-2.25
+2.25S9.75 10.24 9.75 9 10.76 6.75 12 6.75zM17 17H7v-1.5c0-1.67 3.33-2.5 5-2.5s5
+.83 5 2.5V17z" />
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/perm_group_location.xml b/core/res/res/drawable/perm_group_location.xml
index 4184cf9..fbc6066 100644
--- a/core/res/res/drawable/perm_group_location.xml
+++ b/core/res/res/drawable/perm_group_location.xml
@@ -1,3 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
 <!--
     Copyright (C) 2015 The Android Open Source Project
 
@@ -14,11 +15,15 @@
     limitations under the License.
 -->
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="48.0"
-        android:viewportHeight="48.0">
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
     <path
-        android:fillColor="#FF000000"
-        android:pathData="M24.0,16.0c-4.42,0.0 -8.0,3.58 -8.0,8.0s3.58,8.0 8.0,8.0 8.0,-3.58 8.0,-8.0 -3.58,-8.0 -8.0,-8.0zm17.88,6.0C40.96,13.66 34.34,7.04 26.0,6.12L26.0,2.0l-4.0,0.0l0.0,4.12C13.66,7.04 7.04,13.66 6.12,22.0L2.0,22.0l0.0,4.0l4.12,0.0c0.92,8.34 7.54,14.96 15.88,15.88L22.0,46.0l4.0,0.0l0.0,-4.12c8.34,-0.92 14.96,-7.54 15.88,-15.88L46.0,26.0l0.0,-4.0l-4.12,0.0zM24.0,38.0c-7.73,0.0 -14.0,-6.27 -14.0,-14.0s6.27,-14.0 14.0,-14.0 14.0,6.27 14.0,14.0 -6.27,14.0 -14.0,14.0z"/>
-</vector>
+        android:fillColor="#000000"
+        android:pathData="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0
+9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" />
+    <path
+        android:pathData="M0 0h24v24H0z" />
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/perm_group_messages.xml b/core/res/res/drawable/perm_group_messages.xml
deleted file mode 100644
index 4140e6c..0000000
--- a/core/res/res/drawable/perm_group_messages.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
-    Copyright (C) 2015 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="48.0"
-        android:viewportHeight="48.0">
-    <path
-        android:fillColor="#FF000000"
-        android:pathData="M40.0,4.0L8.0,4.0C5.79,4.0 4.02,5.79 4.02,8.0L4.0,44.0l8.0,-8.0l28.0,0.0c2.21,0.0 4.0,-1.79 4.0,-4.0L44.0,8.0c0.0,-2.21 -1.79,-4.0 -4.0,-4.0zm-4.0,24.0L12.0,28.0l0.0,-4.0l16.0,0.0l0.0,4.0zm0.0,-6.0L12.0,22.0l0.0,-4.0l24.0,0.0l0.0,4.0zm0.0,-6.0L12.0,16.0l0.0,-4.0l24.0,0.0l0.0,4.0z"/>
-</vector>
diff --git a/core/res/res/drawable/perm_group_microphone.xml b/core/res/res/drawable/perm_group_microphone.xml
index 670ef98..c565d20 100644
--- a/core/res/res/drawable/perm_group_microphone.xml
+++ b/core/res/res/drawable/perm_group_microphone.xml
@@ -1,3 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
 <!--
     Copyright (C) 2015 The Android Open Source Project
 
@@ -14,11 +15,16 @@
     limitations under the License.
 -->
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="48.0"
-        android:viewportHeight="48.0">
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
     <path
-        android:fillColor="#FF000000"
-        android:pathData="M24.0,28.0c3.31,0.0 5.98,-2.69 5.98,-6.0L30.0,10.0c0.0,-3.32 -2.68,-6.0 -6.0,-6.0 -3.31,0.0 -6.0,2.68 -6.0,6.0l0.0,12.0c0.0,3.31 2.69,6.0 6.0,6.0zm10.6,-6.0c0.0,6.0 -5.07,10.2 -10.6,10.2 -5.52,0.0 -10.6,-4.2 -10.6,-10.2L10.0,22c0.0,6.83 5.44,12.47 12.0,13.44L22.0,42.0l4.0,0.0l0.0,-6.56c6.56,-0.97 12.0,-6.61 12.0,-13.44l-3.4,0.0z"/>
-</vector>
+        android:fillColor="#000000"
+        android:pathData="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3
+3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6
+6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z" />
+    <path
+        android:pathData="M0 0h24v24H0z" />
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/perm_group_phone_calls.xml b/core/res/res/drawable/perm_group_phone_calls.xml
index 04ac6b9..a647894 100644
--- a/core/res/res/drawable/perm_group_phone_calls.xml
+++ b/core/res/res/drawable/perm_group_phone_calls.xml
@@ -1,3 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
 <!--
     Copyright (C) 2015 The Android Open Source Project
 
@@ -14,11 +15,17 @@
     limitations under the License.
 -->
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="48.0"
-        android:viewportHeight="48.0">
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
     <path
-        android:fillColor="#FF000000"
-        android:pathData="M13.25,21.59c2.88,5.66 7.51,10.29 13.18,13.17l4.4,-4.41c0.55,-0.55 1.34,-0.71 2.03,-0.49C35.1,30.6 37.51,31.0 40.0,31.0c1.11,0.0 2.0,0.89 2.0,2.0l0.0,7.0c0.0,1.11 -0.89,2.0 -2.0,2.0C21.22,42.0 6.0,26.78 6.0,8.0c0.0,-1.1 0.9,-2.0 2.0,-2.0l7.0,0.0c1.11,0.0 2.0,0.89 2.0,2.0 0.0,2.4 0.4,4.9 1.14,7.1 0.2,0.6 0.06,1.48 -0.49,2.03l-4.4,4.42z"/>
-</vector>
+        android:pathData="M0 0h24v24H0z" />
+    <path
+        android:fillColor="#000000"
+        android:pathData="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27 .67 -.36 1.02-.24 1.12
+.37 2.33 .57 3.57 .57 .55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17
+0-.55 .45 -1 1-1h3.5c.55 0 1 .45 1 1 0 1.25 .2 2.45 .57 3.57 .11 .35 .03 .74-.25
+1.02l-2.2 2.2z" />
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/perm_group_sensors.xml b/core/res/res/drawable/perm_group_sensors.xml
new file mode 100644
index 0000000..ce36c13
--- /dev/null
+++ b/core/res/res/drawable/perm_group_sensors.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+    Copyright (C) 2015 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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:fillColor="#000000"
+        android:pathData="M13.49 5.48c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-3.6 13.9l1-4.4 2.1
+2v6h2v-7.5l-2.1-2 .6-3c1.3 1.5 3.3 2.5 5.5 2.5v-2c-1.9
+0-3.5-1-4.3-2.4l-1-1.6c-.4-.6-1-1-1.7-1-.3 0-.5 .1 -.8 .1 l-5.2
+2.2v4.7h2v-3.4l1.8-.7-1.6 8.1-4.9-1-.4 2 7 1.4z" />
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/perm_group_sms.xml b/core/res/res/drawable/perm_group_sms.xml
new file mode 100644
index 0000000..9b32c601
--- /dev/null
+++ b/core/res/res/drawable/perm_group_sms.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+    Copyright (C) 2015 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.
+-->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
+    <path
+        android:fillColor="#000000"
+        android:pathData="M20 2H4c-1.1 0-1.99 .9 -1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM9
+11H7V9h2v2zm4 0h-2V9h2v2zm4 0h-2V9h2v2z" />
+    <path
+        android:pathData="M0 0h24v24H0z" />
+</vector>
\ No newline at end of file
diff --git a/core/res/res/drawable/perm_group_social_info.xml b/core/res/res/drawable/perm_group_social_info.xml
deleted file mode 100644
index f0f7a90..0000000
--- a/core/res/res/drawable/perm_group_social_info.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<!--
-    Copyright (C) 2015 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.
--->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24.0dp"
-        android:height="24.0dp"
-        android:viewportWidth="48.0"
-        android:viewportHeight="48.0">
-    <path
-        android:fillColor="#FF000000"
-        android:pathData="M32.0,22.0c3.31,0.0 5.98,-2.69 5.98,-6.0s-2.67,-6.0 -5.98,-6.0c-3.31,0.0 -6.0,2.69 -6.0,6.0s2.69,6.0 6.0,6.0zm-16.0,0.0c3.31,0.0 5.98,-2.69 5.98,-6.0s-2.67,-6.0 -5.98,-6.0c-3.31,0.0 -6.0,2.69 -6.0,6.0s2.69,6.0 6.0,6.0zm0.0,4.0c-4.67,0.0 -14.0,2.34 -14.0,7.0l0.0,5.0l28.0,0.0l0.0,-5.0c0.0,-4.66 -9.33,-7.0 -14.0,-7.0zm16.0,0.0c-0.58,0.0 -1.2,0.04 -1.9,0.11C32.39,27.78 34.0,30.03 34.0,33.0l0.0,5.0l12.0,0.0l0.0,-5.0c0.0,-4.66 -9.33,-7.0 -14.0,-7.0z"/>
-</vector>
diff --git a/core/res/res/drawable/perm_group_storage.xml b/core/res/res/drawable/perm_group_storage.xml
index 74f16d8..477270d 100644
--- a/core/res/res/drawable/perm_group_storage.xml
+++ b/core/res/res/drawable/perm_group_storage.xml
@@ -1,7 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
 <!--
-Copyright (C) 2015 The Android Open Source Project
+    Copyright (C) 2015 The Android Open Source Project
 
-   Licensed under the Apache License, Version 2.0 (the "License");
+    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
 
@@ -14,11 +15,15 @@
     limitations under the License.
 -->
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="24dp"
-        android:height="24dp"
-        android:viewportWidth="48.0"
-        android:viewportHeight="48.0">
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportWidth="24"
+    android:viewportHeight="24">
+
     <path
-        android:pathData="M20,8H8c-2.2,0 -4,1.8 -4,4l0,24c0,2.2 1.8,4 4,4h32c2.2,0 4,-1.8 4,-4V16c0,-2.2 -1.8,-4 -4,-4H24L20,8z"
-        android:fillColor="#FFFFFF"/>
-</vector>
+        android:fillColor="#000000"
+        android:pathData="M10 4H4c-1.1 0-1.99 .9 -1.99 2L2 18c0 1.1 .9 2 2 2h16c1.1 0 2-.9
+2-2V8c0-1.1-.9-2-2-2h-8l-2-2z" />
+    <path
+        android:pathData="M0 0h24v24H0z" />
+</vector>
\ No newline at end of file
diff --git a/core/res/res/layout/common_tab_settings.xml b/core/res/res/layout/common_tab_settings.xml
new file mode 100644
index 0000000..d2a4acc
--- /dev/null
+++ b/core/res/res/layout/common_tab_settings.xml
@@ -0,0 +1,60 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2014 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.
+-->
+
+<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@android:id/tabhost"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+    <LinearLayout
+        android:id="@+id/tabs_container"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:orientation="vertical">
+
+        <HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:scrollbars="none"
+            android:fillViewport="true">
+
+            <TabWidget
+                android:id="@android:id/tabs"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:orientation="horizontal"
+                style="?android:attr/tabWidgetStyle" />
+
+        </HorizontalScrollView>
+
+        <!-- give an empty content area to make tabhost happy -->
+        <FrameLayout
+            android:id="@android:id/tabcontent"
+            android:layout_width="0dip"
+            android:layout_height="0dip" />
+
+        <ListView
+            android:id="@android:id/list"
+            android:layout_width="match_parent"
+            android:layout_height="0dip"
+            android:layout_weight="1"
+            android:clipChildren="false"
+            android:clipToPadding="false"
+            android:smoothScrollbar="false" />
+
+    </LinearLayout>
+
+</TabHost>
diff --git a/core/res/res/layout/time_picker_header_material.xml b/core/res/res/layout/time_picker_header_material.xml
index 3f5e300..3c3a8a8 100644
--- a/core/res/res/layout/time_picker_header_material.xml
+++ b/core/res/res/layout/time_picker_header_material.xml
@@ -22,7 +22,9 @@
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                 android:orientation="horizontal"
-                android:padding="@dimen/timepicker_separator_padding">
+                android:padding="@dimen/timepicker_separator_padding"
+                android:paddingStart="16dp"
+                android:paddingEnd="16dp">
 
     <!-- The hour should always be to the left of the separator,
          regardless of the current locale's layout direction. -->
@@ -68,14 +70,14 @@
         android:layout_height="wrap_content"
         android:layout_toRightOf="@+id/minutes"
         android:layout_alignBaseline="@+id/minutes"
+        android:paddingStart="8dp"
+        android:paddingEnd="8dp"
         android:orientation="vertical"
         android:baselineAlignedChildIndex="1">
         <CheckedTextView
             android:id="@+id/am_label"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:paddingStart="@dimen/timepicker_ampm_horizontal_padding"
-            android:paddingEnd="@dimen/timepicker_ampm_horizontal_padding"
             android:paddingTop="@dimen/timepicker_am_top_padding"
             android:textAppearance="@style/TextAppearance.Material.TimePicker.AmPmLabel"
             android:lines="1"
@@ -84,8 +86,6 @@
             android:id="@+id/pm_label"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:paddingStart="@dimen/timepicker_ampm_horizontal_padding"
-            android:paddingEnd="@dimen/timepicker_ampm_horizontal_padding"
             android:paddingTop="@dimen/timepicker_pm_top_padding"
             android:textAppearance="@style/TextAppearance.Material.TimePicker.AmPmLabel"
             android:lines="1"
diff --git a/core/res/res/values-az-rAZ-watch/strings.xml b/core/res/res/values-az-rAZ-watch/strings.xml
new file mode 100644
index 0000000..7e4a762
--- /dev/null
+++ b/core/res/res/values-az-rAZ-watch/strings.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- 
+/* //device/apps/common/assets/res/any/strings.xml
+**
+** Copyright 2015, 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.
+*/
+ -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="android_upgrading_apk" msgid="1090732262010398759">"Tətbiq <xliff:g id="NUMBER_0">%1$d</xliff:g>/<xliff:g id="NUMBER_1">%2$d</xliff:g>."</string>
+</resources>
diff --git a/core/res/res/values-da/strings.xml b/core/res/res/values-da/strings.xml
index 9e22ff7..b5a01ed 100644
--- a/core/res/res/values-da/strings.xml
+++ b/core/res/res/values-da/strings.xml
@@ -354,8 +354,8 @@
     <string name="permdesc_flashlight" msgid="6522284794568368310">"Tillader, at appen kan kontrollere lommelygten."</string>
     <string name="permlab_callPhone" msgid="3925836347681847954">"ringe direkte op til telefonnumre"</string>
     <string name="permdesc_callPhone" msgid="3740797576113760827">"Tillader, at appen kan ringe til telefonnumre uden din indgriben. Dette kan resultere i uventede opkrævninger eller opkald. Bemærk, at appen med denne tilladelse ikke kan ringe til nødopkaldsnumre. Skadelige apps kan koste dig penge ved at foretage opkald uden din bekræftelse."</string>
-    <string name="permlab_accessImsCallService" msgid="3574943847181793918">"få adgang til IMS-opkaldstjeneste"</string>
-    <string name="permdesc_accessImsCallService" msgid="8992884015198298775">"Tillader, at appen kan bruge IMS-tjenesten til at foretage opkald, uden at du foretager dig noget."</string>
+    <string name="permlab_accessImsCallService" msgid="3574943847181793918">"få adgang til chat-opkaldstjeneste"</string>
+    <string name="permdesc_accessImsCallService" msgid="8992884015198298775">"Tillader, at appen kan bruge chat-tjenesten til at foretage opkald, uden du gør noget."</string>
     <string name="permlab_readPhoneState" msgid="9178228524507610486">"læse telefonens status og identitet"</string>
     <string name="permdesc_readPhoneState" msgid="1639212771826125528">"Tillader, at appen kan få adgang til telefonfunktionerne på enheden. Med denne tilladelse kan appen fastslå telefonnummeret og enheds-id\'erne, hvorvidt et opkald er aktivt samt det eksterne nummer, der oprettes forbindelse til via et opkald."</string>
     <string name="permlab_wakeLock" product="tablet" msgid="1531731435011495015">"afholde tabletcomputeren fra at gå i dvale"</string>
diff --git a/core/res/res/values-eu-rES/strings.xml b/core/res/res/values-eu-rES/strings.xml
index cc23637..93f7523 100644
--- a/core/res/res/values-eu-rES/strings.xml
+++ b/core/res/res/values-eu-rES/strings.xml
@@ -355,7 +355,7 @@
     <string name="permlab_callPhone" msgid="3925836347681847954">"deitu zuzenean telefono-zenbakietara"</string>
     <string name="permdesc_callPhone" msgid="3740797576113760827">"Telefono-zenbakietara zuk esku hartu gabe deitzeko baimena ematen die aplikazioei. Horrela, ustekabeko gastuak edo deiak eragin daitezke. Aplikazio gaiztoek erabil dezakete zuk berretsi gabeko deiak eginda gastuak eragiteko."</string>
     <string name="permlab_accessImsCallService" msgid="3574943847181793918">"Atzitu IMS dei-zerbitzua"</string>
-    <string name="permdesc_accessImsCallService" msgid="8992884015198298775">"Zuk ezer egin beharrik gabe deiak egiteko IMS zerbitzua erabiltzea baimentzen dio aplikazioari."</string>
+    <string name="permdesc_accessImsCallService" msgid="8992884015198298775">"Zuk ezer egin beharrik gabe deiak egiteko IMS zerbitzua erabiltzea baimentzen die aplikazioei."</string>
     <string name="permlab_readPhoneState" msgid="9178228524507610486">"telefonoaren egoera eta identitatea irakurtzea"</string>
     <string name="permdesc_readPhoneState" msgid="1639212771826125528">"Gailuaren telefono-eginbideak atzitzeko baimena ematen die aplikazioei. Baimen horrek aplikazioari telefono-zenbakia eta gailu IDak zein diren, deirik aktibo dagoen eta deia zer zenbakirekin konektatuta dagoen zehazteko baimena ematen die aplikazioei."</string>
     <string name="permlab_wakeLock" product="tablet" msgid="1531731435011495015">"eragotzi tableta inaktibo ezartzea"</string>
@@ -883,7 +883,7 @@
     <string name="whichViewApplicationNamed" msgid="2286418824011249620">"Irekin %1$s aplikazioarekin"</string>
     <string name="whichEditApplication" msgid="144727838241402655">"Editatu honekin:"</string>
     <string name="whichEditApplicationNamed" msgid="1775815530156447790">"Editatu %1$s aplikazioarekin"</string>
-    <string name="whichSendApplication" msgid="6902512414057341668">"Partekatu honekin:"</string>
+    <string name="whichSendApplication" msgid="6902512414057341668">"Partekatu hauen bidez:"</string>
     <string name="whichSendApplicationNamed" msgid="2799370240005424391">"Partekatu %1$s aplikazioarekin"</string>
     <string name="whichHomeApplication" msgid="4307587691506919691">"Hautatu hasierako aplikazioa"</string>
     <string name="whichHomeApplicationNamed" msgid="4493438593214760979">"Erabili %1$s hasierako aplikazio gisa"</string>
diff --git a/core/res/res/values-mcc310-mnc260-az-rAZ/strings.xml b/core/res/res/values-mcc310-mnc260-az-rAZ/strings.xml
new file mode 100644
index 0000000..32d21c5
--- /dev/null
+++ b/core/res/res/values-mcc310-mnc260-az-rAZ/strings.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- 
+/*
+** Copyright 2015, 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 my 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.
+*/
+ -->
+
+<!--  These resources are around just to allow their values to be customized
+     for different hardware and product builds.  -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+  <string-array name="wfcOperatorErrorAlertMessages">
+    <item msgid="7239039348648848288">"Wi-Fi üzərindən zəng etmək və mesaj göndərmək üçün ilk öncə operatordan bu xidməti ayarlamağı tələb edin. Sonra Ayarlardan Wi-Fi çağrısını aktivləşdirin."</item>
+  </string-array>
+  <string-array name="wfcOperatorErrorNotificationMessages">
+    <item msgid="483847327467331298">"Operatorla qeydiyyatdan keçin"</item>
+  </string-array>
+    <string name="wfcSpnFormat" msgid="4982938551498609442">"%s Wi-Fi Zəngi"</string>
+</resources>
diff --git a/core/res/res/values-mcc310-mnc260-de/strings.xml b/core/res/res/values-mcc310-mnc260-de/strings.xml
index f357bb6..3994bba 100644
--- a/core/res/res/values-mcc310-mnc260-de/strings.xml
+++ b/core/res/res/values-mcc310-mnc260-de/strings.xml
@@ -23,10 +23,10 @@
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
   <string-array name="wfcOperatorErrorAlertMessages">
-    <item msgid="7239039348648848288">"Um über WLAN Anrufe durchführen und Nachrichten senden zu können, bitten Sie zuerst Ihren Mobilfunkanbieter, diesen Dienst einzurichten. Aktivieren Sie WLAN-Anrufe dann erneut über die Einstellungen."</item>
+    <item msgid="7239039348648848288">"Um über WLAN telefonieren und Nachrichten senden zu können, bitten Sie zuerst Ihren Mobilfunkanbieter, diesen Dienst einzurichten. Aktivieren Sie die Option \"Anrufe über WLAN\" dann erneut über die Einstellungen."</item>
   </string-array>
   <string-array name="wfcOperatorErrorNotificationMessages">
     <item msgid="483847327467331298">"Registrieren Sie sich bei Ihrem Mobilfunkanbieter."</item>
   </string-array>
-    <string name="wfcSpnFormat" msgid="4982938551498609442">"%s WLAN-Anrufe"</string>
+    <string name="wfcSpnFormat" msgid="4982938551498609442">"%s Anrufe über WLAN"</string>
 </resources>
diff --git a/core/res/res/values-mcc310-mnc260-kn-rIN/strings.xml b/core/res/res/values-mcc310-mnc260-kn-rIN/strings.xml
index f24bed0..0a9d58d 100644
--- a/core/res/res/values-mcc310-mnc260-kn-rIN/strings.xml
+++ b/core/res/res/values-mcc310-mnc260-kn-rIN/strings.xml
@@ -23,10 +23,10 @@
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
   <string-array name="wfcOperatorErrorAlertMessages">
-    <item msgid="7239039348648848288">"ವೈ-ಫೈ ಬಳಸಿಕೊಂಡು ಕರೆ ಮಾಡಲು ಮತ್ತು ಸಂದೇಶಗಳನ್ನು ಕಳುಹಿಸಲು, ಮೊದಲು ಈ ಸಾಧನವನ್ನು ಹೊಂದಿಸಲು ನಿಮ್ಮ ವಾಹಕವನ್ನು ಕೇಳಿ. ತದನಂತರ ಸೆಟ್ಟಿಂಗ್‌ಗಳಲ್ಲಿ ಮತ್ತೆ ವೈ-ಫೈ ಆನ್‌ ಮಾಡಿ."</item>
+    <item msgid="7239039348648848288">"Wi-Fi ಬಳಸಿಕೊಂಡು ಕರೆ ಮಾಡಲು ಮತ್ತು ಸಂದೇಶಗಳನ್ನು ಕಳುಹಿಸಲು, ಮೊದಲು ಈ ಸಾಧನವನ್ನು ಹೊಂದಿಸಲು ನಿಮ್ಮ ವಾಹಕವನ್ನು ಕೇಳಿ. ತದನಂತರ ಸೆಟ್ಟಿಂಗ್‌ಗಳಲ್ಲಿ ಮತ್ತೆ Wi-Fi ಆನ್‌ ಮಾಡಿ."</item>
   </string-array>
   <string-array name="wfcOperatorErrorNotificationMessages">
     <item msgid="483847327467331298">"ನಿಮ್ಮ ವಾಹಕದಲ್ಲಿ ನೋಂದಾಯಿಸಿಕೊಳ್ಳಿ"</item>
   </string-array>
-    <string name="wfcSpnFormat" msgid="4982938551498609442">"%s ವೈ-ಫೈ ಕರೆ ಮಾಡುವಿಕೆ"</string>
+    <string name="wfcSpnFormat" msgid="4982938551498609442">"%s Wi-Fi ಕರೆ ಮಾಡುವಿಕೆ"</string>
 </resources>
diff --git a/core/res/res/values-mcc310-mnc260-ml-rIN/strings.xml b/core/res/res/values-mcc310-mnc260-ml-rIN/strings.xml
index 764b792..a94680d 100644
--- a/core/res/res/values-mcc310-mnc260-ml-rIN/strings.xml
+++ b/core/res/res/values-mcc310-mnc260-ml-rIN/strings.xml
@@ -23,10 +23,10 @@
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
   <string-array name="wfcOperatorErrorAlertMessages">
-    <item msgid="7239039348648848288">"Wi-Fi വഴി കോളുകൾ വിളിക്കാനും സന്ദേശങ്ങൾ അയയ്‌ക്കാനും ആദ്യം നിങ്ങളുടെ കാരിയറോട് ഈ സേവനം സജ്ജമാക്കാൻ ആവശ്യപ്പെടുക. ക്രമീകരണത്തിൽ നിന്ന് വീണ്ടും Wi-Fi കോളിംഗ് ഓണാക്കുക."</item>
+    <item msgid="7239039348648848288">"വൈഫൈ വഴി കോളുകൾ വിളിക്കാനും സന്ദേശങ്ങൾ അയയ്‌ക്കാനും ആദ്യം നിങ്ങളുടെ കാരിയറോട് ഈ സേവനം സജ്ജമാക്കാൻ ആവശ്യപ്പെടുക. ക്രമീകരണത്തിൽ നിന്ന് വീണ്ടും വൈഫൈ കോളിംഗ് ഓണാക്കുക."</item>
   </string-array>
   <string-array name="wfcOperatorErrorNotificationMessages">
     <item msgid="483847327467331298">"നിങ്ങളുടെ കാരിയറിൽ രജിസ്റ്റർ ചെയ്യുക"</item>
   </string-array>
-    <string name="wfcSpnFormat" msgid="4982938551498609442">"%s Wi-Fi കോളിംഗ്"</string>
+    <string name="wfcSpnFormat" msgid="4982938551498609442">"%s വൈഫൈ കോളിംഗ്"</string>
 </resources>
diff --git a/core/res/res/values-ml-rIN/strings.xml b/core/res/res/values-ml-rIN/strings.xml
index 8ccf2fb..a4c23ee 100644
--- a/core/res/res/values-ml-rIN/strings.xml
+++ b/core/res/res/values-ml-rIN/strings.xml
@@ -569,7 +569,7 @@
     <item msgid="1648797903785279353">"Jabber"</item>
   </string-array>
     <string name="phoneTypeCustom" msgid="1644738059053355820">"ഇഷ്‌ടാനുസൃതം"</string>
-    <string name="phoneTypeHome" msgid="2570923463033985887">"വീട്ടുനമ്പർ"</string>
+    <string name="phoneTypeHome" msgid="2570923463033985887">"വീട്"</string>
     <string name="phoneTypeMobile" msgid="6501463557754751037">"മൊബൈൽ"</string>
     <string name="phoneTypeWork" msgid="8863939667059911633">"ഔദ്യോഗിക നമ്പർ"</string>
     <string name="phoneTypeFaxWork" msgid="3517792160008890912">"ഔദ്യോഗിക ഫാക്‌സ്"</string>
@@ -999,7 +999,7 @@
     <string name="sms_short_code_confirm_deny" msgid="2927389840209170706">"റദ്ദാക്കുക"</string>
     <string name="sms_short_code_remember_choice" msgid="5289538592272218136">"എന്റെ ഇഷ്ടം ഓർമ്മിച്ചുവയ്ക്കുക"</string>
     <string name="sms_short_code_remember_undo_instruction" msgid="4960944133052287484">"നിങ്ങൾക്ക് ഇത് പിന്നീട് ക്രമീകരണങ്ങൾ &gt; അപ്ലിക്കേഷനുകൾ എന്നതിൽ മാറ്റാനാകും"</string>
-    <string name="sms_short_code_confirm_always_allow" msgid="3241181154869493368">"എല്ലായ്‌പ്പോഴും അനുവദിക്കുക"</string>
+    <string name="sms_short_code_confirm_always_allow" msgid="3241181154869493368">"എപ്പോഴും അനുവദിക്കൂ"</string>
     <string name="sms_short_code_confirm_never_allow" msgid="446992765774269673">"ഒരിക്കലുമനുവദിക്കരുത്"</string>
     <string name="sim_removed_title" msgid="6227712319223226185">"സിം കാർഡ് നീക്കംചെയ്‌തു"</string>
     <string name="sim_removed_message" msgid="5450336489923274918">"സാധുതയുള്ള ഒരു സിം കാർഡ് ചേർത്ത് പുനരാരംഭിക്കുന്നതുവരെ സെല്ലുലാർ നെറ്റ്‌വർക്ക് ലഭ്യമാകില്ല."</string>
diff --git a/core/res/res/values-pt-rBR/strings.xml b/core/res/res/values-pt-rBR/strings.xml
new file mode 100644
index 0000000..ffbe8d6
--- /dev/null
+++ b/core/res/res/values-pt-rBR/strings.xml
@@ -0,0 +1,1517 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- 
+/* //device/apps/common/assets/res/any/strings.xml
+**
+** Copyright 2006, 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.
+*/
+ -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <string name="byteShort" msgid="8340973892742019101">"B"</string>
+    <string name="kilobyteShort" msgid="5973789783504771878">"Kb"</string>
+    <string name="megabyteShort" msgid="6355851576770428922">"MB"</string>
+    <string name="gigabyteShort" msgid="3259882455212193214">"GB"</string>
+    <string name="terabyteShort" msgid="231613018159186962">"TB"</string>
+    <string name="petabyteShort" msgid="5637816680144990219">"PB"</string>
+    <string name="fileSizeSuffix" msgid="8897567456150907538">"<xliff:g id="NUMBER">%1$s</xliff:g> <xliff:g id="UNIT">%2$s</xliff:g>"</string>
+    <string name="durationDays" msgid="6652371460511178259">"<xliff:g id="DAYS">%1$d</xliff:g> dias"</string>
+    <string name="durationDayHours" msgid="2713107458736744435">"<xliff:g id="DAYS">%1$d</xliff:g> dia <xliff:g id="HOURS">%2$d</xliff:g> h"</string>
+    <string name="durationDayHour" msgid="7293789639090958917">"<xliff:g id="DAYS">%1$d</xliff:g> dia <xliff:g id="HOURS">%2$d</xliff:g> h"</string>
+    <string name="durationHours" msgid="4266858287167358988">"<xliff:g id="HOURS">%1$d</xliff:g> h"</string>
+    <string name="durationHourMinutes" msgid="9029176248692041549">"<xliff:g id="HOURS">%1$d</xliff:g> h <xliff:g id="MINUTES">%2$d</xliff:g> min"</string>
+    <string name="durationHourMinute" msgid="2741677355177402539">"<xliff:g id="HOURS">%1$d</xliff:g> h <xliff:g id="MINUTES">%2$d</xliff:g> min"</string>
+    <string name="durationMinutes" msgid="3134226679883579347">"<xliff:g id="MINUTES">%1$d</xliff:g> min"</string>
+    <string name="durationMinute" msgid="7155301744174623818">"<xliff:g id="MINUTES">%1$d</xliff:g> m"</string>
+    <string name="durationMinuteSeconds" msgid="1424656185379003751">"<xliff:g id="MINUTES">%1$d</xliff:g> min <xliff:g id="SECONDS">%2$d</xliff:g> s"</string>
+    <string name="durationMinuteSecond" msgid="3989228718067466680">"<xliff:g id="MINUTES">%1$d</xliff:g> min <xliff:g id="SECONDS">%2$d</xliff:g> s"</string>
+    <string name="durationSeconds" msgid="8050088505238241405">"<xliff:g id="SECONDS">%1$d</xliff:g> s"</string>
+    <string name="durationSecond" msgid="985669622276420331">"<xliff:g id="SECONDS">%1$d</xliff:g> s"</string>
+    <string name="untitled" msgid="4638956954852782576">"&lt;Sem título&gt;"</string>
+    <string name="emptyPhoneNumber" msgid="7694063042079676517">"(Nenhum número de telefone)"</string>
+    <string name="unknownName" msgid="6867811765370350269">"Desconhecido"</string>
+    <string name="defaultVoiceMailAlphaTag" msgid="2660020990097733077">"Correio de voz"</string>
+    <string name="defaultMsisdnAlphaTag" msgid="2850889754919584674">"MSISDN1"</string>
+    <string name="mmiError" msgid="5154499457739052907">"Problema de conexão ou código MMI inválido."</string>
+    <string name="mmiFdnError" msgid="5224398216385316471">"A operação é limitada somente a números de chamadas fixas."</string>
+    <string name="serviceEnabled" msgid="8147278346414714315">"O serviço foi ativado."</string>
+    <string name="serviceEnabledFor" msgid="6856228140453471041">"O serviço foi ativado para:"</string>
+    <string name="serviceDisabled" msgid="1937553226592516411">"O serviço foi desativado."</string>
+    <string name="serviceRegistered" msgid="6275019082598102493">"Registro bem-sucedido."</string>
+    <string name="serviceErased" msgid="1288584695297200972">"Exclusão bem-sucedida."</string>
+    <string name="passwordIncorrect" msgid="7612208839450128715">"Senha incorreta."</string>
+    <string name="mmiComplete" msgid="8232527495411698359">"MMI concluído."</string>
+    <string name="badPin" msgid="9015277645546710014">"O PIN antigo digitado está incorreto."</string>
+    <string name="badPuk" msgid="5487257647081132201">"O PUK digitado está incorreto."</string>
+    <string name="mismatchPin" msgid="609379054496863419">"Os PINs digitados não correspondem."</string>
+    <string name="invalidPin" msgid="3850018445187475377">"Digite um PIN com 4 a 8 números."</string>
+    <string name="invalidPuk" msgid="8761456210898036513">"Digite um PUK com oito números ou mais."</string>
+    <string name="needPuk" msgid="919668385956251611">"O seu cartão SIM está bloqueado por um PUK. Digite o código PUK para desbloqueá-lo."</string>
+    <string name="needPuk2" msgid="4526033371987193070">"Digite o PUK2 para desbloquear o cartão SIM."</string>
+    <string name="enablePin" msgid="209412020907207950">"Falha. Ative o bloqueio do SIM/R-UIM."</string>
+    <plurals name="pinpuk_attempts" formatted="false" msgid="1251012001539225582">
+      <item quantity="one">Tentativas restantes: <xliff:g id="NUMBER_1">%d</xliff:g>. Caso o código correto não seja digitado, o SIM será bloqueado.</item>
+      <item quantity="other">Tentativas restantes: <xliff:g id="NUMBER_1">%d</xliff:g>. Caso o código correto não seja digitado, o SIM será bloqueado.</item>
+    </plurals>
+    <string name="imei" msgid="2625429890869005782">"IMEI"</string>
+    <string name="meid" msgid="4841221237681254195">"MEID"</string>
+    <string name="ClipMmi" msgid="6952821216480289285">"ID do chamador de entrada"</string>
+    <string name="ClirMmi" msgid="7784673673446833091">"ID do chamador de saída"</string>
+    <string name="ColpMmi" msgid="3065121483740183974">"ID de linha conectada"</string>
+    <string name="ColrMmi" msgid="4996540314421889589">"Restrição de ID de linha conectada"</string>
+    <string name="CfMmi" msgid="5123218989141573515">"Encaminhamento de chamada"</string>
+    <string name="CwMmi" msgid="9129678056795016867">"Chamada em espera"</string>
+    <string name="BaMmi" msgid="455193067926770581">"Bloqueio de chamadas"</string>
+    <string name="PwdMmi" msgid="7043715687905254199">"Alteração da senha"</string>
+    <string name="PinMmi" msgid="3113117780361190304">"Alteração do PIN"</string>
+    <string name="CnipMmi" msgid="3110534680557857162">"Chamando número atual"</string>
+    <string name="CnirMmi" msgid="3062102121430548731">"Chamando número restrito"</string>
+    <string name="ThreeWCMmi" msgid="9051047170321190368">"Chamada com três participantes"</string>
+    <string name="RuacMmi" msgid="7827887459138308886">"Rejeição das chamadas indesejadas"</string>
+    <string name="CndMmi" msgid="3116446237081575808">"Chamando número de entrega"</string>
+    <string name="DndMmi" msgid="1265478932418334331">"Não perturbe"</string>
+    <string name="CLIRDefaultOnNextCallOn" msgid="429415409145781923">"O ID do chamador assume o padrão de restrito. Próxima chamada: Restrita"</string>
+    <string name="CLIRDefaultOnNextCallOff" msgid="3092918006077864624">"O ID do chamador assume o padrão de restrito. Próxima chamada: Não restrita"</string>
+    <string name="CLIRDefaultOffNextCallOn" msgid="6179425182856418465">"O ID do chamador assume o padrão de não restrito. Próxima chamada: Restrita"</string>
+    <string name="CLIRDefaultOffNextCallOff" msgid="2567998633124408552">"O ID do chamador assume o padrão de não restrito. Próxima chamada: Não restrita"</string>
+    <string name="serviceNotProvisioned" msgid="8614830180508686666">"O serviço não foi habilitado."</string>
+    <string name="CLIRPermanent" msgid="3377371145926835671">"Não é possível alterar a configuração de identificação de chamadas."</string>
+    <string name="RestrictedChangedTitle" msgid="5592189398956187498">"Acesso restrito alterado"</string>
+    <string name="RestrictedOnData" msgid="8653794784690065540">"O serviço de dados está bloqueado."</string>
+    <string name="RestrictedOnEmergency" msgid="6581163779072833665">"O serviço de emergência está bloqueado."</string>
+    <string name="RestrictedOnNormal" msgid="4953867011389750673">"O serviço de voz está bloqueado."</string>
+    <string name="RestrictedOnAllVoice" msgid="3396963652108151260">"Todos os serviços de voz estão bloqueados."</string>
+    <string name="RestrictedOnSms" msgid="8314352327461638897">"O serviço de SMS está bloqueado."</string>
+    <string name="RestrictedOnVoiceData" msgid="996636487106171320">"Os serviços de voz/dados estão bloqueados."</string>
+    <string name="RestrictedOnVoiceSms" msgid="1888588152792023873">"Os serviços de voz/SMS estão bloqueados."</string>
+    <string name="RestrictedOnAll" msgid="5643028264466092821">"Todos os serviços de voz/dados/SMS estão bloqueados."</string>
+    <string name="peerTtyModeFull" msgid="6165351790010341421">"TTD modo COMPLETO solicitado"</string>
+    <string name="peerTtyModeHco" msgid="5728602160669216784">"TTD modo HCO solicitado"</string>
+    <string name="peerTtyModeVco" msgid="1742404978686538049">"TTD modo VCO solicitado"</string>
+    <string name="peerTtyModeOff" msgid="3280819717850602205">"TTD modo DESLIGADO solicitado"</string>
+    <string name="serviceClassVoice" msgid="1258393812335258019">"Voz"</string>
+    <string name="serviceClassData" msgid="872456782077937893">"Dados"</string>
+    <string name="serviceClassFAX" msgid="5566624998840486475">"FAX"</string>
+    <string name="serviceClassSMS" msgid="2015460373701527489">"SMS"</string>
+    <string name="serviceClassDataAsync" msgid="4523454783498551468">"Assíncrono"</string>
+    <string name="serviceClassDataSync" msgid="7530000519646054776">"Sincronizar"</string>
+    <string name="serviceClassPacket" msgid="6991006557993423453">"Pacote"</string>
+    <string name="serviceClassPAD" msgid="3235259085648271037">"PAD"</string>
+    <string name="roamingText0" msgid="7170335472198694945">"Indicador de roaming ativado"</string>
+    <string name="roamingText1" msgid="5314861519752538922">"Indicador de roaming desativado"</string>
+    <string name="roamingText2" msgid="8969929049081268115">"Indicador de roaming piscando"</string>
+    <string name="roamingText3" msgid="5148255027043943317">"Fora da vizinhança"</string>
+    <string name="roamingText4" msgid="8808456682550796530">"Ao ar livre"</string>
+    <string name="roamingText5" msgid="7604063252850354350">"Roaming - Sistema recomendado"</string>
+    <string name="roamingText6" msgid="2059440825782871513">"Roaming -  Sistema disponível"</string>
+    <string name="roamingText7" msgid="7112078724097233605">"Roaming - Parceiro do Alliance"</string>
+    <string name="roamingText8" msgid="5989569778604089291">"Roaming - Parceiro do Google Premium"</string>
+    <string name="roamingText9" msgid="7969296811355152491">"Roaming - Funcionalidade de serviço completo"</string>
+    <string name="roamingText10" msgid="3992906999815316417">"Roaming - Funcionalidade de serviço parcial"</string>
+    <string name="roamingText11" msgid="4154476854426920970">"Banner de roaming ativado"</string>
+    <string name="roamingText12" msgid="1189071119992726320">"Banner de roaming desativado"</string>
+    <string name="roamingTextSearching" msgid="8360141885972279963">"Pesquisando serviço"</string>
+    <string name="wfcRegErrorTitle" msgid="2301376280632110664">"Chamadas por Wi-Fi"</string>
+  <string-array name="wfcOperatorErrorAlertMessages">
+  </string-array>
+  <string-array name="wfcOperatorErrorNotificationMessages">
+  </string-array>
+    <string name="wfcSpnFormat" msgid="8211621332478306568">"%s"</string>
+    <string name="wfcDataSpnFormat" msgid="1118052028767666883">"%s"</string>
+    <string name="wifi_calling_off_summary" msgid="8720659586041656098">"Desativado"</string>
+    <string name="wfc_mode_wifi_preferred_summary" msgid="1994113411286935263">"Wi-Fi preferido"</string>
+    <string name="wfc_mode_cellular_preferred_summary" msgid="5920549484600758786">"Celular preferido"</string>
+    <string name="wfc_mode_wifi_only_summary" msgid="2379919155237869320">"Somente Wi-Fi"</string>
+    <string name="cfTemplateNotForwarded" msgid="1683685883841272560">"<xliff:g id="BEARER_SERVICE_CODE">{0}</xliff:g>: Não encaminhado"</string>
+    <string name="cfTemplateForwarded" msgid="1302922117498590521">"<xliff:g id="BEARER_SERVICE_CODE">{0}</xliff:g>: <xliff:g id="DIALING_NUMBER">{1}</xliff:g>"</string>
+    <string name="cfTemplateForwardedTime" msgid="9206251736527085256">"<xliff:g id="BEARER_SERVICE_CODE">{0}</xliff:g>: <xliff:g id="DIALING_NUMBER">{1}</xliff:g> após <xliff:g id="TIME_DELAY">{2}</xliff:g> segundos"</string>
+    <string name="cfTemplateRegistered" msgid="5073237827620166285">"<xliff:g id="BEARER_SERVICE_CODE">{0}</xliff:g>: Não encaminhado"</string>
+    <string name="cfTemplateRegisteredTime" msgid="6781621964320635172">"<xliff:g id="BEARER_SERVICE_CODE">{0}</xliff:g>: Não encaminhado"</string>
+    <string name="fcComplete" msgid="3118848230966886575">"Código de recurso concluído."</string>
+    <string name="fcError" msgid="3327560126588500777">"Problema de conexão ou código de recurso inválido."</string>
+    <string name="httpErrorOk" msgid="1191919378083472204">"OK"</string>
+    <string name="httpError" msgid="7956392511146698522">"Ocorreu um erro na rede."</string>
+    <string name="httpErrorLookup" msgid="4711687456111963163">"Não foi possível encontrar o URL."</string>
+    <string name="httpErrorUnsupportedAuthScheme" msgid="6299980280442076799">"O esquema de autenticação do site não é suportado."</string>
+    <string name="httpErrorAuth" msgid="1435065629438044534">"Não foi possível autenticar."</string>
+    <string name="httpErrorProxyAuth" msgid="1788207010559081331">"Falha na autenticação por meio do servidor proxy."</string>
+    <string name="httpErrorConnect" msgid="8714273236364640549">"Não foi possível se conectar ao servidor."</string>
+    <string name="httpErrorIO" msgid="2340558197489302188">"Não foi possível estabelecer comunicação com o servidor. Tente novamente mais tarde."</string>
+    <string name="httpErrorTimeout" msgid="4743403703762883954">"O tempo limite de conexão com o servidor esgotou."</string>
+    <string name="httpErrorRedirectLoop" msgid="8679596090392779516">"A página contém muitos redirecionamentos do servidor."</string>
+    <string name="httpErrorUnsupportedScheme" msgid="5015730812906192208">"O protocolo não é compatível."</string>
+    <string name="httpErrorFailedSslHandshake" msgid="96549606000658641">"Não foi possível estabelecer uma conexão segura."</string>
+    <string name="httpErrorBadUrl" msgid="3636929722728881972">"Não foi possível abrir a página porque o URL é inválido."</string>
+    <string name="httpErrorFile" msgid="2170788515052558676">"Não foi possível acessar o arquivo."</string>
+    <string name="httpErrorFileNotFound" msgid="6203856612042655084">"Não foi possível encontrar o arquivo solicitado."</string>
+    <string name="httpErrorTooManyRequests" msgid="1235396927087188253">"Há muitas solicitações sendo processadas. Tente novamente mais tarde."</string>
+    <string name="notification_title" msgid="8967710025036163822">"Erro de login para <xliff:g id="ACCOUNT">%1$s</xliff:g>"</string>
+    <string name="contentServiceSync" msgid="8353523060269335667">"Sincronizar"</string>
+    <string name="contentServiceSyncNotificationTitle" msgid="397743349191901458">"Sincronizar"</string>
+    <string name="contentServiceTooManyDeletesNotificationDesc" msgid="8100981435080696431">"Muitas exclusões de <xliff:g id="CONTENT_TYPE">%s</xliff:g>."</string>
+    <string name="low_memory" product="tablet" msgid="6494019234102154896">"O armazenamento do tablet está cheio. Exclua alguns arquivos para liberar espaço."</string>
+    <string name="low_memory" product="watch" msgid="4415914910770005166">"Armazenamento do relógio cheio. Exclua alguns arquivos para liberar espaço."</string>
+    <string name="low_memory" product="tv" msgid="516619861191025923">"O armazenamento da TV está cheio. Exclua alguns arquivos para liberar espaço."</string>
+    <string name="low_memory" product="default" msgid="3475999286680000541">"O armazenamento do telefone está cheio. Exclua alguns arquivos para liberar espaço."</string>
+    <string name="ssl_ca_cert_warning" msgid="5848402127455021714">"A rede pode ser monitorada"</string>
+    <string name="ssl_ca_cert_noti_by_unknown" msgid="4475437862189850602">"Por terceiros desconhecidos"</string>
+    <string name="ssl_ca_cert_noti_by_administrator" msgid="550758088185764312">"Pelo seu perfil profissional de administrador"</string>
+    <string name="ssl_ca_cert_noti_managed" msgid="4030263497686867141">"Por <xliff:g id="MANAGING_DOMAIN">%s</xliff:g>"</string>
+    <string name="work_profile_deleted" msgid="5005572078641980632">"Perfil de trabalho excluído"</string>
+    <string name="work_profile_deleted_description" msgid="6305147513054341102">"Perfil de trabalho excluído devido à ausência de um app para administrador."</string>
+    <string name="work_profile_deleted_details" msgid="226615743462361248">"O app para administrador do perfil de trabalho não foi encontrado ou está corrompido. Consequentemente, seu perfil de trabalho e os dados relacionados foram excluídos. Entre em contato com seu administrador para receber assistência."</string>
+    <string name="work_profile_deleted_description_dpm_wipe" msgid="6019770344820507579">"Seu perfil de trabalho não está mais disponível neste dispositivo."</string>
+    <string name="factory_reset_warning" msgid="5423253125642394387">"Seu dispositivo será limpo"</string>
+    <string name="factory_reset_message" msgid="4905025204141900666">"O app para administrador está sem alguns componentes ou foi corrompido e não pode ser usado. Seu dispositivo será limpo agora. Entre em contato com seu administrador para receber assistência."</string>
+    <string name="me" msgid="6545696007631404292">"Eu"</string>
+    <string name="power_dialog" product="tablet" msgid="8545351420865202853">"Opções do tablet"</string>
+    <string name="power_dialog" product="tv" msgid="6153888706430556356">"Opções de TV"</string>
+    <string name="power_dialog" product="default" msgid="1319919075463988638">"Opções do telefone"</string>
+    <string name="silent_mode" msgid="7167703389802618663">"Modo silencioso"</string>
+    <string name="turn_on_radio" msgid="3912793092339962371">"Ativar sem fio"</string>
+    <string name="turn_off_radio" msgid="8198784949987062346">"Desativar a rede sem fio"</string>
+    <string name="screen_lock" msgid="799094655496098153">"Bloquear tela"</string>
+    <string name="power_off" msgid="4266614107412865048">"Desligar"</string>
+    <string name="silent_mode_silent" msgid="319298163018473078">"Campainha desligada"</string>
+    <string name="silent_mode_vibrate" msgid="7072043388581551395">"Vibração da campainha"</string>
+    <string name="silent_mode_ring" msgid="8592241816194074353">"Campainha ligada"</string>
+    <string name="reboot_to_update_title" msgid="6212636802536823850">"Atualização do sistema Android"</string>
+    <string name="reboot_to_update_prepare" msgid="6305853831955310890">"Preparando para atualizar..."</string>
+    <string name="reboot_to_update_package" msgid="3871302324500927291">"Processando o pacote de atualização…"</string>
+    <string name="reboot_to_update_reboot" msgid="6428441000951565185">"Reiniciando..."</string>
+    <string name="reboot_to_reset_title" msgid="4142355915340627490">"Redefinição para configuração original"</string>
+    <string name="reboot_to_reset_message" msgid="2432077491101416345">"Reiniciando..."</string>
+    <string name="shutdown_progress" msgid="2281079257329981203">"Encerrando…"</string>
+    <string name="shutdown_confirm" product="tablet" msgid="3385745179555731470">"Seu tablet será desligado."</string>
+    <string name="shutdown_confirm" product="tv" msgid="476672373995075359">"Sua TV será desligada."</string>
+    <string name="shutdown_confirm" product="watch" msgid="3490275567476369184">"Seu relógio será desligado."</string>
+    <string name="shutdown_confirm" product="default" msgid="649792175242821353">"O seu telefone será desligado."</string>
+    <string name="shutdown_confirm_question" msgid="2906544768881136183">"Deseja desligar?"</string>
+    <string name="reboot_safemode_title" msgid="7054509914500140361">"Reiniciar no modo de segurança"</string>
+    <string name="reboot_safemode_confirm" msgid="55293944502784668">"Deseja reiniciar no modo de segurança? Isso desativará todos os apps de terceiros instalados. Eles serão restaurados quando você reiniciar novamente."</string>
+    <string name="recent_tasks_title" msgid="3691764623638127888">"Recente"</string>
+    <string name="no_recent_tasks" msgid="8794906658732193473">"Nenhum app recente"</string>
+    <string name="global_actions" product="tablet" msgid="408477140088053665">"Opções do tablet"</string>
+    <string name="global_actions" product="tv" msgid="7240386462508182976">"Opções da TV"</string>
+    <string name="global_actions" product="default" msgid="2406416831541615258">"Opções do telefone"</string>
+    <string name="global_action_lock" msgid="2844945191792119712">"Bloquear tela"</string>
+    <string name="global_action_power_off" msgid="4471879440839879722">"Desligar"</string>
+    <string name="global_action_bug_report" msgid="7934010578922304799">"Relatório de bugs"</string>
+    <string name="bugreport_title" msgid="2667494803742548533">"Obter relatório de bugs"</string>
+    <string name="bugreport_message" msgid="398447048750350456">"Isto coletará informações sobre o estado atual do dispositivo para enviá-las em uma mensagem de e-mail. Após iniciar o relatório de bugs, será necessário aguardar algum tempo até que esteja pronto para ser enviado."</string>
+    <string name="global_action_toggle_silent_mode" msgid="8219525344246810925">"Modo silencioso"</string>
+    <string name="global_action_silent_mode_on_status" msgid="3289841937003758806">"Som DESATIVADO"</string>
+    <string name="global_action_silent_mode_off_status" msgid="1506046579177066419">"O som está ATIVADO"</string>
+    <string name="global_actions_toggle_airplane_mode" msgid="5884330306926307456">"Modo avião"</string>
+    <string name="global_actions_airplane_mode_on_status" msgid="2719557982608919750">"Modo avião ATIVADO"</string>
+    <string name="global_actions_airplane_mode_off_status" msgid="5075070442854490296">"Modo avião DESATIVADO"</string>
+    <string name="global_action_settings" msgid="1756531602592545966">"Configurações"</string>
+    <string name="global_action_assist" msgid="3892832961594295030">"Assistência"</string>
+    <string name="global_action_voice_assist" msgid="7751191495200504480">"Ajuda de voz"</string>
+    <string name="global_action_lockdown" msgid="8751542514724332873">"Bloquear agora"</string>
+    <string name="status_bar_notification_info_overflow" msgid="5301981741705354993">"&gt;999"</string>
+    <string name="safeMode" msgid="2788228061547930246">"Modo de segurança"</string>
+    <string name="android_system_label" msgid="6577375335728551336">"Sistema Android"</string>
+    <string name="user_owner_label" msgid="2804351898001038951">"Pessoal"</string>
+    <string name="managed_profile_label" msgid="6260850669674791528">"Trabalho"</string>
+    <string name="permgrouplab_contacts" msgid="3657758145679177612">"Contatos"</string>
+    <string name="permgroupdesc_contacts" msgid="6951499528303668046">"acessar seus contatos"</string>
+    <string name="permgrouplab_location" msgid="7275582855722310164">"Local"</string>
+    <string name="permgroupdesc_location" msgid="1346617465127855033">"acesse o local do dispositivo"</string>
+    <string name="permgrouplab_calendar" msgid="5863508437783683902">"Agenda"</string>
+    <string name="permgroupdesc_calendar" msgid="3889615280211184106">"acessar sua agenda"</string>
+    <string name="permgrouplab_sms" msgid="228308803364967808">"SMS"</string>
+    <string name="permgroupdesc_sms" msgid="4656988620100940350">"enviar e ver mensagens SMS"</string>
+    <string name="permgrouplab_storage" msgid="1971118770546336966">"Armazenamento"</string>
+    <string name="permgroupdesc_storage" msgid="637758554581589203">"acesse fotos, mídia e arquivos do seu dispositivo"</string>
+    <string name="permgrouplab_microphone" msgid="171539900250043464">"Microfone"</string>
+    <string name="permgroupdesc_microphone" msgid="4988812113943554584">"grave áudio"</string>
+    <string name="permgrouplab_camera" msgid="4820372495894586615">"Câmera"</string>
+    <string name="permgroupdesc_camera" msgid="3250611594678347720">"tire fotos e grave vídeos"</string>
+    <string name="permgrouplab_phone" msgid="5229115638567440675">"Telefone"</string>
+    <string name="permgroupdesc_phone" msgid="6234224354060641055">"fazer e gerenciar chamadas telefônicas"</string>
+    <string name="permgrouplab_sensors" msgid="416037179223226722">"Sensores corporais"</string>
+    <string name="permgroupdesc_sensors" msgid="7147968539346634043">"acessar dados do sensor sobre seus sinais vitais"</string>
+    <string name="capability_title_canRetrieveWindowContent" msgid="3901717936930170320">"Recuperar cont. da janela"</string>
+    <string name="capability_desc_canRetrieveWindowContent" msgid="3772225008605310672">"Inspecionar o conteúdo da janela com que você está interagindo."</string>
+    <string name="capability_title_canRequestTouchExploration" msgid="3108723364676667320">"Ativar Explorar por toque"</string>
+    <string name="capability_desc_canRequestTouchExploration" msgid="5800552516779249356">"Itens tocados serão falados em voz alta e a tela poderá ser explorada por meio de gestos."</string>
+    <string name="capability_title_canRequestEnhancedWebAccessibility" msgid="1739881766522594073">"Ativar acessibilidade na Web aprimorada"</string>
+    <string name="capability_desc_canRequestEnhancedWebAccessibility" msgid="7881063961507511765">"Scripts podem ser instalados para tornar o conteúdo do app mais acessível."</string>
+    <string name="capability_title_canRequestFilterKeyEvents" msgid="2103440391902412174">"Observar o texto digitado"</string>
+    <string name="capability_desc_canRequestFilterKeyEvents" msgid="7463135292204152818">"Inclui dados pessoais, como números de cartão de crédito e senhas."</string>
+    <string name="permlab_statusBar" msgid="7417192629601890791">"desativar ou modificar a barra de status"</string>
+    <string name="permdesc_statusBar" msgid="8434669549504290975">"Permite que o app desative a barra de status ou adicione e remova ícones do sistema."</string>
+    <string name="permlab_statusBarService" msgid="7247281911387931485">"barra de status"</string>
+    <string name="permdesc_statusBarService" msgid="716113660795976060">"Permite que o app seja a barra de status."</string>
+    <string name="permlab_expandStatusBar" msgid="1148198785937489264">"expandir/recolher barra de status"</string>
+    <string name="permdesc_expandStatusBar" msgid="6917549437129401132">"Permite que o app expanda ou recolha a barra de status."</string>
+    <string name="permlab_install_shortcut" msgid="4279070216371564234">"instalar atalhos"</string>
+    <string name="permdesc_install_shortcut" msgid="8341295916286736996">"Permite que um app adicione atalhos da tela inicial sem a intervenção do usuário."</string>
+    <string name="permlab_uninstall_shortcut" msgid="4729634524044003699">"desinstalar atalhos"</string>
+    <string name="permdesc_uninstall_shortcut" msgid="6745743474265057975">"Permite que o app remova atalhos da tela inicial sem a intervenção do usuário."</string>
+    <string name="permlab_processOutgoingCalls" msgid="3906007831192990946">"redirecionar as chamadas efetuadas"</string>
+    <string name="permdesc_processOutgoingCalls" msgid="5156385005547315876">"Permite que o app veja o número discado ao realizar uma chamada, com a opção de redirecionar a chamada para outro número ou abortá-la."</string>
+    <string name="permlab_receiveSms" msgid="8673471768947895082">"receber mensagens de texto (SMS)"</string>
+    <string name="permdesc_receiveSms" msgid="6424387754228766939">"Permite que o app receba e processe mensagens SMS. Isso significa que o app pode monitorar ou excluir mensagens enviadas para o dispositivo sem mostrá-las para você."</string>
+    <string name="permlab_receiveMms" msgid="1821317344668257098">"receber mensagens de texto (MMS)"</string>
+    <string name="permdesc_receiveMms" msgid="533019437263212260">"Permite que o app receba e processe mensagens MMS. Isso significa que o app pode monitorar ou excluir as mensagens enviadas para o dispositivo sem mostrá-las para você."</string>
+    <string name="permlab_readCellBroadcasts" msgid="1598328843619646166">"ler mensagens de difusão celular"</string>
+    <string name="permdesc_readCellBroadcasts" msgid="6361972776080458979">"Permite que o app leia mensagens de difusão celular recebidas por seu dispositivo. Alertas de difusão celular são recebidos em alguns locais para avisar você de situações de emergência. Apps maliciosos podem interferir no desempenho ou funcionamento de seu dispositivo quando uma difusão celular de emergência é recebida."</string>
+    <string name="permlab_subscribedFeedsRead" msgid="4756609637053353318">"ler feeds inscritos"</string>
+    <string name="permdesc_subscribedFeedsRead" msgid="5557058907906144505">"Permite que o app obtenha detalhes sobre os feeds sincronizados no momento."</string>
+    <string name="permlab_sendSms" msgid="7544599214260982981">"enviar e ver mensagens SMS"</string>
+    <string name="permdesc_sendSms" msgid="7094729298204937667">"Permite que o app envie mensagens SMS. Isso pode resultar em cobranças inesperadas. Apps maliciosos podem gerar custos através do envio de mensagens sem sua confirmação."</string>
+    <string name="permlab_readSms" msgid="8745086572213270480">"ler suas mensagens de texto (SMS ou MMS)"</string>
+    <string name="permdesc_readSms" product="tablet" msgid="2467981548684735522">"Permite que o app leia mensagens SMS armazenadas no tablet ou cartão SIM. Isso permite que o app leia todas as mensagens SMS, independentemente de seu conteúdo ou confidencialidade."</string>
+    <string name="permdesc_readSms" product="tv" msgid="5102425513647038535">"Permite que o app leia as mensagens SMS armazenadas na sua TV ou no cartão SIM. Isso permite que o app leia todas as mensagens SMS, independentemente do seu conteúdo ou confidencialidade."</string>
+    <string name="permdesc_readSms" product="default" msgid="3695967533457240550">"Permite que o app leia mensagens SMS armazenadas no telefone ou cartão SIM. Isso permite que o app leia todas as mensagens SMS, independentemente de seu conteúdo ou confidencialidade."</string>
+    <string name="permlab_receiveWapPush" msgid="5991398711936590410">"receber mensagens de texto (WAP)"</string>
+    <string name="permdesc_receiveWapPush" msgid="748232190220583385">"Permite que o app receba e processe mensagens WAP. Esta permissão inclui a capacidade de monitorar ou excluir mensagens enviadas para você sem mostrá-las para você."</string>
+    <string name="permlab_getTasks" msgid="6466095396623933906">"recuperar apps em execução"</string>
+    <string name="permdesc_getTasks" msgid="7454215995847658102">"Permite que o app obtenha informações sobre tarefas em execução atuais e recentes. Pode permitir que o app descubra informações sobre os apps usados ​​no dispositivo."</string>
+    <string name="permlab_manageProfileAndDeviceOwners" msgid="5979288447973722097">"Gerenciar proprietários de perfis e de dispositivos"</string>
+    <string name="permdesc_manageProfileAndDeviceOwners" msgid="106894851498657169">"Permitir que os apps definam os proprietários de perfis e de dispositivos."</string>
+    <string name="permlab_reorderTasks" msgid="2018575526934422779">"reordenar os apps em execução"</string>
+    <string name="permdesc_reorderTasks" msgid="7734217754877439351">"Permite que o app mova tarefas para o primeiro plano e o plano de fundo, sem sua intervenção."</string>
+    <string name="permlab_enableCarMode" msgid="5684504058192921098">"ativar o modo carro"</string>
+    <string name="permdesc_enableCarMode" msgid="4853187425751419467">"Permite que o app ative o modo Carro."</string>
+    <string name="permlab_killBackgroundProcesses" msgid="3914026687420177202">"fechar outros apps"</string>
+    <string name="permdesc_killBackgroundProcesses" msgid="4593353235959733119">"Permite que o app encerre processos em segundo plano de outros apps. Pode ser que outros apps parem de funcionar."</string>
+    <string name="permlab_systemAlertWindow" msgid="3543347980839518613">"sobrepor outros apps"</string>
+    <string name="permdesc_systemAlertWindow" msgid="8584678381972820118">"Permite que o app se sobreponha visualmente a outros apps ou a partes da interface do usuário. Podem interferir com o uso da interface de qualquer app ou alterar o que você acha que está vendo em outros apps."</string>
+    <string name="permlab_persistentActivity" msgid="8841113627955563938">"sempre executar o app"</string>
+    <string name="permdesc_persistentActivity" product="tablet" msgid="8525189272329086137">"Permite que o app torne partes de si mesmo persistentes na memória. Pode limitar a memória disponível para outros apps, deixando o tablet mais lento."</string>
+    <string name="permdesc_persistentActivity" product="tv" msgid="5086862529499103587">"Permite que o app torne partes de si mesmo persistentes na memória. Isso pode limitar a memória disponível para outros apps, deixando a TV mais lenta."</string>
+    <string name="permdesc_persistentActivity" product="default" msgid="4384760047508278272">"Permite que o app torne partes de si mesmo persistentes na memória. Pode limitar a memória disponível para outros apps, deixando o telefone mais lento."</string>
+    <string name="permlab_getPackageSize" msgid="7472921768357981986">"medir o espaço de armazenamento do app"</string>
+    <string name="permdesc_getPackageSize" msgid="3921068154420738296">"Permite que o app recupere o código, os dados e os tamanhos de cache"</string>
+    <string name="permlab_writeSettings" msgid="2226195290955224730">"modificar configurações do sistema"</string>
+    <string name="permdesc_writeSettings" msgid="7775723441558907181">"Permite que o app modifique os dados das configurações do sistema. Apps maliciosos podem corromper a configuração de seu sistema."</string>
+    <string name="permlab_receiveBootCompleted" msgid="5312965565987800025">"executar na inicialização"</string>
+    <string name="permdesc_receiveBootCompleted" product="tablet" msgid="7390304664116880704">"Permite que o app inicie-se logo que o sistema concluir a inicialização. Isso pode tornar a inicialização do tablet mais lenta e permitir que o app deixe o telefone mais lento por estar sempre em execução."</string>
+    <string name="permdesc_receiveBootCompleted" product="tv" msgid="4525890122209673621">"Permite que o app seja iniciado assim que o sistema terminar de ser iniciado. Isso pode fazer com que demore mais tempo para a TV ser iniciada, além de permitir que o app deixe o tablet em geral mais lento por estar sempre em execução."</string>
+    <string name="permdesc_receiveBootCompleted" product="default" msgid="513950589102617504">"Permite que o app inicie-se logo que o sistema concluir a inicialização. Isso pode tornar a inicialização do telefone mais lenta e permitir que o app deixe o telefone mais lento por estar sempre em execução."</string>
+    <string name="permlab_broadcastSticky" msgid="7919126372606881614">"enviar transmissão persistente"</string>
+    <string name="permdesc_broadcastSticky" product="tablet" msgid="7749760494399915651">"Permite que o app envie transmissões fixas, que permaneçam depois que a transmissão terminar. O uso excessivo pode desacelerar ou desestabilizar o tablet, fazendo com que ele utilize muita memória."</string>
+    <string name="permdesc_broadcastSticky" product="tv" msgid="6839285697565389467">"Permite que o app envie transmissões aderentes, que permanecem depois que a transmissão termina. O uso excessivo pode fazer com que a TV fique lenta ou instável ao fazer com que ela use muita memória."</string>
+    <string name="permdesc_broadcastSticky" product="default" msgid="2825803764232445091">"Permite que o app envie transmissões fixas, que permanecem depois que a transmissão termina. O uso excessivo pode deixar o telefone lento ou instável, fazendo com que ele use muita memória."</string>
+    <string name="permlab_readContacts" msgid="8348481131899886131">"ler seus contatos"</string>
+    <string name="permdesc_readContacts" product="tablet" msgid="5294866856941149639">"Permite que o app leia dados dos contatos armazenados no tablet, incluindo a frequência com que você chamou, enviou e-mails ou se comunicou de qualquer outra forma com indivíduos específicos. Esta permissão autoriza o app a salvar seus dados de contato, e apps maliciosos podem compartilhar esses dados de contato sem seu conhecimento."</string>
+    <string name="permdesc_readContacts" product="tv" msgid="1839238344654834087">"Permite que o app leia os dados dos seus contatos armazenados na sua TV, incluindo a frequência com que você ligou, enviou e-mail ou se comunicou de outras formas com pessoas específicas. Essa permissão autoriza apps a salvarem seus dados de contato, e apps maliciosos podem compartilhar os dados de contato sem seu conhecimento."</string>
+    <string name="permdesc_readContacts" product="default" msgid="8440654152457300662">"Permite que o app leia dados dos contatos armazenados no telefone, incluindo a frequência com que você chamou, enviou e-mails ou se comunicou de qualquer outra forma com indivíduos específicos. Esta permissão autoriza o app a salvar seus dados de contato, e apps maliciosos podem compartilhar esses dados de contato sem seu conhecimento."</string>
+    <string name="permlab_writeContacts" msgid="5107492086416793544">"modificar seus contatos"</string>
+    <string name="permdesc_writeContacts" product="tablet" msgid="897243932521953602">"Permite que o app modifique os dados sobre os contatos armazenados no tablet, incluindo a frequência com que você fez chamadas, enviou e-mails ou se comunicou de outras formas com contatos específicos. Esta permissão autoriza o app a excluir dados de contatos."</string>
+    <string name="permdesc_writeContacts" product="tv" msgid="5438230957000018959">"Permite que o app modifique os dados de contatos armazenados na sua TV, incluindo a frequência com que você fez chamadas, enviou e-mails ou se comunicou de outras formas com contatos específicos. Essa permissão autoriza o app a excluir dados de contatos."</string>
+    <string name="permdesc_writeContacts" product="default" msgid="589869224625163558">"Permite que o app modifique os dados dos contatos armazenados no telefone, incluindo a frequência com que você fez chamadas, enviou e-mails ou se comunicou de outras formas com contatos específicos. Esta permissão autoriza o app a excluir dados de contatos."</string>
+    <string name="permlab_readCallLog" msgid="3478133184624102739">"ler registro de chamadas"</string>
+    <string name="permdesc_readCallLog" product="tablet" msgid="3700645184870760285">"Permite que o app leia o histórico de chamadas do tablet, incluindo dados de chamadas recebidas e realizadas. Esta permissão autoriza o app a salvar os dados de seu histórico de chamadas, e apps maliciosos podem compartilhar esses dados do histórico de chamadas sem seu conhecimento."</string>
+    <string name="permdesc_readCallLog" product="tv" msgid="5611770887047387926">"Permite que o app leia o registro de chamadas da sua TV, incluindo dados sobre chamadas recebidas e efetuadas. Essa permissão autoriza apps a salvarem os dados do seu registro de chamadas, e apps maliciosos podem compartilhar dados do registro de chamadas sem seu conhecimento."</string>
+    <string name="permdesc_readCallLog" product="default" msgid="5777725796813217244">"Permite que o app leia o histórico de chamadas do telefone, incluindo dados de chamadas recebidas e realizadas. Esta permissão autoriza o app a salvar os dados de seu histórico de chamadas, e apps maliciosos podem compartilhar os dados de seu histórico de chamadas sem seu conhecimento."</string>
+    <string name="permlab_writeCallLog" msgid="8552045664743499354">"salvar no registo de chamadas"</string>
+    <string name="permdesc_writeCallLog" product="tablet" msgid="6661806062274119245">"Permite que o app modifique o registro de chamadas de seu tablet, incluindo dados sobre chamadas recebidas e efetuadas. Apps maliciosos podem usar esta permissão para apagar ou modificar seu registro de chamadas."</string>
+    <string name="permdesc_writeCallLog" product="tv" msgid="4225034892248398019">"Permite que o app modifique o registro de chamadas da sua TV, incluindo dados sobre chamadas recebidas e efetuadas. Apps maliciosos podem usá-lo para apagar ou modificar seu registro de chamadas."</string>
+    <string name="permdesc_writeCallLog" product="default" msgid="683941736352787842">"Permite que o app modifique o registro de chamadas de seu telefone, incluindo dados sobre chamadas recebidas e efetuadas. Apps maliciosos podem usar esta permissão para apagar ou modificar seu registro de chamadas."</string>
+    <string name="permlab_bodySensors" msgid="4871091374767171066">"sensores corporais"</string>
+    <string name="permdesc_bodySensors" product="default" msgid="4380015021754180431">"Permite que o app acesse dados de sensores que monitoram sua condição física, como a frequência cardíaca."</string>
+    <string name="permlab_readCalendar" msgid="5972727560257612398">"ler compromissos e informações confidenciais"</string>
+    <string name="permdesc_readCalendar" product="tablet" msgid="4216462049057658723">"Permite que o app leia todos os eventos do calendário armazenados no tablet, incluindo os de amigos ou colegas de trabalho. Pode permitir que o app compartilhe ou salve os dados do calendário, independentemente de sua confidencialidade."</string>
+    <string name="permdesc_readCalendar" product="tv" msgid="3191352452242394196">"Permite que o app leia todos os eventos da agenda armazenados na sua TV, incluindo os de amigos ou colegas de trabalho. Isso pode permitir que o app compartilhe ou salve os dados da sua agenda, independentemente de serem confidenciais ou sensíveis."</string>
+    <string name="permdesc_readCalendar" product="default" msgid="7434548682470851583">"Permite que o app leia todos os eventos do calendário armazenados no telefone, incluindo os de amigos ou colegas de trabalho. Pode permitir que o app compartilhe ou salve os dados do calendário, independentemente de sua confidencialidade."</string>
+    <string name="permlab_writeCalendar" msgid="8438874755193825647">"adicionar ou modificar compromissos e enviar e-mail para os convidados sem o conhecimento dos donos"</string>
+    <string name="permdesc_writeCalendar" product="tablet" msgid="6679035520113668528">"Permite que o app adicione, remova e altere eventos que você pode modificar em seu tablet, incluindo os de amigos e colegas de trabalho. Isso pode permitir que o app envie mensagens que parecem ser de autoria do proprietário do calendário, ou modifique eventos sem conhecimento do proprietário."</string>
+    <string name="permdesc_writeCalendar" product="tv" msgid="1273290605500902507">"Permite que o app adicione, remova ou altere eventos que podem ser modificados na sua TV, incluindo eventos de amigos ou colegas de trabalho. Isso pode permitir que o app envie mensagens que parecem vir dos proprietários de agendas ou modifique eventos sem o conhecimento dos proprietários."</string>
+    <string name="permdesc_writeCalendar" product="default" msgid="2324469496327249376">"Permite que o app adicione, remova e altere eventos que você pode modificar em seu telefone, incluindo os de amigos e colegas de trabalho. Isso pode permitir que o app envie mensagens que parecem ser de autoria do proprietário do calendário, ou modifique eventos sem conhecimento do proprietário."</string>
+    <string name="permlab_accessLocationExtraCommands" msgid="2836308076720553837">"acessar comandos extras do provedor de localização"</string>
+    <string name="permdesc_accessLocationExtraCommands" msgid="6078307221056649927">"Permite que o app acesse comandos do provedor não relacionados à localização. Isso pode permitir que o app interfira no funcionamento do GPS ou de outras fontes de localização."</string>
+    <string name="permlab_accessFineLocation" msgid="1191898061965273372">"localização precisa (GPS e com base na rede)"</string>
+    <string name="permdesc_accessFineLocation" msgid="5295047563564981250">"Permite que o app acesse sua localização exata por meio do sistema de posicionamento global (GPS) ou de fontes de localização da rede, como torres de celulares e redes Wi-Fi. Esses serviços de localização devem estar ativados e disponíveis para que sejam usados pelo app. O app pode usar esta permissão para determinar onde você está, além de consumir mais bateria."</string>
+    <string name="permlab_accessCoarseLocation" msgid="4887895362354239628">"localização aproximada (com base na rede)"</string>
+    <string name="permdesc_accessCoarseLocation" msgid="2538200184373302295">"Permite que o app acesse sua localização aproximada por meio do sistema de posicionamento global (GPS) ou de fontes de localização da rede, como torres de celulares e redes Wi-Fi. Esses serviços de localização devem estar ativados e disponíveis para que sejam usados pelo app. O app pode usar esta permissão para determinar aproximadamente onde você está."</string>
+    <string name="permlab_modifyAudioSettings" msgid="6095859937069146086">"alterar as suas configurações de áudio"</string>
+    <string name="permdesc_modifyAudioSettings" msgid="3522565366806248517">"Permite que o app modifique configurações de áudio globais como volume e alto-falantes de saída."</string>
+    <string name="permlab_recordAudio" msgid="3876049771427466323">"gravar áudio"</string>
+    <string name="permdesc_recordAudio" msgid="4906839301087980680">"Permite que o app grave áudio com o microfone. Esta permissão autoriza o app a gravar áudio a qualquer momento, sem sua confirmação."</string>
+    <string name="permlab_sim_communication" msgid="1180265879464893029">"comunicação com sim"</string>
+    <string name="permdesc_sim_communication" msgid="5725159654279639498">"Permite que o app envie comandos ao SIM. Muito perigoso."</string>
+    <string name="permlab_camera" msgid="3616391919559751192">"tirar fotos e gravar vídeos"</string>
+    <string name="permdesc_camera" msgid="8497216524735535009">"Permite que o app tire fotos e filme vídeos com a câmera. Esta permissão autoriza o app a usar a câmera a qualquer momento sem sua confirmação."</string>
+    <string name="permlab_vibrate" msgid="7696427026057705834">"controlar vibração"</string>
+    <string name="permdesc_vibrate" msgid="6284989245902300945">"Permite que o app controle a vibração."</string>
+    <string name="permlab_flashlight" msgid="2155920810121984215">"controlar lanterna"</string>
+    <string name="permdesc_flashlight" msgid="6522284794568368310">"Permite que o app controle a lanterna."</string>
+    <string name="permlab_callPhone" msgid="3925836347681847954">"ligar diretamente para números de telefone"</string>
+    <string name="permdesc_callPhone" msgid="3740797576113760827">"Permite que o app ligue para números de telefone sem sua intervenção. Isso pode resultar em cobranças ou chamadas inesperadas. Esta opção não permite que o app ligue para números de emergência. Apps maliciosos podem gerar custos com chamadas feitas sem sua confirmação."</string>
+    <string name="permlab_accessImsCallService" msgid="3574943847181793918">"acessar serviço de mensagens instantâneas para chamadas"</string>
+    <string name="permdesc_accessImsCallService" msgid="8992884015198298775">"Permite que o app use o serviço de mensagens instantâneas para fazer chamadas sem sua intervenção."</string>
+    <string name="permlab_readPhoneState" msgid="9178228524507610486">"ler status e identidade do telefone"</string>
+    <string name="permdesc_readPhoneState" msgid="1639212771826125528">"Permite que o app acesse os recursos de telefonia do dispositivo. Esta permissão autoriza o app a determinar o número de telefone e IDs de dispositivo, quando uma chamada está ativa, e o número remoto conectado a uma chamada."</string>
+    <string name="permlab_wakeLock" product="tablet" msgid="1531731435011495015">"impedir modo de inatividade do tablet"</string>
+    <string name="permlab_wakeLock" product="tv" msgid="2601193288949154131">"impedir a suspensão da TV"</string>
+    <string name="permlab_wakeLock" product="default" msgid="573480187941496130">"impedir modo de inatividade do telefone"</string>
+    <string name="permdesc_wakeLock" product="tablet" msgid="7311319824400447868">"Permite que o app impeça o tablet de entrar no modo de inatividade."</string>
+    <string name="permdesc_wakeLock" product="tv" msgid="3208534859208996974">"Permite que o app impeça a suspensão da TV."</string>
+    <string name="permdesc_wakeLock" product="default" msgid="8559100677372928754">"Permite que o app impeça o telefone de entrar no modo de inatividade."</string>
+    <string name="permlab_transmitIr" msgid="7545858504238530105">"transmitir infravermelhos"</string>
+    <string name="permdesc_transmitIr" product="tablet" msgid="5358308854306529170">"Permite que o app use o transmissor infravermelho do tablet."</string>
+    <string name="permdesc_transmitIr" product="tv" msgid="3926790828514867101">"Permite que o app use o transmissor de infravermelho da TV."</string>
+    <string name="permdesc_transmitIr" product="default" msgid="7957763745020300725">"Permite que o app use o transmissor infravermelho do telefone."</string>
+    <string name="permlab_setWallpaper" msgid="6627192333373465143">"definir plano de fundo"</string>
+    <string name="permdesc_setWallpaper" msgid="7373447920977624745">"Permite que o app defina o plano de fundo do sistema."</string>
+    <string name="permlab_setWallpaperHints" msgid="3278608165977736538">"ajustar tamanho do plano de fundo"</string>
+    <string name="permdesc_setWallpaperHints" msgid="8235784384223730091">"Permite que o app defina as dicas de tamanho do plano de fundo do sistema."</string>
+    <string name="permlab_setTimeZone" msgid="2945079801013077340">"definir fuso horário"</string>
+    <string name="permdesc_setTimeZone" product="tablet" msgid="1676983712315827645">"Permite que o app altere o fuso horário do tablet."</string>
+    <string name="permdesc_setTimeZone" product="tv" msgid="888864653946175955">"Permite que o app altere o fuso horário da TV."</string>
+    <string name="permdesc_setTimeZone" product="default" msgid="4499943488436633398">"Permite que o app altera o fuso horário do telefone."</string>
+    <string name="permlab_getAccounts" msgid="1086795467760122114">"encontrar contas no dispositivo"</string>
+    <string name="permdesc_getAccounts" product="tablet" msgid="2741496534769660027">"Permite que o app obtenha a lista de contas conhecidas pelo tablet. Isso pode incluir todas as contas criadas pelos apps instalados."</string>
+    <string name="permdesc_getAccounts" product="tv" msgid="4190633395633907543">"Permite que o app receba a lista de contas conhecidas pela TV. Isso pode incluir todas as contas criadas pelos apps instalados."</string>
+    <string name="permdesc_getAccounts" product="default" msgid="3448316822451807382">"Permite que o app obtenha a lista de contas conhecidas pelo telefone. Isso pode incluir todas as contas criadas pelos apps instalados."</string>
+    <string name="permlab_accessNetworkState" msgid="4951027964348974773">"ver conexões de rede"</string>
+    <string name="permdesc_accessNetworkState" msgid="8318964424675960975">"Permite que o app acesse informações sobre conexões de rede, como as redes existentes e conectadas."</string>
+    <string name="permlab_createNetworkSockets" msgid="8018758136404323658">"acesso total à rede"</string>
+    <string name="permdesc_createNetworkSockets" msgid="3403062187779724185">"Permite que o app crie soquetes de rede e utilize protocolos de rede personalizados. O navegador e outros apps fornecem meios de enviar dados para a Internet, e por isso esta permissão não é necessária para enviar os dados."</string>
+    <string name="permlab_changeNetworkState" msgid="958884291454327309">"alterar conectividade da rede"</string>
+    <string name="permdesc_changeNetworkState" msgid="6789123912476416214">"Permite que o app altere o estado de conectividade de rede."</string>
+    <string name="permlab_changeTetherState" msgid="5952584964373017960">"alterar conectividade vinculada"</string>
+    <string name="permdesc_changeTetherState" msgid="1524441344412319780">"Permite que o app altere o estado de conectividade de rede conectada."</string>
+    <string name="permlab_accessWifiState" msgid="5202012949247040011">"ver conexões Wi-Fi"</string>
+    <string name="permdesc_accessWifiState" msgid="5002798077387803726">"Permite que o app acesse informações sobre redes Wi-Fi, como a ativação do Wi-Fi e o nome dos dispositivos Wi-Fi conectados."</string>
+    <string name="permlab_changeWifiState" msgid="6550641188749128035">"conectar e desconectar do Wi-Fi"</string>
+    <string name="permdesc_changeWifiState" msgid="7137950297386127533">"Permite que o app conecte e desconecte dos pontos de acesso Wi-Fi e faça alterações nas configurações do dispositivo para redes Wi-Fi."</string>
+    <string name="permlab_changeWifiMulticastState" msgid="1368253871483254784">"permitir recebimento de multicast Wi-Fi"</string>
+    <string name="permdesc_changeWifiMulticastState" product="tablet" msgid="7969774021256336548">"Permite que o app receba pacotes enviados para todos os dispositivos em uma rede Wi-Fi usando endereços de difusão seletiva, e não apenas o tablet. Consome mais energia do que o modo não multicast."</string>
+    <string name="permdesc_changeWifiMulticastState" product="tv" msgid="9031975661145014160">"Permite que o app receba pacotes enviados para todos os dispositivos em uma rede Wi-Fi usando endereços multicast, não apenas sua TV. Usa mais energia do que o modo não multicast."</string>
+    <string name="permdesc_changeWifiMulticastState" product="default" msgid="6851949706025349926">"Permite que o app receba pacotes enviados para todos os dispositivos em uma rede Wi-Fi usando endereços de difusão seletiva, e não apenas o telefone. Consome mais energia do que o modo não multicast."</string>
+    <string name="permlab_bluetoothAdmin" msgid="6006967373935926659">"acessar configurações de Bluetooth"</string>
+    <string name="permdesc_bluetoothAdmin" product="tablet" msgid="6921177471748882137">"Permite que um app configure o tablet Bluetooth local, descubra dispositivos remotos e emparelhe com eles."</string>
+    <string name="permdesc_bluetoothAdmin" product="tv" msgid="3373125682645601429">"Permite que o app configure a TV com Bluetooth local, descubra dispositivos remotos e faça pareamento com eles."</string>
+    <string name="permdesc_bluetoothAdmin" product="default" msgid="8931682159331542137">"Permite que um app configure o telefone Bluetooth local, descubra e emparelhe com dispositivos remotos."</string>
+    <string name="permlab_accessWimaxState" msgid="4195907010610205703">"conectar e desconectar do WiMAX"</string>
+    <string name="permdesc_accessWimaxState" msgid="6360102877261978887">"Permite que o app determine se o WiMAX está ativado e acesse informações sobre as redes WiMAX conectadas."</string>
+    <string name="permlab_changeWimaxState" msgid="2405042267131496579">"Alterar estado do WiMAX"</string>
+    <string name="permdesc_changeWimaxState" product="tablet" msgid="3156456504084201805">"Permite que o app conecte e desconecte o tablet de redes WiMAX."</string>
+    <string name="permdesc_changeWimaxState" product="tv" msgid="6022307083934827718">"Permite que o app se conecte à TV e desconecte-a de redes WiMAX."</string>
+    <string name="permdesc_changeWimaxState" product="default" msgid="697025043004923798">"Permite que o app conecte e desconecte o telefone de redes WiMAX."</string>
+    <string name="permlab_bluetooth" msgid="6127769336339276828">"parear com dispositivos Bluetooth"</string>
+    <string name="permdesc_bluetooth" product="tablet" msgid="3480722181852438628">"Permite que o app acesse a configuração do Bluetooth no tablet, além de fazer e aceitar conexões com dispositivos pareados."</string>
+    <string name="permdesc_bluetooth" product="tv" msgid="3974124940101104206">"Permite que o app veja a configuração do Bluetooth na TV, faça e aceite conexões com dispositivos pareados."</string>
+    <string name="permdesc_bluetooth" product="default" msgid="3207106324452312739">"Permite que o app acesse a configuração do Bluetooth no telefone, além de fazer e aceitar conexões com dispositivos pareados."</string>
+    <string name="permlab_nfc" msgid="4423351274757876953">"controlar a comunicação a curta distância"</string>
+    <string name="permdesc_nfc" msgid="7120611819401789907">"Permite que o app se comunique com leitores, cartões e etiqueta NFC (Comunicação a curta distância)."</string>
+    <string name="permlab_disableKeyguard" msgid="3598496301486439258">"desativar o bloqueio de tela"</string>
+    <string name="permdesc_disableKeyguard" msgid="6034203065077122992">"Permite que o app desative o bloqueio de teclas e qualquer segurança por senha associada. Por exemplo, o telefone desativa o bloqueio de telas ao receber uma chamada e o reativa quando a chamada é finalizada."</string>
+    <string name="permlab_manageFingerprint" msgid="5640858826254575638">"gerenciar hardware de impressão digital"</string>
+    <string name="permdesc_manageFingerprint" msgid="178208705828055464">"Permite que o app execute métodos para adicionar e excluir modelos de impressão digital para uso."</string>
+    <string name="permlab_useFingerprint" msgid="3150478619915124905">"usar hardware de impressão digital"</string>
+    <string name="permdesc_useFingerprint" msgid="9165097460730684114">"Permite que o app use hardware de impressão digital para autenticação."</string>
+    <string name="fingerprint_acquired_partial" msgid="735082772341716043">"Impressão digital parcial detectada. Tente novamente."</string>
+    <string name="fingerprint_acquired_insufficient" msgid="4596546021310923214">"Não foi possível processar a impressão digital. Tente novamente."</string>
+    <string name="fingerprint_acquired_imager_dirty" msgid="1087209702421076105">"O sensor de impressão digital está sujo. Limpe-o e tente novamente."</string>
+    <string name="fingerprint_acquired_too_fast" msgid="6470642383109155969">"O dedo foi retirado rápido demais. Tente novamente."</string>
+    <string name="fingerprint_acquired_too_slow" msgid="59250885689661653">"O movimento do dedo está muito lento. Tente novamente."</string>
+  <string-array name="fingerprint_acquired_vendor">
+  </string-array>
+    <string name="fingerprint_error_hw_not_available" msgid="7955921658939936596">"Hardware de impressão digital não disponível."</string>
+    <string name="fingerprint_error_no_space" msgid="1055819001126053318">"Não foi possível armazenar a impressão digital. Remova uma impressão digital já existente."</string>
+    <string name="fingerprint_error_timeout" msgid="3927186043737732875">"Tempo máximo para captura da impressão digital atingido. Tente novamente."</string>
+    <string name="fingerprint_error_canceled" msgid="4402024612660774395">"Operação de impressão digital cancelada."</string>
+    <string name="fingerprint_error_lockout" msgid="5536934748136933450">"Excesso de tentativas. Tente novamente mais tarde."</string>
+    <string name="fingerprint_error_unable_to_process" msgid="6107816084103552441">"Tente novamente."</string>
+    <string name="fingerprint_name_template" msgid="5870957565512716938">"Dedo <xliff:g id="FINGERID">%d</xliff:g>"</string>
+  <string-array name="fingerprint_error_vendor">
+  </string-array>
+    <string name="permlab_readSyncSettings" msgid="6201810008230503052">"ler as configurações de sincronização"</string>
+    <string name="permdesc_readSyncSettings" msgid="2706745674569678644">"Permite que o app leia as configurações de sincronização de uma conta. Por exemplo, pode determinar se o app People está sincronizado com uma conta."</string>
+    <string name="permlab_writeSyncSettings" msgid="5408694875793945314">"ativar e desativar sincronização"</string>
+    <string name="permdesc_writeSyncSettings" msgid="8956262591306369868">"Permite que o app modifique as configurações de sincronização de uma conta. Por exemplo, pode ser usado para ativar a sincronização do app People com uma conta."</string>
+    <string name="permlab_readSyncStats" msgid="7396577451360202448">"ler estatísticas de sincronização"</string>
+    <string name="permdesc_readSyncStats" msgid="1510143761757606156">"Permite que um app acesse as estatísticas de sincronização de uma conta, incluindo a história dos eventos de sincronização e a quantidade de dados sincronizados."</string>
+    <string name="permlab_sdcardRead" product="nosdcard" msgid="367275095159405468">"ler conteúdo do armaz. USB"</string>
+    <string name="permlab_sdcardRead" product="default" msgid="2188156462934977940">"ler conteúdo do cartão SD"</string>
+    <string name="permdesc_sdcardRead" product="nosdcard" msgid="3446988712598386079">"Perm. que app leia cartão SD."</string>
+    <string name="permdesc_sdcardRead" product="default" msgid="2607362473654975411">"Permite que o app leia o conteúdo do cartão SD."</string>
+    <string name="permlab_sdcardWrite" product="nosdcard" msgid="8485979062254666748">"modificar ou excluir conteúdo do armazenamento USB"</string>
+    <string name="permlab_sdcardWrite" product="default" msgid="8805693630050458763">"modificar ou excluir o conteúdo do cartão SD"</string>
+    <string name="permdesc_sdcardWrite" product="nosdcard" msgid="6175406299445710888">"Permite gravar no armaz. USB."</string>
+    <string name="permdesc_sdcardWrite" product="default" msgid="4337417790936632090">"Permite que o app grave em seu cartão SD."</string>
+    <string name="permlab_use_sip" msgid="2052499390128979920">"fazer/receber chamadas SIP"</string>
+    <string name="permdesc_use_sip" msgid="2297804849860225257">"Permite que o app faça e receba chamadas SIP."</string>
+    <string name="permlab_register_sim_subscription" msgid="3166535485877549177">"registrar novas conexões SIM de telecomunicações"</string>
+    <string name="permdesc_register_sim_subscription" msgid="2138909035926222911">"Permite que o app registre novas conexões SIM de telecomunicações."</string>
+    <string name="permlab_register_call_provider" msgid="108102120289029841">"registrar novas conexões de telecomunicações"</string>
+    <string name="permdesc_register_call_provider" msgid="7034310263521081388">"Permite que o app registre novas conexões de telecomunicações."</string>
+    <string name="permlab_connection_manager" msgid="1116193254522105375">"gerenciar conexões de telecomunicações"</string>
+    <string name="permdesc_connection_manager" msgid="5925480810356483565">"Permite que o app gerencie conexões de telecomunicações."</string>
+    <string name="permlab_bind_incall_service" msgid="6773648341975287125">"interagir com chamada na tela"</string>
+    <string name="permdesc_bind_incall_service" msgid="8343471381323215005">"Permite que o app controle quando e como o usuário visualiza a chamada na tela."</string>
+    <string name="permlab_bind_connection_service" msgid="3557341439297014940">"interagir com os serviços de telefonia"</string>
+    <string name="permdesc_bind_connection_service" msgid="4008754499822478114">"Permite ao app interagir com os serviços de telefonia para fazer/receber chamadas."</string>
+    <string name="permlab_control_incall_experience" msgid="9061024437607777619">"fornecer uma experiência de usuário em chamada"</string>
+    <string name="permdesc_control_incall_experience" msgid="915159066039828124">"Permite ao app fornecer uma experiência de usuário em chamada."</string>
+    <string name="permlab_readNetworkUsageHistory" msgid="7862593283611493232">"ler histórico de uso da rede"</string>
+    <string name="permdesc_readNetworkUsageHistory" msgid="7689060749819126472">"Permite que o app leia o histórico de uso da rede para redes e apps específicos."</string>
+    <string name="permlab_manageNetworkPolicy" msgid="2562053592339859990">"gerenciar a política de rede"</string>
+    <string name="permdesc_manageNetworkPolicy" msgid="7537586771559370668">"Permite que o app gerencie políticas de rede e definia regras específicas para o app."</string>
+    <string name="permlab_modifyNetworkAccounting" msgid="5088217309088729650">"modificar contagem de uso da rede"</string>
+    <string name="permdesc_modifyNetworkAccounting" msgid="5443412866746198123">"Permite que o app modifique como o uso da rede é contabilizado em relação aos apps. Não deve ser usado em apps normais."</string>
+    <string name="permlab_accessNotifications" msgid="7673416487873432268">"acessar notificações"</string>
+    <string name="permdesc_accessNotifications" msgid="458457742683431387">"Permite que o app recupere, examine e limpe notificações, inclusive as postadas por outros apps."</string>
+    <string name="permlab_bindNotificationListenerService" msgid="7057764742211656654">"sujeitar a um serviço ouvinte de notificações"</string>
+    <string name="permdesc_bindNotificationListenerService" msgid="985697918576902986">"Permite que o proprietário sujeite a interface de nível superior a um serviço ouvinte de notificações. Não deve ser necessário para apps comuns."</string>
+    <string name="permlab_bindConditionProviderService" msgid="1180107672332704641">"associar a um serviço provedor de condições"</string>
+    <string name="permdesc_bindConditionProviderService" msgid="1680513931165058425">"Permite que o proprietário use a interface de nível superior de um serviço provedor de condições. Não deve ser necessário para apps comuns."</string>
+    <string name="permlab_bindDreamService" msgid="4153646965978563462">"conectar-se a um serviço de sonho"</string>
+    <string name="permdesc_bindDreamService" msgid="7325825272223347863">"Permite que o sistema autorizado se conecte à interface de nível superior de um serviço de sonho. Não deve ser necessário para apps comuns."</string>
+    <string name="permlab_invokeCarrierSetup" msgid="3699600833975117478">"invocar o app de configuração fornecido pela operadora"</string>
+    <string name="permdesc_invokeCarrierSetup" msgid="4159549152529111920">"Permite que o proprietário invoque o app de configuração fornecido pela operadora. Não deve ser necessário para apps comuns."</string>
+    <string name="permlab_accessNetworkConditions" msgid="8206077447838909516">"detectar observações nas condições da rede"</string>
+    <string name="permdesc_accessNetworkConditions" msgid="6899102075825272211">"Permite que o app detecte observações nas condições da rede. Não deve ser necessário para apps comuns."</string>
+    <string name="permlab_setInputCalibration" msgid="4902620118878467615">"alterar calibragem do dispositivo de entrada"</string>
+    <string name="permdesc_setInputCalibration" msgid="4527511047549456929">"Permite que o app modifique os parâmetros de calibragem da tela sensível ao toque. Não deve ser necessário para apps normais."</string>
+    <string name="permlab_accessDrmCertificates" msgid="7436886640723203615">"acessar certificados de DRM"</string>
+    <string name="permdesc_accessDrmCertificates" msgid="8073288354426159089">"Permite que o app provisione e use certificados de DRM. Não deve ser necessário para apps comuns."</string>
+    <string name="permlab_handoverStatus" msgid="1159132046126626731">"Receber status de transferência do Android Beam"</string>
+    <string name="permdesc_handoverStatus" msgid="4788144087245714948">"Permite que este app receba informações sobre as atuais transferências do Android Beam"</string>
+    <string name="permlab_removeDrmCertificates" msgid="7044888287209892751">"remover certificados de DRM"</string>
+    <string name="permdesc_removeDrmCertificates" msgid="7272999075113400993">"Permite que um app remova certificados de DRM. Não deve ser necessário para apps comuns."</string>
+    <string name="permlab_bindCarrierMessagingService" msgid="1490229371796969158">"vincular a um serviço de mensagens de operadora"</string>
+    <string name="permdesc_bindCarrierMessagingService" msgid="2762882888502113944">"Permite que o proprietário use a interface de nível superior de um serviço de mensagens de operadora. Não deve ser necessária para apps comuns."</string>
+    <string name="permlab_bindCarrierServices" msgid="3233108656245526783">"vincular a serviços de operadora"</string>
+    <string name="permdesc_bindCarrierServices" msgid="1391552602551084192">"Permite que o proprietário use serviços de operadora. Não deve ser necessário para apps comuns."</string>
+    <string name="permlab_access_notification_policy" msgid="4247510821662059671">"acessar \"Não perturbe\""</string>
+    <string name="permdesc_access_notification_policy" msgid="3296832375218749580">"Permitir que o app leia e grave a configuração \"Não perturbe\"."</string>
+    <string name="policylab_limitPassword" msgid="4497420728857585791">"Definir regras para senha"</string>
+    <string name="policydesc_limitPassword" msgid="2502021457917874968">"Controla o tamanho e os caracteres permitidos nos PINs e nas senhas do bloqueio de tela."</string>
+    <string name="policylab_watchLogin" msgid="914130646942199503">"Monitorar tentativas de desbloqueio da tela"</string>
+    <string name="policydesc_watchLogin" product="tablet" msgid="3215729294215070072">"Monitorar quantas vezes a senha foi digitada incorretamente ao desbloquear a tela e bloquear o tablet ou apagar todos os dados do tablet se a senha for digitada incorretamente muitas vezes."</string>
+    <string name="policydesc_watchLogin" product="TV" msgid="2707817988309890256">"Monitora o número de senhas incorretas digitadas ao desbloquear a tela e bloqueia a TV ou apagar todos os dados dela se muitas senhas incorretas forem digitadas."</string>
+    <string name="policydesc_watchLogin" product="default" msgid="5712323091846761073">"Monitorar quantas vezes a senha foi digitada incorretamente ao desbloquear a tela e bloquear o telefone ou apagar todos os dados do telefone se a senha for digitada incorretamente muitas vezes."</string>
+    <string name="policydesc_watchLogin_secondaryUser" product="tablet" msgid="4280246270601044505">"Monitora o número de senhas incorretas digitadas ao desbloquear a tela e bloqueia o tablet ou limpa todos os dados do usuário se muitas senhas incorretas forem digitadas."</string>
+    <string name="policydesc_watchLogin_secondaryUser" product="TV" msgid="3484832653564483250">"Monitora o número de senhas incorretas digitadas ao desbloquear a tela e bloqueia a TV ou limpa todos os dados do usuário se muitas senhas incorretas forem digitadas."</string>
+    <string name="policydesc_watchLogin_secondaryUser" product="default" msgid="2185480427217127147">"Monitora o número de senhas incorretas digitadas ao desbloquear a tela e bloqueia o smartphone ou limpa todos os dados do usuário se muitas senhas incorretas forem digitadas."</string>
+    <string name="policylab_resetPassword" msgid="4934707632423915395">"Alterar o bloqueio de tela"</string>
+    <string name="policydesc_resetPassword" msgid="1278323891710619128">"Altera o bloqueio de tela."</string>
+    <string name="policylab_forceLock" msgid="2274085384704248431">"Bloquear a tela"</string>
+    <string name="policydesc_forceLock" msgid="1141797588403827138">"Controlar como e quando a tela é bloqueada."</string>
+    <string name="policylab_wipeData" msgid="3910545446758639713">"Apagar todos os dados"</string>
+    <string name="policydesc_wipeData" product="tablet" msgid="4306184096067756876">"Apague os dados do tablet sem aviso redefinindo a configuração original."</string>
+    <string name="policydesc_wipeData" product="tv" msgid="5816221315214527028">"Apaga dados da TV sem aviso, fazendo uma redefinição para configuração original."</string>
+    <string name="policydesc_wipeData" product="default" msgid="5096895604574188391">"Apagar os dados do telefone sem aviso redefinindo a configuração original."</string>
+    <string name="policylab_wipeData_secondaryUser" msgid="8362863289455531813">"Limpar dados do usuário"</string>
+    <string name="policydesc_wipeData_secondaryUser" product="tablet" msgid="6336255514635308054">"Limpa os dados do usuário neste tablet sem aviso prévio."</string>
+    <string name="policydesc_wipeData_secondaryUser" product="tv" msgid="2086473496848351810">"Limpa os dados do usuário nesta TV sem aviso prévio."</string>
+    <string name="policydesc_wipeData_secondaryUser" product="default" msgid="6787904546711590238">"Limpa os dados do usuário neste smartphone sem aviso prévio."</string>
+    <string name="policylab_setGlobalProxy" msgid="2784828293747791446">"Definir o proxy global do dispositivo"</string>
+    <string name="policydesc_setGlobalProxy" msgid="8459859731153370499">"Configura o proxy global do dispositivo para ser usado enquanto a política está ativada. Somente o proprietário do dispositivo pode definir o proxy global."</string>
+    <string name="policylab_expirePassword" msgid="5610055012328825874">"Definir expiração da senha de bloqueio de tela"</string>
+    <string name="policydesc_expirePassword" msgid="5367525762204416046">"Altera a frequência com que o PIN, a senha ou o padrão do bloqueio de tela deve ser alterado."</string>
+    <string name="policylab_encryptedStorage" msgid="8901326199909132915">"Definir criptografia de armazenamento"</string>
+    <string name="policydesc_encryptedStorage" msgid="2637732115325316992">"Exija que os dados armazenados do app sejam criptografados."</string>
+    <string name="policylab_disableCamera" msgid="6395301023152297826">"Desativar câmeras"</string>
+    <string name="policydesc_disableCamera" msgid="2306349042834754597">"Impeça o uso de todas as câmeras do dispositivo."</string>
+    <string name="policylab_disableKeyguardFeatures" msgid="8552277871075367771">"Desat. recursos bloq. de tela"</string>
+    <string name="policydesc_disableKeyguardFeatures" msgid="2044755691354158439">"Impede o uso de alguns recursos do bloqueio de tela."</string>
+  <string-array name="phoneTypes">
+    <item msgid="8901098336658710359">"Residencial"</item>
+    <item msgid="869923650527136615">"Celular"</item>
+    <item msgid="7897544654242874543">"Trabalho"</item>
+    <item msgid="1103601433382158155">"Fax do trabalho"</item>
+    <item msgid="1735177144948329370">"Fax doméstico"</item>
+    <item msgid="603878674477207394">"Pager"</item>
+    <item msgid="1650824275177931637">"Outros"</item>
+    <item msgid="9192514806975898961">"Personalizado"</item>
+  </string-array>
+  <string-array name="emailAddressTypes">
+    <item msgid="8073994352956129127">"Residencial"</item>
+    <item msgid="7084237356602625604">"Trabalho"</item>
+    <item msgid="1112044410659011023">"Outros"</item>
+    <item msgid="2374913952870110618">"Personalizado"</item>
+  </string-array>
+  <string-array name="postalAddressTypes">
+    <item msgid="6880257626740047286">"Residencial"</item>
+    <item msgid="5629153956045109251">"Trabalho"</item>
+    <item msgid="4966604264500343469">"Outros"</item>
+    <item msgid="4932682847595299369">"Personalizado"</item>
+  </string-array>
+  <string-array name="imAddressTypes">
+    <item msgid="1738585194601476694">"Residencial"</item>
+    <item msgid="1359644565647383708">"Trabalho"</item>
+    <item msgid="7868549401053615677">"Outros"</item>
+    <item msgid="3145118944639869809">"Personalizado"</item>
+  </string-array>
+  <string-array name="organizationTypes">
+    <item msgid="7546335612189115615">"Trabalho"</item>
+    <item msgid="4378074129049520373">"Outros"</item>
+    <item msgid="3455047468583965104">"Personalizado"</item>
+  </string-array>
+  <string-array name="imProtocols">
+    <item msgid="8595261363518459565">"AIM"</item>
+    <item msgid="7390473628275490700">"Windows Live"</item>
+    <item msgid="7882877134931458217">"Yahoo"</item>
+    <item msgid="5035376313200585242">"Skype"</item>
+    <item msgid="7532363178459444943">"QQ"</item>
+    <item msgid="3713441034299660749">"Google Talk"</item>
+    <item msgid="2506857312718630823">"ICQ"</item>
+    <item msgid="1648797903785279353">"Jabber"</item>
+  </string-array>
+    <string name="phoneTypeCustom" msgid="1644738059053355820">"Personalizado"</string>
+    <string name="phoneTypeHome" msgid="2570923463033985887">"Residencial"</string>
+    <string name="phoneTypeMobile" msgid="6501463557754751037">"Celular"</string>
+    <string name="phoneTypeWork" msgid="8863939667059911633">"Comercial"</string>
+    <string name="phoneTypeFaxWork" msgid="3517792160008890912">"Fax comercial"</string>
+    <string name="phoneTypeFaxHome" msgid="2067265972322971467">"Fax residencial"</string>
+    <string name="phoneTypePager" msgid="7582359955394921732">"Pager"</string>
+    <string name="phoneTypeOther" msgid="1544425847868765990">"Outros"</string>
+    <string name="phoneTypeCallback" msgid="2712175203065678206">"Retorno de chamada"</string>
+    <string name="phoneTypeCar" msgid="8738360689616716982">"Carro"</string>
+    <string name="phoneTypeCompanyMain" msgid="540434356461478916">"Empresa (principal)"</string>
+    <string name="phoneTypeIsdn" msgid="8022453193171370337">"ISDN"</string>
+    <string name="phoneTypeMain" msgid="6766137010628326916">"Principal"</string>
+    <string name="phoneTypeOtherFax" msgid="8587657145072446565">"Outro fax"</string>
+    <string name="phoneTypeRadio" msgid="4093738079908667513">"Rádio"</string>
+    <string name="phoneTypeTelex" msgid="3367879952476250512">"Telex"</string>
+    <string name="phoneTypeTtyTdd" msgid="8606514378585000044">"TTY TDD"</string>
+    <string name="phoneTypeWorkMobile" msgid="1311426989184065709">"Celular comercial"</string>
+    <string name="phoneTypeWorkPager" msgid="649938731231157056">"Pager comercial"</string>
+    <string name="phoneTypeAssistant" msgid="5596772636128562884">"Assistente"</string>
+    <string name="phoneTypeMms" msgid="7254492275502768992">"MMS"</string>
+    <string name="eventTypeCustom" msgid="7837586198458073404">"Personalizado"</string>
+    <string name="eventTypeBirthday" msgid="2813379844211390740">"Aniversário"</string>
+    <string name="eventTypeAnniversary" msgid="3876779744518284000">"Data comemorativa"</string>
+    <string name="eventTypeOther" msgid="7388178939010143077">"Outros"</string>
+    <string name="emailTypeCustom" msgid="8525960257804213846">"Personalizado"</string>
+    <string name="emailTypeHome" msgid="449227236140433919">"Residencial"</string>
+    <string name="emailTypeWork" msgid="3548058059601149973">"Comercial"</string>
+    <string name="emailTypeOther" msgid="2923008695272639549">"Outros"</string>
+    <string name="emailTypeMobile" msgid="119919005321166205">"Celular"</string>
+    <string name="postalTypeCustom" msgid="8903206903060479902">"Personalizado"</string>
+    <string name="postalTypeHome" msgid="8165756977184483097">"Residencial"</string>
+    <string name="postalTypeWork" msgid="5268172772387694495">"Comercial"</string>
+    <string name="postalTypeOther" msgid="2726111966623584341">"Outros"</string>
+    <string name="imTypeCustom" msgid="2074028755527826046">"Personalizado"</string>
+    <string name="imTypeHome" msgid="6241181032954263892">"Residencial"</string>
+    <string name="imTypeWork" msgid="1371489290242433090">"Comercial"</string>
+    <string name="imTypeOther" msgid="5377007495735915478">"Outros"</string>
+    <string name="imProtocolCustom" msgid="6919453836618749992">"Personalizado"</string>
+    <string name="imProtocolAim" msgid="7050360612368383417">"AIM"</string>
+    <string name="imProtocolMsn" msgid="144556545420769442">"Windows Live"</string>
+    <string name="imProtocolYahoo" msgid="8271439408469021273">"Yahoo"</string>
+    <string name="imProtocolSkype" msgid="9019296744622832951">"Skype"</string>
+    <string name="imProtocolQq" msgid="8887484379494111884">"QQ"</string>
+    <string name="imProtocolGoogleTalk" msgid="493902321140277304">"Hangouts"</string>
+    <string name="imProtocolIcq" msgid="1574870433606517315">"ICQ"</string>
+    <string name="imProtocolJabber" msgid="2279917630875771722">"Jabber"</string>
+    <string name="imProtocolNetMeeting" msgid="8287625655986827971">"NetMeeting"</string>
+    <string name="orgTypeWork" msgid="29268870505363872">"Comercial"</string>
+    <string name="orgTypeOther" msgid="3951781131570124082">"Outros"</string>
+    <string name="orgTypeCustom" msgid="225523415372088322">"Personalizado"</string>
+    <string name="relationTypeCustom" msgid="3542403679827297300">"Personalizado"</string>
+    <string name="relationTypeAssistant" msgid="6274334825195379076">"Assistente"</string>
+    <string name="relationTypeBrother" msgid="8757913506784067713">"Irmão"</string>
+    <string name="relationTypeChild" msgid="1890746277276881626">"Filho(a)"</string>
+    <string name="relationTypeDomesticPartner" msgid="6904807112121122133">"Parceiro doméstico"</string>
+    <string name="relationTypeFather" msgid="5228034687082050725">"Pai"</string>
+    <string name="relationTypeFriend" msgid="7313106762483391262">"Amigo(a)"</string>
+    <string name="relationTypeManager" msgid="6365677861610137895">"Gerente"</string>
+    <string name="relationTypeMother" msgid="4578571352962758304">"Mãe"</string>
+    <string name="relationTypeParent" msgid="4755635567562925226">"Pai/Mãe"</string>
+    <string name="relationTypePartner" msgid="7266490285120262781">"Parceiro"</string>
+    <string name="relationTypeReferredBy" msgid="101573059844135524">"Indicado por"</string>
+    <string name="relationTypeRelative" msgid="1799819930085610271">"Parente"</string>
+    <string name="relationTypeSister" msgid="1735983554479076481">"Irmã"</string>
+    <string name="relationTypeSpouse" msgid="394136939428698117">"Cônjuge"</string>
+    <string name="sipAddressTypeCustom" msgid="2473580593111590945">"Personalizado"</string>
+    <string name="sipAddressTypeHome" msgid="6093598181069359295">"Página inicial"</string>
+    <string name="sipAddressTypeWork" msgid="6920725730797099047">"Comercial"</string>
+    <string name="sipAddressTypeOther" msgid="4408436162950119849">"Outros"</string>
+    <string name="quick_contacts_not_available" msgid="746098007828579688">"Nenhum app encontrado para visualizar este contato."</string>
+    <string name="keyguard_password_enter_pin_code" msgid="3037685796058495017">"Insira o código PIN"</string>
+    <string name="keyguard_password_enter_puk_code" msgid="4800725266925845333">"Insira o PUK e o novo código PIN"</string>
+    <string name="keyguard_password_enter_puk_prompt" msgid="1341112146710087048">"Código PUK"</string>
+    <string name="keyguard_password_enter_pin_prompt" msgid="8027680321614196258">"Novo código PIN"</string>
+    <string name="keyguard_password_entry_touch_hint" msgid="7858547464982981384"><font size="17">"Toque para inserir a senha"</font></string>
+    <string name="keyguard_password_enter_password_code" msgid="1054721668279049780">"Digite a senha para desbloquear"</string>
+    <string name="keyguard_password_enter_pin_password_code" msgid="6391755146112503443">"Insira o PIN para desbloquear"</string>
+    <string name="keyguard_password_wrong_pin_code" msgid="2422225591006134936">"Código PIN incorreto."</string>
+    <string name="keyguard_label_text" msgid="861796461028298424">"Para desbloquear, pressione Menu e, em seguida, 0."</string>
+    <string name="emergency_call_dialog_number_for_display" msgid="696192103195090970">"Número de emergência"</string>
+    <string name="lockscreen_carrier_default" msgid="8963839242565653192">"Sem serviço."</string>
+    <string name="lockscreen_screen_locked" msgid="7288443074806832904">"Tela bloqueada."</string>
+    <string name="lockscreen_instructions_when_pattern_enabled" msgid="46154051614126049">"Pressione Menu para desbloquear ou fazer uma chamada de emergência."</string>
+    <string name="lockscreen_instructions_when_pattern_disabled" msgid="686260028797158364">"Pressione Menu para desbloquear."</string>
+    <string name="lockscreen_pattern_instructions" msgid="7478703254964810302">"Desenhe o padrão para desbloquear"</string>
+    <string name="lockscreen_emergency_call" msgid="5298642613417801888">"Emergência"</string>
+    <string name="lockscreen_return_to_call" msgid="5244259785500040021">"Retornar à chamada"</string>
+    <string name="lockscreen_pattern_correct" msgid="9039008650362261237">"Correto!"</string>
+    <string name="lockscreen_pattern_wrong" msgid="4317955014948108794">"Tente novamente"</string>
+    <string name="lockscreen_password_wrong" msgid="5737815393253165301">"Tente novamente"</string>
+    <string name="faceunlock_multiple_failures" msgid="754137583022792429">"O número máximo de tentativas de Desbloqueio por reconhecimento facial foi excedido"</string>
+    <string name="lockscreen_missing_sim_message_short" msgid="5099439277819215399">"Sem cartão SIM"</string>
+    <string name="lockscreen_missing_sim_message" product="tablet" msgid="151659196095791474">"Não há um cartão SIM no tablet."</string>
+    <string name="lockscreen_missing_sim_message" product="tv" msgid="1943633865476989599">"Nenhum cartão SIM na TV."</string>
+    <string name="lockscreen_missing_sim_message" product="default" msgid="2186920585695169078">"Não há um cartão SIM no telefone."</string>
+    <string name="lockscreen_missing_sim_instructions" msgid="5372787138023272615">"Insera um cartão SIM."</string>
+    <string name="lockscreen_missing_sim_instructions_long" msgid="3526573099019319472">"O cartão SIM não foi inserido ou não é possível lê-lo. Insira um cartão SIM."</string>
+    <string name="lockscreen_permanent_disabled_sim_message_short" msgid="5096149665138916184">"Cartão SIM inutilizável."</string>
+    <string name="lockscreen_permanent_disabled_sim_instructions" msgid="910904643433151371">"O cartão SIM foi desativado permanentemente.\nEntre em contato com seu provedor de serviços sem fio para obter outro cartão SIM."</string>
+    <string name="lockscreen_transport_prev_description" msgid="6300840251218161534">"Faixa anterior"</string>
+    <string name="lockscreen_transport_next_description" msgid="573285210424377338">"Próxima faixa"</string>
+    <string name="lockscreen_transport_pause_description" msgid="3980308465056173363">"Pausar"</string>
+    <string name="lockscreen_transport_play_description" msgid="1901258823643886401">"Reproduzir"</string>
+    <string name="lockscreen_transport_stop_description" msgid="5907083260651210034">"Parar"</string>
+    <string name="lockscreen_transport_rew_description" msgid="6944412838651990410">"Retroceder"</string>
+    <string name="lockscreen_transport_ffw_description" msgid="42987149870928985">"Avançar"</string>
+    <string name="emergency_calls_only" msgid="6733978304386365407">"Só chamadas de emergência"</string>
+    <string name="lockscreen_network_locked_message" msgid="143389224986028501">"Rede bloqueada"</string>
+    <string name="lockscreen_sim_puk_locked_message" msgid="7441797339976230">"O cartão SIM está bloqueado pelo PUK."</string>
+    <string name="lockscreen_sim_puk_locked_instructions" msgid="8127916255245181063">"Consulte o Guia do usuário ou entre em contato com o Serviço de atendimento ao cliente."</string>
+    <string name="lockscreen_sim_locked_message" msgid="8066660129206001039">"O cartão SIM está bloqueado."</string>
+    <string name="lockscreen_sim_unlock_progress_dialog_message" msgid="595323214052881264">"Desbloqueando o cartão SIM…"</string>
+    <string name="lockscreen_too_many_failed_attempts_dialog_message" msgid="6481623830344107222">"Você desenhou seu padrão de desbloqueio incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes. \n\nTente novamente em <xliff:g id="NUMBER_1">%d</xliff:g> segundos."</string>
+    <string name="lockscreen_too_many_failed_password_attempts_dialog_message" msgid="2725973286239344555">"Você digitou sua senha incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes. \n\nTente novamente em <xliff:g id="NUMBER_1">%d</xliff:g> segundos."</string>
+    <string name="lockscreen_too_many_failed_pin_attempts_dialog_message" msgid="6216672706545696955">"Você digitou seu PIN incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes.\n\nTente novamente em <xliff:g id="NUMBER_1">%d</xliff:g> segundos."</string>
+    <string name="lockscreen_failed_attempts_almost_glogin" product="tablet" msgid="9191611984625460820">"Você desenhou sua sequência de desbloqueio incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Se fizer mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas incorretas, será solicitado que você use o login do Google para desbloquear seu tablet.\n\n Tente novamente em <xliff:g id="NUMBER_2">%d</xliff:g> segundos."</string>
+    <string name="lockscreen_failed_attempts_almost_glogin" product="tv" msgid="5316664559603394684">"Você desenhou seu padrão de desbloqueio incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Depois de mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas sem sucesso, será pedido que você desbloqueie sua TV usando seu login do Google.\n\n Tente novamente em <xliff:g id="NUMBER_2">%d</xliff:g> segundos."</string>
+    <string name="lockscreen_failed_attempts_almost_glogin" product="default" msgid="2590227559763762751">"Você desenhou sua sequência de desbloqueio incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Se fizer mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas incorretas, será solicitado que você use o login do Google para desbloquear.\n\n Tente novamente em <xliff:g id="NUMBER_2">%d</xliff:g> segundos."</string>
+    <string name="lockscreen_failed_attempts_almost_at_wipe" product="tablet" msgid="6128106399745755604">"Você tentou desbloquear incorretamente o tablet <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Após mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas malsucedidas, o tablet será redefinido para o padrão de fábrica e todos os dados do usuário serão perdidos."</string>
+    <string name="lockscreen_failed_attempts_almost_at_wipe" product="tv" msgid="950408382418270260">"Você tentou desbloquear a TV de forma incorreta <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Depois de mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas sem sucesso, a TV será redefinida para os padrões de fábrica e todos os dados do usuário serão perdidos."</string>
+    <string name="lockscreen_failed_attempts_almost_at_wipe" product="default" msgid="8603565142156826565">"Você tentou desbloquear incorretamente o telefone <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Após mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas malsucedidas, o telefone será redefinido para o padrão de fábrica e todos os dados do usuário serão perdidos."</string>
+    <string name="lockscreen_failed_attempts_now_wiping" product="tablet" msgid="280873516493934365">"Você tentou desbloquear incorretamente o tablet <xliff:g id="NUMBER">%d</xliff:g> vezes. O tablet será redefinido para o padrão de fábrica."</string>
+    <string name="lockscreen_failed_attempts_now_wiping" product="tv" msgid="3195755534096192191">"Você tentou desbloquear a TV de forma incorreta <xliff:g id="NUMBER">%d</xliff:g> vezes. A TV será redefinida agora para os padrões de fábrica."</string>
+    <string name="lockscreen_failed_attempts_now_wiping" product="default" msgid="3025504721764922246">"Você tentou desbloquear incorretamente o telefone <xliff:g id="NUMBER">%d</xliff:g> vezes. O telefone será redefinido para o padrão de fábrica."</string>
+    <string name="lockscreen_too_many_failed_attempts_countdown" msgid="6251480343394389665">"Tente novamente em <xliff:g id="NUMBER">%d</xliff:g> segundos."</string>
+    <string name="lockscreen_forgot_pattern_button_text" msgid="2626999449610695930">"Esqueceu o padrão?"</string>
+    <string name="lockscreen_glogin_forgot_pattern" msgid="2588521501166032747">"Desbloqueio de conta"</string>
+    <string name="lockscreen_glogin_too_many_attempts" msgid="2751368605287288808">"Muitas tentativas de padrão"</string>
+    <string name="lockscreen_glogin_instructions" msgid="3931816256100707784">"Para desbloquear, faça login com sua Conta do Google."</string>
+    <string name="lockscreen_glogin_username_hint" msgid="8846881424106484447">"Nome de usuário (e-mail)"</string>
+    <string name="lockscreen_glogin_password_hint" msgid="5958028383954738528">"Senha"</string>
+    <string name="lockscreen_glogin_submit_button" msgid="7130893694795786300">"Fazer login"</string>
+    <string name="lockscreen_glogin_invalid_input" msgid="1364051473347485908">"Nome de usuário ou senha inválidos."</string>
+    <string name="lockscreen_glogin_account_recovery_hint" msgid="1696924763690379073">"Esqueceu seu nome de usuário ou senha?\nAcesse "<b>"google.com.br/accounts/recovery"</b>"."</string>
+    <string name="lockscreen_glogin_checking_password" msgid="7114627351286933867">"Verificando…"</string>
+    <string name="lockscreen_unlock_label" msgid="737440483220667054">"Desbloquear"</string>
+    <string name="lockscreen_sound_on_label" msgid="9068877576513425970">"Som ativado"</string>
+    <string name="lockscreen_sound_off_label" msgid="996822825154319026">"Som desativado"</string>
+    <string name="lockscreen_access_pattern_start" msgid="3941045502933142847">"Padrão iniciado"</string>
+    <string name="lockscreen_access_pattern_cleared" msgid="5583479721001639579">"Padrão apagado"</string>
+    <string name="lockscreen_access_pattern_cell_added" msgid="6756031208359292487">"Célula adicionada"</string>
+    <string name="lockscreen_access_pattern_cell_added_verbose" msgid="7264580781744026939">"Célula <xliff:g id="CELL_INDEX">%1$s</xliff:g> adicionada"</string>
+    <string name="lockscreen_access_pattern_detected" msgid="4988730895554057058">"Padrão concluído"</string>
+    <string name="keyguard_accessibility_widget_changed" msgid="5678624624681400191">"%1$s. Widget %2$d de %3$d."</string>
+    <string name="keyguard_accessibility_add_widget" msgid="8273277058724924654">"Adicionar widget"</string>
+    <string name="keyguard_accessibility_widget_empty_slot" msgid="1281505703307930757">"Vazio"</string>
+    <string name="keyguard_accessibility_unlock_area_expanded" msgid="2278106022311170299">"Área de desbloqueio expandida."</string>
+    <string name="keyguard_accessibility_unlock_area_collapsed" msgid="6366992066936076396">"Área de desbloqueio recolhida."</string>
+    <string name="keyguard_accessibility_widget" msgid="6527131039741808240">"Widget de <xliff:g id="WIDGET_INDEX">%1$s</xliff:g>."</string>
+    <string name="keyguard_accessibility_user_selector" msgid="1226798370913698896">"Seletor de usuários"</string>
+    <string name="keyguard_accessibility_status" msgid="8008264603935930611">"Status"</string>
+    <string name="keyguard_accessibility_camera" msgid="8904231194181114603">"Câmera"</string>
+    <string name="keygaurd_accessibility_media_controls" msgid="262209654292161806">"Controles de mídia"</string>
+    <string name="keyguard_accessibility_widget_reorder_start" msgid="8736853615588828197">"Reordenação de widgets iniciada."</string>
+    <string name="keyguard_accessibility_widget_reorder_end" msgid="7170190950870468320">"Reordenação de widgets concluída."</string>
+    <string name="keyguard_accessibility_widget_deleted" msgid="4426204263929224434">"Widget <xliff:g id="WIDGET_INDEX">%1$s</xliff:g> excluído."</string>
+    <string name="keyguard_accessibility_expand_lock_area" msgid="519859720934178024">"Expandir a área de desbloqueio."</string>
+    <string name="keyguard_accessibility_slide_unlock" msgid="2959928478764697254">"Desbloqueio com deslize."</string>
+    <string name="keyguard_accessibility_pattern_unlock" msgid="1490840706075246612">"Desbloqueio com padrão."</string>
+    <string name="keyguard_accessibility_face_unlock" msgid="4817282543351718535">"Desbloqueio facial."</string>
+    <string name="keyguard_accessibility_pin_unlock" msgid="2469687111784035046">"Desbloqueio com PIN."</string>
+    <string name="keyguard_accessibility_password_unlock" msgid="7675777623912155089">"Desbloqueio com senha."</string>
+    <string name="keyguard_accessibility_pattern_area" msgid="7679891324509597904">"Área do padrão."</string>
+    <string name="keyguard_accessibility_slide_area" msgid="6736064494019979544">"Área de deslize."</string>
+    <string name="password_keyboard_label_symbol_key" msgid="992280756256536042">"?123"</string>
+    <string name="password_keyboard_label_alpha_key" msgid="8001096175167485649">"ABC"</string>
+    <string name="password_keyboard_label_alt_key" msgid="1284820942620288678">"ALT"</string>
+    <string name="granularity_label_character" msgid="7336470535385009523">"caractere"</string>
+    <string name="granularity_label_word" msgid="7075570328374918660">"palavra"</string>
+    <string name="granularity_label_link" msgid="5815508880782488267">"link"</string>
+    <string name="granularity_label_line" msgid="5764267235026120888">"linha"</string>
+    <string name="hour_ampm" msgid="4584338083529355982">"<xliff:g id="HOUR">%-l</xliff:g><xliff:g id="AMPM">%P</xliff:g>"</string>
+    <string name="hour_cap_ampm" msgid="2083465992940444366">"<xliff:g id="HOUR">%-l</xliff:g><xliff:g id="AMPM">%p</xliff:g>"</string>
+    <string name="factorytest_failed" msgid="5410270329114212041">"Falha no teste de fábrica"</string>
+    <string name="factorytest_not_system" msgid="4435201656767276723">"A ação FACTORY_TEST é suportada apenas para pacotes instalados em /system/app."</string>
+    <string name="factorytest_no_action" msgid="872991874799998561">"Nenhum pacote que forneça a ação FACTORY_TEST foi encontrado."</string>
+    <string name="factorytest_reboot" msgid="6320168203050791643">"Reiniciar"</string>
+    <string name="js_dialog_title" msgid="1987483977834603872">"A página em \"<xliff:g id="TITLE">%s</xliff:g>\" diz:"</string>
+    <string name="js_dialog_title_default" msgid="6961903213729667573">"JavaScript"</string>
+    <string name="js_dialog_before_unload_title" msgid="2619376555525116593">"Confirmar navegação"</string>
+    <string name="js_dialog_before_unload_positive_button" msgid="3112752010600484130">"Sair desta página"</string>
+    <string name="js_dialog_before_unload_negative_button" msgid="5614861293026099715">"Permanecer nesta página"</string>
+    <string name="js_dialog_before_unload" msgid="3468816357095378590">"<xliff:g id="MESSAGE">%s</xliff:g>\n\nTem certeza de que deseja sair desta página?"</string>
+    <string name="save_password_label" msgid="6860261758665825069">"Confirmar"</string>
+    <string name="double_tap_toast" msgid="4595046515400268881">"Dica: toque duas vezes para aumentar e diminuir o zoom."</string>
+    <string name="autofill_this_form" msgid="4616758841157816676">"Preench. aut."</string>
+    <string name="setup_autofill" msgid="7103495070180590814">"Conf. preench. aut."</string>
+    <string name="autofill_address_name_separator" msgid="6350145154779706772">" "</string>
+    <string name="autofill_address_summary_name_format" msgid="3268041054899214945">"$1$2$3"</string>
+    <string name="autofill_address_summary_separator" msgid="7483307893170324129">", "</string>
+    <string name="autofill_address_summary_format" msgid="4874459455786827344">"$1$2$3"</string>
+    <string name="autofill_province" msgid="2231806553863422300">"Distrito"</string>
+    <string name="autofill_postal_code" msgid="4696430407689377108">"Código Postal"</string>
+    <string name="autofill_state" msgid="6988894195520044613">"Estado"</string>
+    <string name="autofill_zip_code" msgid="8697544592627322946">"CEP"</string>
+    <string name="autofill_county" msgid="237073771020362891">"Condado"</string>
+    <string name="autofill_island" msgid="4020100875984667025">"Ilha"</string>
+    <string name="autofill_district" msgid="8400735073392267672">"Distrito"</string>
+    <string name="autofill_department" msgid="5343279462564453309">"Departamento"</string>
+    <string name="autofill_prefecture" msgid="2028499485065800419">"Município"</string>
+    <string name="autofill_parish" msgid="8202206105468820057">"Paróquia"</string>
+    <string name="autofill_area" msgid="3547409050889952423">"Área"</string>
+    <string name="autofill_emirate" msgid="2893880978835698818">"Emirado"</string>
+    <string name="permlab_readHistoryBookmarks" msgid="3775265775405106983">"ler seu histórico e seus favoritos da web"</string>
+    <string name="permdesc_readHistoryBookmarks" msgid="8462378226600439658">"Permite que o app leia o histórico de todos os URLs acessados no navegador e todos os favoritos do navegador. Observação: pode não ser aplicável a navegadores de terceiros e outros apps com capacidade de navegação na web."</string>
+    <string name="permlab_writeHistoryBookmarks" msgid="3714785165273314490">"gravar seu histórico e seus favoritos da web"</string>
+    <string name="permdesc_writeHistoryBookmarks" product="tablet" msgid="6825527469145760922">"Permite que o app modifique o histórico ou os favoritos do navegador armazenados no tablet. Pode permitir que o app apague ou modifique os dados do navegador. Observação: pode não ser aplicável a navegadores de terceiros e outros apps com capacidade de navegação na web."</string>
+    <string name="permdesc_writeHistoryBookmarks" product="tv" msgid="7007393823197766548">"Permite que o app modifique o histórico ou os favoritos do navegador armazenados na sua TV. Isso pode permitir que o app apague ou modifique os dados do navegador. Observação: essa autorização pode ser aplicada por navegadores de terceiros ou outros apps com recursos de navegação na Web."</string>
+    <string name="permdesc_writeHistoryBookmarks" product="default" msgid="8497389531014185509">"Permite que o app modifique o histórico ou os favoritos do navegador armazenados no telefone. Pode permitir que o app apague ou modifique os dados do navegador. Observação: pode não ser aplicável a navegadores de terceiros e outros apps com capacidade de navegação na web."</string>
+    <string name="permlab_setAlarm" msgid="1379294556362091814">"definir um alarme"</string>
+    <string name="permdesc_setAlarm" msgid="316392039157473848">"Permite que o app defina um alarme em um app despertador instalado. Alguns apps despertador podem não implementar este recurso."</string>
+    <string name="permlab_addVoicemail" msgid="5525660026090959044">"adicionar correio de voz"</string>
+    <string name="permdesc_addVoicemail" msgid="6604508651428252437">"Permite que o app adicione mensagens a sua caixa de entrada do correio de voz."</string>
+    <string name="permlab_writeGeolocationPermissions" msgid="5962224158955273932">"Modifique as permissões de geolocalização de seu navegador"</string>
+    <string name="permdesc_writeGeolocationPermissions" msgid="1083743234522638747">"Permite que o app modifique as permissões de geolocalização do navegador. Apps maliciosos podem usar isso para permitir o envio de informações locais para sites arbitrários."</string>
+    <string name="save_password_message" msgid="767344687139195790">"Deseja que o navegador lembre desta senha?"</string>
+    <string name="save_password_notnow" msgid="6389675316706699758">"Agora não"</string>
+    <string name="save_password_remember" msgid="6491879678996749466">"Lembrar"</string>
+    <string name="save_password_never" msgid="8274330296785855105">"Nunca"</string>
+    <string name="open_permission_deny" msgid="7374036708316629800">"Você não tem permissão para abrir esta página."</string>
+    <string name="text_copied" msgid="4985729524670131385">"Texto copiado para a área de transferência."</string>
+    <string name="more_item_label" msgid="4650918923083320495">"Mais"</string>
+    <string name="prepend_shortcut_label" msgid="2572214461676015642">"Menu+"</string>
+    <string name="menu_space_shortcut_label" msgid="2410328639272162537">"espaço"</string>
+    <string name="menu_enter_shortcut_label" msgid="2743362785111309668">"enter"</string>
+    <string name="menu_delete_shortcut_label" msgid="3658178007202748164">"excluir"</string>
+    <string name="search_go" msgid="8298016669822141719">"Pesquisar"</string>
+    <string name="search_hint" msgid="1733947260773056054">"Pesquisar..."</string>
+    <string name="searchview_description_search" msgid="6749826639098512120">"Pesquisar"</string>
+    <string name="searchview_description_query" msgid="5911778593125355124">"Consulta de pesquisa"</string>
+    <string name="searchview_description_clear" msgid="1330281990951833033">"Limpar consulta"</string>
+    <string name="searchview_description_submit" msgid="2688450133297983542">"Enviar consulta"</string>
+    <string name="searchview_description_voice" msgid="2453203695674994440">"Pesquisa por voz"</string>
+    <string name="enable_explore_by_touch_warning_title" msgid="7460694070309730149">"Ativar exploração pelo toque?"</string>
+    <string name="enable_explore_by_touch_warning_message" product="tablet" msgid="8655887539089910577">"<xliff:g id="ACCESSIBILITY_SERVICE_NAME">%1$s</xliff:g> quer ativar a exploração pelo toque. Com ela, você pode ouvir ou ver descrições do que está sob seu dedo e interagir com o tablet através de gestos."</string>
+    <string name="enable_explore_by_touch_warning_message" product="default" msgid="2708199672852373195">"<xliff:g id="ACCESSIBILITY_SERVICE_NAME">%1$s</xliff:g> quer ativar a exploração pelo toque. Com ela, você pode ouvir ou ver descrições do que está sob seu dedo e interagir com o telefone através de gestos."</string>
+    <string name="oneMonthDurationPast" msgid="7396384508953779925">"1 mês atrás"</string>
+    <string name="beforeOneMonthDurationPast" msgid="909134546836499826">"Antes de 1 mês atrás"</string>
+    <plurals name="last_num_days" formatted="false" msgid="5104533550723932025">
+      <item quantity="one">Últimos <xliff:g id="COUNT_1">%d</xliff:g> dias</item>
+      <item quantity="other">Últimos <xliff:g id="COUNT_1">%d</xliff:g> dias</item>
+    </plurals>
+    <string name="last_month" msgid="3959346739979055432">"Mês passado"</string>
+    <string name="older" msgid="5211975022815554840">"Mais antigos"</string>
+    <string name="preposition_for_date" msgid="9093949757757445117">"em <xliff:g id="DATE">%s</xliff:g>"</string>
+    <string name="preposition_for_time" msgid="5506831244263083793">"às <xliff:g id="TIME">%s</xliff:g>"</string>
+    <string name="preposition_for_year" msgid="5040395640711867177">"em <xliff:g id="YEAR">%s</xliff:g>"</string>
+    <string name="day" msgid="8144195776058119424">"dia"</string>
+    <string name="days" msgid="4774547661021344602">"dias"</string>
+    <string name="hour" msgid="2126771916426189481">"hora"</string>
+    <string name="hours" msgid="894424005266852993">"horas"</string>
+    <string name="minute" msgid="9148878657703769868">"min."</string>
+    <string name="minutes" msgid="5646001005827034509">"min."</string>
+    <string name="second" msgid="3184235808021478">"seg."</string>
+    <string name="seconds" msgid="3161515347216589235">"segundos"</string>
+    <string name="week" msgid="5617961537173061583">"semana"</string>
+    <string name="weeks" msgid="6509623834583944518">"semanas"</string>
+    <string name="year" msgid="4001118221013892076">"ano"</string>
+    <string name="years" msgid="6881577717993213522">"anos"</string>
+    <plurals name="duration_seconds" formatted="false" msgid="4527986939729687805">
+      <item quantity="one"><xliff:g id="COUNT">%d</xliff:g> segundos</item>
+      <item quantity="other"><xliff:g id="COUNT">%d</xliff:g> segundos</item>
+    </plurals>
+    <plurals name="duration_minutes" formatted="false" msgid="643786953939956125">
+      <item quantity="one"><xliff:g id="COUNT">%d</xliff:g> minutos</item>
+      <item quantity="other"><xliff:g id="COUNT">%d</xliff:g> minutos</item>
+    </plurals>
+    <plurals name="duration_hours" formatted="false" msgid="6826233369186668274">
+      <item quantity="one"><xliff:g id="COUNT">%d</xliff:g> horas</item>
+      <item quantity="other"><xliff:g id="COUNT">%d</xliff:g> horas</item>
+    </plurals>
+    <string name="VideoView_error_title" msgid="3534509135438353077">"Problema com o vídeo"</string>
+    <string name="VideoView_error_text_invalid_progressive_playback" msgid="3186670335938670444">"Este vídeo não é válido para transmissão neste dispositivo."</string>
+    <string name="VideoView_error_text_unknown" msgid="3450439155187810085">"Não é possível reproduzir este vídeo."</string>
+    <string name="VideoView_error_button" msgid="2822238215100679592">"OK"</string>
+    <string name="relative_time" msgid="1818557177829411417">"<xliff:g id="DATE">%1$s</xliff:g>, <xliff:g id="TIME">%2$s</xliff:g>"</string>
+    <string name="noon" msgid="7245353528818587908">"meio-dia"</string>
+    <string name="Noon" msgid="3342127745230013127">"Meio-dia"</string>
+    <string name="midnight" msgid="7166259508850457595">"meia-noite"</string>
+    <string name="Midnight" msgid="5630806906897892201">"Meia-noite"</string>
+    <string name="elapsed_time_short_format_mm_ss" msgid="4431555943828711473">"<xliff:g id="MINUTES">%1$02d</xliff:g>:<xliff:g id="SECONDS">%2$02d</xliff:g>"</string>
+    <string name="elapsed_time_short_format_h_mm_ss" msgid="1846071997616654124">"<xliff:g id="HOURS">%1$d</xliff:g>:<xliff:g id="MINUTES">%2$02d</xliff:g>:<xliff:g id="SECONDS">%3$02d</xliff:g>"</string>
+    <string name="selectAll" msgid="6876518925844129331">"Selecionar tudo"</string>
+    <string name="cut" msgid="3092569408438626261">"Recortar"</string>
+    <string name="copy" msgid="2681946229533511987">"Copiar"</string>
+    <string name="paste" msgid="5629880836805036433">"Colar"</string>
+    <string name="replace" msgid="5781686059063148930">"Substituir..."</string>
+    <string name="delete" msgid="6098684844021697789">"Excluir"</string>
+    <string name="copyUrl" msgid="2538211579596067402">"Copiar URL"</string>
+    <string name="selectTextMode" msgid="1018691815143165326">"Selecionar texto"</string>
+    <string name="textSelectionCABTitle" msgid="5236850394370820357">"Seleção de texto"</string>
+    <string name="addToDictionary" msgid="4352161534510057874">"Adicionar ao dicionário"</string>
+    <string name="deleteText" msgid="6979668428458199034">"Excluir"</string>
+    <string name="inputMethod" msgid="1653630062304567879">"Método de entrada"</string>
+    <string name="editTextMenuTitle" msgid="4909135564941815494">"Ações de texto"</string>
+    <string name="low_internal_storage_view_title" msgid="5576272496365684834">"Pouco espaço de armazenamento"</string>
+    <string name="low_internal_storage_view_text" msgid="6640505817617414371">"Algumas funções do sistema podem não funcionar"</string>
+    <string name="low_internal_storage_view_text_no_boot" msgid="6935190099204693424">"Não há armazenamento suficiente para o sistema. Certifique-se de ter 250 MB de espaço livre e reinicie."</string>
+    <string name="app_running_notification_title" msgid="8718335121060787914">"<xliff:g id="APP_NAME">%1$s</xliff:g> está em execução"</string>
+    <string name="app_running_notification_text" msgid="4653586947747330058">"Toque para mais informações ou para parar o app."</string>
+    <string name="ok" msgid="5970060430562524910">"OK"</string>
+    <string name="cancel" msgid="6442560571259935130">"Cancelar"</string>
+    <string name="yes" msgid="5362982303337969312">"OK"</string>
+    <string name="no" msgid="5141531044935541497">"Cancelar"</string>
+    <string name="dialog_alert_title" msgid="2049658708609043103">"Atenção"</string>
+    <string name="loading" msgid="7933681260296021180">"Carregando…"</string>
+    <string name="capital_on" msgid="1544682755514494298">"LIG"</string>
+    <string name="capital_off" msgid="6815870386972805832">"DESL"</string>
+    <string name="whichApplication" msgid="4533185947064773386">"Complete a ação usando"</string>
+    <string name="whichApplicationNamed" msgid="8260158865936942783">"Concluir a ação usando %1$s"</string>
+    <string name="whichViewApplication" msgid="3272778576700572102">"Abrir com"</string>
+    <string name="whichViewApplicationNamed" msgid="2286418824011249620">"Abrir com %1$s"</string>
+    <string name="whichEditApplication" msgid="144727838241402655">"Editar com"</string>
+    <string name="whichEditApplicationNamed" msgid="1775815530156447790">"Editar com %1$s"</string>
+    <string name="whichSendApplication" msgid="6902512414057341668">"Compartilhar com"</string>
+    <string name="whichSendApplicationNamed" msgid="2799370240005424391">"Compartilhar com %1$s"</string>
+    <string name="whichHomeApplication" msgid="4307587691506919691">"Selecione um app de Página inicial"</string>
+    <string name="whichHomeApplicationNamed" msgid="4493438593214760979">"Usar %1$s como Página inicial"</string>
+    <string name="alwaysUse" msgid="4583018368000610438">"Usar como padrão para esta ação."</string>
+    <string name="use_a_different_app" msgid="8134926230585710243">"Usar outro app"</string>
+    <string name="clearDefaultHintMsg" msgid="3252584689512077257">"Padrão claro em Configurações do sistema &gt; Apps &gt; Baixado."</string>
+    <string name="chooseActivity" msgid="7486876147751803333">"Escolher uma ação"</string>
+    <string name="chooseUsbActivity" msgid="6894748416073583509">"Selecione um app para o dispositivo USB"</string>
+    <string name="noApplications" msgid="2991814273936504689">"Nenhum app pode realizar esta ação."</string>
+    <string name="aerr_title" msgid="1905800560317137752"></string>
+    <string name="aerr_application" msgid="932628488013092776">"O <xliff:g id="APPLICATION">%1$s</xliff:g> parou."</string>
+    <string name="aerr_process" msgid="4507058997035697579">"O processo <xliff:g id="PROCESS">%1$s</xliff:g> parou."</string>
+    <string name="anr_title" msgid="4351948481459135709"></string>
+    <string name="anr_activity_application" msgid="1904477189057199066">"<xliff:g id="APPLICATION">%2$s</xliff:g> não está respondendo.\n\nDeseja fechá-lo?"</string>
+    <string name="anr_activity_process" msgid="5776209883299089767">"A atividade <xliff:g id="ACTIVITY">%1$s</xliff:g> não está respondendo.\n\nDeseja fechá-la?"</string>
+    <string name="anr_application_process" msgid="8941757607340481057">"<xliff:g id="APPLICATION">%1$s</xliff:g> não está respondendo. Deseja encerrar o app?"</string>
+    <string name="anr_process" msgid="6513209874880517125">"O processo <xliff:g id="PROCESS">%1$s</xliff:g> não está respondendo.\n\nDeseja fechá-lo?"</string>
+    <string name="force_close" msgid="8346072094521265605">"OK"</string>
+    <string name="report" msgid="4060218260984795706">"Informar"</string>
+    <string name="wait" msgid="7147118217226317732">"Aguardar"</string>
+    <string name="webpage_unresponsive" msgid="3272758351138122503">"A página não responde.\n\nDeseja fechá-la?"</string>
+    <string name="launch_warning_title" msgid="1547997780506713581">"App redirecionado"</string>
+    <string name="launch_warning_replace" msgid="6202498949970281412">"<xliff:g id="APP_NAME">%1$s</xliff:g> não está em execução."</string>
+    <string name="launch_warning_original" msgid="188102023021668683">"<xliff:g id="APP_NAME">%1$s</xliff:g> foi iniciado."</string>
+    <string name="screen_compat_mode_scale" msgid="3202955667675944499">"Escala"</string>
+    <string name="screen_compat_mode_show" msgid="4013878876486655892">"Mostrar sempre"</string>
+    <string name="screen_compat_mode_hint" msgid="1064524084543304459">"Reativar isso em Configurações do sistema &gt; Apps &gt; Transferidos."</string>
+    <string name="smv_application" msgid="3307209192155442829">"O app <xliff:g id="APPLICATION">%1$s</xliff:g>, processo <xliff:g id="PROCESS">%2$s</xliff:g>, violou a política StrictMode imposta automaticamente."</string>
+    <string name="smv_process" msgid="5120397012047462446">"O processo <xliff:g id="PROCESS">%1$s</xliff:g> violou a política StrictMode imposta automaticamente."</string>
+    <string name="android_upgrading_title" msgid="1584192285441405746">"O Android está sendo atualizado..."</string>
+    <string name="android_start_title" msgid="8418054686415318207">"O Android está iniciando..."</string>
+    <string name="android_upgrading_fstrim" msgid="8036718871534640010">"Otimizando o armazenamento."</string>
+    <string name="android_upgrading_apk" msgid="7904042682111526169">"Otimizando app <xliff:g id="NUMBER_0">%1$d</xliff:g> de <xliff:g id="NUMBER_1">%2$d</xliff:g>."</string>
+    <string name="android_preparing_apk" msgid="8162599310274079154">"Preparando <xliff:g id="APPNAME">%1$s</xliff:g>."</string>
+    <string name="android_upgrading_starting_apps" msgid="451464516346926713">"Iniciando apps."</string>
+    <string name="android_upgrading_complete" msgid="1405954754112999229">"Concluindo a inicialização."</string>
+    <string name="heavy_weight_notification" msgid="9087063985776626166">"<xliff:g id="APP">%1$s</xliff:g> em execução"</string>
+    <string name="heavy_weight_notification_detail" msgid="1721681741617898865">"Toque para alternar para o app"</string>
+    <string name="heavy_weight_switcher_title" msgid="7153167085403298169">"Alternar entre apps?"</string>
+    <string name="heavy_weight_switcher_text" msgid="7022631924534406403">"Outro app já está em execução e deve ser interrompido antes que você inicie um novo app."</string>
+    <string name="old_app_action" msgid="493129172238566282">"Voltar para <xliff:g id="OLD_APP">%1$s</xliff:g>"</string>
+    <string name="old_app_description" msgid="2082094275580358049">"Não inicie o novo app."</string>
+    <string name="new_app_action" msgid="5472756926945440706">"Iniciar <xliff:g id="OLD_APP">%1$s</xliff:g>"</string>
+    <string name="new_app_description" msgid="1932143598371537340">"Parar o app antigo sem salvar."</string>
+    <string name="dump_heap_notification" msgid="2618183274836056542">"<xliff:g id="PROC">%1$s</xliff:g> excedeu o limite de memória"</string>
+    <string name="dump_heap_notification_detail" msgid="2075673362317481664">"O despejo de heap foi coletado. Toque para compartilhar"</string>
+    <string name="dump_heap_title" msgid="5864292264307651673">"Compartilhar despejo de heap?"</string>
+    <string name="dump_heap_text" msgid="4809417337240334941">"O processo <xliff:g id="PROC">%1$s</xliff:g> excedeu seu limite de memória de <xliff:g id="SIZE">%2$s</xliff:g>. Um despejo de heap está disponível para compartilhamento com o desenvolvedor. Tenha cuidado: esse despejo de heap pode conter informações pessoais às quais o aplicativo tem acesso."</string>
+    <string name="sendText" msgid="5209874571959469142">"Escolha uma ação para o texto"</string>
+    <string name="volume_ringtone" msgid="6885421406845734650">"Volume da campainha"</string>
+    <string name="volume_music" msgid="5421651157138628171">"Volume da mídia"</string>
+    <string name="volume_music_hint_playing_through_bluetooth" msgid="9165984379394601533">"Reproduzindo por meio de Bluetooth"</string>
+    <string name="volume_music_hint_silent_ringtone_selected" msgid="8310739960973156272">"Toque silencioso definido"</string>
+    <string name="volume_call" msgid="3941680041282788711">"Volume na chamada"</string>
+    <string name="volume_bluetooth_call" msgid="2002891926351151534">"Volume de chamada Bluetooth"</string>
+    <string name="volume_alarm" msgid="1985191616042689100">"Volume do alarme"</string>
+    <string name="volume_notification" msgid="2422265656744276715">"Volume da notificação"</string>
+    <string name="volume_unknown" msgid="1400219669770445902">"Volume"</string>
+    <string name="volume_icon_description_bluetooth" msgid="6538894177255964340">"Volume de Bluetooth"</string>
+    <string name="volume_icon_description_ringer" msgid="3326003847006162496">"Volume do toque"</string>
+    <string name="volume_icon_description_incall" msgid="8890073218154543397">"Volume de chamadas"</string>
+    <string name="volume_icon_description_media" msgid="4217311719665194215">"Volume da mídia"</string>
+    <string name="volume_icon_description_notification" msgid="7044986546477282274">"Volume da notificação"</string>
+    <string name="ringtone_default" msgid="3789758980357696936">"Toque padrão"</string>
+    <string name="ringtone_default_with_actual" msgid="8129563480895990372">"Toque padrão (<xliff:g id="ACTUAL_RINGTONE">%1$s</xliff:g>)"</string>
+    <string name="ringtone_silent" msgid="7937634392408977062">"Nenhum"</string>
+    <string name="ringtone_picker_title" msgid="3515143939175119094">"Toques"</string>
+    <string name="ringtone_unknown" msgid="5477919988701784788">"Toque desconhecido"</string>
+    <plurals name="wifi_available" formatted="false" msgid="7900333017752027322">
+      <item quantity="one">Redes Wi-Fi disponíveis</item>
+      <item quantity="other">Redes Wi-Fi disponíveis</item>
+    </plurals>
+    <plurals name="wifi_available_detailed" formatted="false" msgid="1140699367193975606">
+      <item quantity="one">Abrir redes Wi-Fi disponíveis</item>
+      <item quantity="other">Abrir redes Wi-Fi disponíveis</item>
+    </plurals>
+    <string name="wifi_available_sign_in" msgid="9157196203958866662">"Fazer login na rede Wi-Fi"</string>
+    <string name="network_available_sign_in" msgid="1848877297365446605">"Fazer login na rede"</string>
+    <!-- no translation found for network_available_sign_in_detailed (8000081941447976118) -->
+    <skip />
+    <string name="wifi_no_internet" msgid="8451173622563841546">"O Wi-Fi não tem acesso à Internet"</string>
+    <string name="wifi_no_internet_detailed" msgid="7593858887662270131">"Toque para ver as opções"</string>
+    <string name="wifi_watchdog_network_disabled" msgid="7904214231651546347">"Não foi possível se conectar a redes Wi-Fi"</string>
+    <string name="wifi_watchdog_network_disabled_detailed" msgid="5548780776418332675">" tem uma conexão de baixa qualidade com a Internet."</string>
+    <string name="wifi_connect_alert_title" msgid="8455846016001810172">"Permitir conexão?"</string>
+    <string name="wifi_connect_alert_message" msgid="6451273376815958922">"O app %1$s deseja se conectar à rede Wi-Fi %2$s"</string>
+    <string name="wifi_connect_default_application" msgid="7143109390475484319">"Um app"</string>
+    <string name="wifi_p2p_dialog_title" msgid="97611782659324517">"Wi-Fi Direct"</string>
+    <string name="wifi_p2p_turnon_message" msgid="2909250942299627244">"Iniciar o Wi-Fi Direct. Isso desativará o ponto de acesso/cliente Wi-Fi."</string>
+    <string name="wifi_p2p_failed_message" msgid="3763669677935623084">"Não foi possível iniciar o Wi-Fi Direct."</string>
+    <string name="wifi_p2p_enabled_notification_title" msgid="2068321881673734886">"Wi-Fi Direct ativado"</string>
+    <string name="wifi_p2p_enabled_notification_message" msgid="1638949953993894335">"Tocar para acessar configurações"</string>
+    <string name="accept" msgid="1645267259272829559">"Aceitar"</string>
+    <string name="decline" msgid="2112225451706137894">"Recusar"</string>
+    <string name="wifi_p2p_invitation_sent_title" msgid="1318975185112070734">"Convite enviado"</string>
+    <string name="wifi_p2p_invitation_to_connect_title" msgid="4958803948658533637">"Convite para se conectar"</string>
+    <string name="wifi_p2p_from_message" msgid="570389174731951769">"De:"</string>
+    <string name="wifi_p2p_to_message" msgid="248968974522044099">"Para:"</string>
+    <string name="wifi_p2p_enter_pin_message" msgid="5920929550367828970">"Digite o PIN obrigatório:"</string>
+    <string name="wifi_p2p_show_pin_message" msgid="8530563323880921094">"PIN:"</string>
+    <string name="wifi_p2p_frequency_conflict_message" product="tablet" msgid="8012981257742232475">"O tablet desconectará temporariamente da rede Wi-Fi enquanto estiver conectado a <xliff:g id="DEVICE_NAME">%1$s</xliff:g>"</string>
+    <string name="wifi_p2p_frequency_conflict_message" product="tv" msgid="3087858235069421128">"A TV desconectará o Wi-Fi temporariamente enquanto estiver conectada ao <xliff:g id="DEVICE_NAME">%1$s</xliff:g>"</string>
+    <string name="wifi_p2p_frequency_conflict_message" product="default" msgid="7363907213787469151">"O telefone desconectará temporariamente da rede Wi-Fi enquanto estiver conectado a <xliff:g id="DEVICE_NAME">%1$s</xliff:g>"</string>
+    <string name="select_character" msgid="3365550120617701745">"Inserir caractere"</string>
+    <string name="sms_control_title" msgid="7296612781128917719">"Enviando mensagens SMS"</string>
+    <string name="sms_control_message" msgid="3867899169651496433">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; envia uma grande quantidade de mensagens SMS. Deseja permitir que este app continue enviando mensagens?"</string>
+    <string name="sms_control_yes" msgid="3663725993855816807">"Permitir"</string>
+    <string name="sms_control_no" msgid="625438561395534982">"Negar"</string>
+    <string name="sms_short_code_confirm_message" msgid="1645436466285310855">"&lt;b&gt;<xliff:g id="APP_NAME">%1$s</xliff:g>&lt;/b&gt; deseja enviar uma mensagem para &lt;b&gt;<xliff:g id="DEST_ADDRESS">%2$s</xliff:g>&lt;/b&gt;."</string>
+    <string name="sms_short_code_details" msgid="5873295990846059400">"Isso "<b>"pode resultar em cobranças"</b>" na conta de seu dispositivo móvel."</string>
+    <string name="sms_premium_short_code_details" msgid="7869234868023975"><b>"Isso resultará em cobranças na conta de seu dispositivo móvel."</b></string>
+    <string name="sms_short_code_confirm_allow" msgid="4458878637111023413">"Enviar"</string>
+    <string name="sms_short_code_confirm_deny" msgid="2927389840209170706">"Cancelar"</string>
+    <string name="sms_short_code_remember_choice" msgid="5289538592272218136">"Lembrar minha escolha"</string>
+    <string name="sms_short_code_remember_undo_instruction" msgid="4960944133052287484">"P/ alterar: Configurações &gt; Apps"</string>
+    <string name="sms_short_code_confirm_always_allow" msgid="3241181154869493368">"Sempre permitir"</string>
+    <string name="sms_short_code_confirm_never_allow" msgid="446992765774269673">"Nunca permitir"</string>
+    <string name="sim_removed_title" msgid="6227712319223226185">"Cartão SIM removido"</string>
+    <string name="sim_removed_message" msgid="5450336489923274918">"A rede celular ficará indisponível até que você reinicie com um cartão SIM válido inserido."</string>
+    <string name="sim_done_button" msgid="827949989369963775">"Concluído"</string>
+    <string name="sim_added_title" msgid="3719670512889674693">"Cartão SIM adicionado"</string>
+    <string name="sim_added_message" msgid="7797975656153714319">"Reinicie o dispositivo para acessar a rede celular."</string>
+    <string name="sim_restart_button" msgid="4722407842815232347">"Reiniciar"</string>
+    <string name="time_picker_dialog_title" msgid="8349362623068819295">"Definir hora"</string>
+    <string name="date_picker_dialog_title" msgid="5879450659453782278">"Definir data"</string>
+    <string name="date_time_set" msgid="5777075614321087758">"Definir"</string>
+    <string name="date_time_done" msgid="2507683751759308828">"Concluído"</string>
+    <string name="perms_new_perm_prefix" msgid="8257740710754301407"><font size="12" fgcolor="#ff33b5e5">"NOVO: "</font></string>
+    <string name="perms_description_app" msgid="5139836143293299417">"Fornecido por <xliff:g id="APP_NAME">%1$s</xliff:g>."</string>
+    <string name="no_permissions" msgid="7283357728219338112">"Nenhuma permissão necessária"</string>
+    <string name="perm_costs_money" msgid="4902470324142151116">"isso pode lhe custar dinheiro"</string>
+    <string name="usb_storage_activity_title" msgid="4465055157209648641">"Armazenamento USB em massa"</string>
+    <string name="usb_storage_title" msgid="5901459041398751495">"Conectado por USB"</string>
+    <string name="usb_storage_message" product="nosdcard" msgid="3308538094316477839">"Você se conectou ao computador via USB. Toque no botão abaixo se quiser copiar arquivos entre o computador e o armazenamento USB de seu Android."</string>
+    <string name="usb_storage_message" product="default" msgid="805351000446037811">"Você se conectou ao computador via USB. Toque no botão abaixo se quiser copiar arquivos entre o computador e o cartão SD de seu Android."</string>
+    <string name="usb_storage_button_mount" msgid="1052259930369508235">"Ativar o armazenamento USB"</string>
+    <string name="usb_storage_error_message" product="nosdcard" msgid="3017045217365540658">"Há um problema com o uso do seu armazenamento USB para armazenamento USB em massa."</string>
+    <string name="usb_storage_error_message" product="default" msgid="2876018512716970313">"Há um problema com o uso do seu cartão SD para armazenamento USB em massa."</string>
+    <string name="usb_storage_notification_title" msgid="8175892554757216525">"Conectado por USB"</string>
+    <string name="usb_storage_notification_message" msgid="939822783828183763">"Toque para copiar arquivos para/de seu computador."</string>
+    <string name="usb_storage_stop_notification_title" msgid="2336058396663516017">"Desativar o armazenamento USB"</string>
+    <string name="usb_storage_stop_notification_message" msgid="1656852098555623822">"Toque para desativar o armazenamento USB."</string>
+    <string name="usb_storage_stop_title" msgid="660129851708775853">"Armazenamento USB em uso"</string>
+    <string name="usb_storage_stop_message" product="nosdcard" msgid="4264025280777219521">"Antes de desativar o armazenamento USB, desconecte (“ejete”) o armazenamento USB do Android de seu computador."</string>
+    <string name="usb_storage_stop_message" product="default" msgid="8043969782460613114">"Antes de desativar o armazenamento USB, desconecte (“ejete”) o cartão SD do Android de seu computador."</string>
+    <string name="usb_storage_stop_button_mount" msgid="7060218034900696029">"Desativar o armazenamento USB"</string>
+    <string name="usb_storage_stop_error_message" msgid="1970374898263063836">"Ocorreu um problema ao desativar o armazenamento USB. Verifique se você desconectou o host USB e tente novamente."</string>
+    <string name="dlg_confirm_kill_storage_users_title" msgid="963039033470478697">"Ativar o armazenamento USB"</string>
+    <string name="dlg_confirm_kill_storage_users_text" msgid="5100428757107469454">"Se você ativar o armazenamento USB, alguns apps que estão em uso serão interrompidos e poderão ficar indisponíveis até você desativar o armazenamento USB."</string>
+    <string name="dlg_error_title" msgid="7323658469626514207">"Falha na operação do USB"</string>
+    <string name="dlg_ok" msgid="7376953167039865701">"OK"</string>
+    <string name="usb_charging_notification_title" msgid="4004114449249406402">"USB para carregamento"</string>
+    <string name="usb_mtp_notification_title" msgid="8396264943589760855">"USB para transferência de arquivos"</string>
+    <string name="usb_ptp_notification_title" msgid="1347328437083192112">"USB para transferência de fotos"</string>
+    <string name="usb_midi_notification_title" msgid="4850904915889144654">"USB para MIDI"</string>
+    <string name="usb_accessory_notification_title" msgid="7848236974087653666">"Conectado a um acessório USB"</string>
+    <string name="usb_notification_message" msgid="7347368030849048437">"Toque para ver mais opções."</string>
+    <string name="adb_active_notification_title" msgid="6729044778949189918">"Depuração USB conectada"</string>
+    <string name="adb_active_notification_message" msgid="1016654627626476142">"Toque para desativar a depuração do USB."</string>
+    <string name="select_input_method" msgid="8547250819326693584">"Alterar teclado"</string>
+    <string name="configure_input_methods" msgid="4769971288371946846">"Escolher teclados"</string>
+    <string name="show_ime" msgid="9157568568695230830">"Mostrar método de entrada"</string>
+    <string name="hardware" msgid="7517821086888990278">"Hardware"</string>
+    <string name="select_keyboard_layout_notification_title" msgid="1407367017263030773">"Selecione o layout de teclado"</string>
+    <string name="select_keyboard_layout_notification_message" msgid="4465907700449257063">"Toque para selecionar um layout de teclado."</string>
+    <string name="fast_scroll_alphabet" msgid="5433275485499039199">" ABCDEFGHIJKLMNOPQRSTUVWXYZ"</string>
+    <string name="fast_scroll_numeric_alphabet" msgid="4030170524595123610">" 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"</string>
+    <string name="candidates_style" msgid="4333913089637062257"><u>"candidatos"</u></string>
+    <string name="ext_media_checking_notification_title" msgid="5734005953288045806">"Preparando <xliff:g id="NAME">%s</xliff:g>"</string>
+    <string name="ext_media_checking_notification_message" msgid="4747432538578886744">"Procurando erros"</string>
+    <string name="ext_media_new_notification_message" msgid="7589986898808506239">"Novo <xliff:g id="NAME">%s</xliff:g> detectado"</string>
+    <string name="ext_media_ready_notification_message" msgid="4083398150380114462">"Para transferir fotos e mídia"</string>
+    <string name="ext_media_unmountable_notification_title" msgid="8295123366236989588">"<xliff:g id="NAME">%s</xliff:g> corrompido"</string>
+    <string name="ext_media_unmountable_notification_message" msgid="1586311304430052169">"<xliff:g id="NAME">%s</xliff:g> está corrompida. Toque para corrigir."</string>
+    <string name="ext_media_unsupported_notification_title" msgid="3797642322958803257">"<xliff:g id="NAME">%s</xliff:g> não compatível"</string>
+    <string name="ext_media_unsupported_notification_message" msgid="8789610369456474891">"Este dispositivo não é compatível com o <xliff:g id="NAME">%s</xliff:g>. Toque para configurar em um formato compatível."</string>
+    <string name="ext_media_badremoval_notification_title" msgid="3206248947375505416">"<xliff:g id="NAME">%s</xliff:g> foi removido inesperadamente"</string>
+    <string name="ext_media_badremoval_notification_message" msgid="380176703346946313">"Desconecte <xliff:g id="NAME">%s</xliff:g> antes da remoção para evitar a perda de dados"</string>
+    <string name="ext_media_nomedia_notification_title" msgid="1704840188641749091">"Mídia <xliff:g id="NAME">%s</xliff:g> removida."</string>
+    <string name="ext_media_nomedia_notification_message" msgid="6471542972147056586">"Mídia <xliff:g id="NAME">%s</xliff:g> removida. Insira uma nova"</string>
+    <string name="ext_media_unmounting_notification_title" msgid="640674168454809372">"Ainda ejetando <xliff:g id="NAME">%s</xliff:g>..."</string>
+    <string name="ext_media_unmounting_notification_message" msgid="4182843895023357756">"Não remova"</string>
+    <string name="ext_media_init_action" msgid="7952885510091978278">"Configurar"</string>
+    <string name="ext_media_unmount_action" msgid="1121883233103278199">"Ejetar"</string>
+    <string name="ext_media_browse_action" msgid="8322172381028546087">"Explorar"</string>
+    <string name="ext_media_missing_title" msgid="620980315821543904">"<xliff:g id="NAME">%s</xliff:g> ausente"</string>
+    <string name="ext_media_missing_message" msgid="5761133583368750174">"Reinserir este dispositivo"</string>
+    <string name="ext_media_move_specific_title" msgid="1471100343872375842">"Movendo <xliff:g id="NAME">%s</xliff:g>"</string>
+    <string name="ext_media_move_title" msgid="1022809140035962662">"Movendo dados"</string>
+    <string name="ext_media_move_success_title" msgid="8575300932957954671">"Transferência concluída"</string>
+    <string name="ext_media_move_success_message" msgid="4199002148206265426">"Dados movidos para <xliff:g id="NAME">%s</xliff:g>"</string>
+    <string name="ext_media_move_failure_title" msgid="7613189040358789908">"Não foi possível mover os dados"</string>
+    <string name="ext_media_move_failure_message" msgid="1978096440816403360">"Dados deixados no local original"</string>
+    <string name="ext_media_status_removed" msgid="6576172423185918739">"Removida"</string>
+    <string name="ext_media_status_unmounted" msgid="2551560878416417752">"Ejetada"</string>
+    <string name="ext_media_status_checking" msgid="6193921557423194949">"Verificando..."</string>
+    <string name="ext_media_status_mounted" msgid="7253821726503179202">"Pronto"</string>
+    <string name="ext_media_status_mounted_ro" msgid="8020978752406021015">"Somente leitura"</string>
+    <string name="ext_media_status_bad_removal" msgid="8395398567890329422">"Removido de forma não segura"</string>
+    <string name="ext_media_status_unmountable" msgid="805594039236667894">"Corrompida"</string>
+    <string name="ext_media_status_unsupported" msgid="4691436711745681828">"Incompatível"</string>
+    <string name="ext_media_status_ejecting" msgid="5463887263101234174">"Ejetando…"</string>
+    <string name="ext_media_status_formatting" msgid="1085079556538644861">"Formatando..."</string>
+    <string name="ext_media_status_missing" msgid="5638633895221670766">"Não inserida"</string>
+    <string name="activity_list_empty" msgid="1675388330786841066">"Nenhum atividade correspondente foi encontrada."</string>
+    <string name="permlab_route_media_output" msgid="1642024455750414694">"Rotear saída de mídia"</string>
+    <string name="permdesc_route_media_output" msgid="4932818749547244346">"Permite que um app faça o roteamento de saída de mídia para outros dispositivos externos."</string>
+    <string name="permlab_readInstallSessions" msgid="6165432407628065939">"Ler sessões de instalação"</string>
+    <string name="permdesc_readInstallSessions" msgid="2049771699626019849">"Permite que um app leia sessões de instalação. Isso permite que ele veja detalhes sobre as instalações de pacote ativas."</string>
+    <string name="permlab_requestInstallPackages" msgid="1772330282283082214">"Solicitar instalação de pacotes"</string>
+    <string name="permdesc_requestInstallPackages" msgid="5740101072486783082">"Permite que um app solicite a instalação de pacotes."</string>
+    <string name="tutorial_double_tap_to_zoom_message_short" msgid="4070433208160063538">"Toque duas vezes para controlar o zoom"</string>
+    <string name="gadget_host_error_inflating" msgid="4882004314906466162">"Não foi possível adicionar widget."</string>
+    <string name="ime_action_go" msgid="8320845651737369027">"Ir"</string>
+    <string name="ime_action_search" msgid="658110271822807811">"Pesquisar"</string>
+    <string name="ime_action_send" msgid="2316166556349314424">"Enviar"</string>
+    <string name="ime_action_next" msgid="3138843904009813834">"Avançar"</string>
+    <string name="ime_action_done" msgid="8971516117910934605">"Concluído"</string>
+    <string name="ime_action_previous" msgid="1443550039250105948">"Anter."</string>
+    <string name="ime_action_default" msgid="2840921885558045721">"Executar"</string>
+    <string name="dial_number_using" msgid="5789176425167573586">"Discar número\nusando <xliff:g id="NUMBER">%s</xliff:g>"</string>
+    <string name="create_contact_using" msgid="4947405226788104538">"Criar contato \nusando <xliff:g id="NUMBER">%s</xliff:g>"</string>
+    <string name="grant_credentials_permission_message_header" msgid="2106103817937859662">"O app a seguir ou outros apps solicitam permissão para acessar sua conta, agora e no futuro."</string>
+    <string name="grant_credentials_permission_message_footer" msgid="3125211343379376561">"Deseja permitir essa solicitação?"</string>
+    <string name="grant_permissions_header_text" msgid="6874497408201826708">"Solicitação de acesso"</string>
+    <string name="allow" msgid="7225948811296386551">"Permitir"</string>
+    <string name="deny" msgid="2081879885755434506">"Negar"</string>
+    <string name="permission_request_notification_title" msgid="6486759795926237907">"Permissão solicitada"</string>
+    <string name="permission_request_notification_with_subtitle" msgid="8530393139639560189">"Permissão solicitada\npara a conta <xliff:g id="ACCOUNT">%s</xliff:g>."</string>
+    <string name="forward_intent_to_owner" msgid="1207197447013960896">"Este app está sendo usado fora de seu perfil de trabalho"</string>
+    <string name="forward_intent_to_work" msgid="621480743856004612">"Você está usando este app em seu perfil de trabalho"</string>
+    <string name="input_method_binding_label" msgid="1283557179944992649">"Método de entrada"</string>
+    <string name="sync_binding_label" msgid="3687969138375092423">"Sincronizar"</string>
+    <string name="accessibility_binding_label" msgid="4148120742096474641">"Acessibilidade"</string>
+    <string name="wallpaper_binding_label" msgid="1240087844304687662">"Plano de fundo"</string>
+    <string name="chooser_wallpaper" msgid="7873476199295190279">"Alterar plano de fundo"</string>
+    <string name="notification_listener_binding_label" msgid="2014162835481906429">"Ouvinte de notificações"</string>
+    <string name="condition_provider_service_binding_label" msgid="1321343352906524564">"Provedor de condições"</string>
+    <string name="vpn_title" msgid="19615213552042827">"VPN ativada"</string>
+    <string name="vpn_title_long" msgid="6400714798049252294">"A VPN está ativada por <xliff:g id="APP">%s</xliff:g>"</string>
+    <string name="vpn_text" msgid="3011306607126450322">"Toque para gerenciar a rede."</string>
+    <string name="vpn_text_long" msgid="6407351006249174473">"Conectado a <xliff:g id="SESSION">%s</xliff:g>. Toque para gerenciar a rede."</string>
+    <string name="vpn_lockdown_connecting" msgid="6443438964440960745">"VPN sempre ativa conectando..."</string>
+    <string name="vpn_lockdown_connected" msgid="8202679674819213931">"VPN sempre ativa conectada"</string>
+    <string name="vpn_lockdown_error" msgid="6009249814034708175">"Erro na VPN sempre ativa"</string>
+    <string name="vpn_lockdown_config" msgid="6415899150671537970">"Toque para configurar"</string>
+    <string name="upload_file" msgid="2897957172366730416">"Escolher arquivo"</string>
+    <string name="no_file_chosen" msgid="6363648562170759465">"Nenhum arquivo escolhido"</string>
+    <string name="reset" msgid="2448168080964209908">"Redefinir"</string>
+    <string name="submit" msgid="1602335572089911941">"Enviar"</string>
+    <string name="car_mode_disable_notification_title" msgid="3164768212003864316">"Modo carro ativado"</string>
+    <string name="car_mode_disable_notification_message" msgid="8035230537563503262">"Toque para sair do modo Carro."</string>
+    <string name="tethered_notification_title" msgid="3146694234398202601">"Vínculo ou ponto de acesso ativo"</string>
+    <string name="tethered_notification_message" msgid="6857031760103062982">"Toque para configurar."</string>
+    <string name="back_button_label" msgid="2300470004503343439">"Voltar"</string>
+    <string name="next_button_label" msgid="1080555104677992408">"Avançar"</string>
+    <string name="skip_button_label" msgid="1275362299471631819">"Ignorar"</string>
+    <string name="no_matches" msgid="8129421908915840737">"Não encontrado"</string>
+    <string name="find_on_page" msgid="1946799233822820384">"Localizar na página"</string>
+    <plurals name="matches_found" formatted="false" msgid="1210884353962081884">
+      <item quantity="one"><xliff:g id="INDEX">%d</xliff:g> de <xliff:g id="TOTAL">%d</xliff:g></item>
+      <item quantity="other"><xliff:g id="INDEX">%d</xliff:g> de <xliff:g id="TOTAL">%d</xliff:g></item>
+    </plurals>
+    <string name="action_mode_done" msgid="7217581640461922289">"Concluído"</string>
+    <string name="progress_erasing" product="nosdcard" msgid="4521573321524340058">"Apagando o armazenamento USB..."</string>
+    <string name="progress_erasing" product="default" msgid="6596988875507043042">"Apagando cartão SD..."</string>
+    <string name="share" msgid="1778686618230011964">"Compartilhar"</string>
+    <string name="find" msgid="4808270900322985960">"Localizar"</string>
+    <string name="websearch" msgid="4337157977400211589">"Pesquisa na web do Google"</string>
+    <string name="find_next" msgid="5742124618942193978">"Localizar próximo"</string>
+    <string name="find_previous" msgid="2196723669388360506">"Localizar anterior"</string>
+    <string name="gpsNotifTicker" msgid="5622683912616496172">"Solicitação de local de <xliff:g id="NAME">%s</xliff:g>"</string>
+    <string name="gpsNotifTitle" msgid="5446858717157416839">"Solicitação de local"</string>
+    <string name="gpsNotifMessage" msgid="1374718023224000702">"Solicitado por <xliff:g id="NAME">%1$s</xliff:g> (<xliff:g id="SERVICE">%2$s</xliff:g>)"</string>
+    <string name="gpsVerifYes" msgid="2346566072867213563">"Sim"</string>
+    <string name="gpsVerifNo" msgid="1146564937346454865">"Não"</string>
+    <string name="sync_too_many_deletes" msgid="5296321850662746890">"Limite de exclusão excedido"</string>
+    <string name="sync_too_many_deletes_desc" msgid="496551671008694245">"Há <xliff:g id="NUMBER_OF_DELETED_ITEMS">%1$d</xliff:g> itens excluídos para <xliff:g id="TYPE_OF_SYNC">%2$s</xliff:g>, conta <xliff:g id="ACCOUNT_NAME">%3$s</xliff:g>. O que você deseja fazer?"</string>
+    <string name="sync_really_delete" msgid="2572600103122596243">"Excluir os itens"</string>
+    <string name="sync_undo_deletes" msgid="2941317360600338602">"Desfazer as exclusões"</string>
+    <string name="sync_do_nothing" msgid="3743764740430821845">"Não fazer nada por enquanto"</string>
+    <string name="choose_account_label" msgid="5655203089746423927">"Escolha uma conta"</string>
+    <string name="add_account_label" msgid="2935267344849993553">"Adicionar uma conta"</string>
+    <string name="add_account_button_label" msgid="3611982894853435874">"Adicionar conta"</string>
+    <string name="number_picker_increment_button" msgid="2412072272832284313">"Aumentar"</string>
+    <string name="number_picker_decrement_button" msgid="476050778386779067">"Diminuir"</string>
+    <string name="number_picker_increment_scroll_mode" msgid="3073101067441638428">"<xliff:g id="VALUE">%s</xliff:g> toque e mantenha pressionado."</string>
+    <string name="number_picker_increment_scroll_action" msgid="9101473045891835490">"Deslize para cima para aumentar e para baixo para diminuir."</string>
+    <string name="time_picker_increment_minute_button" msgid="8865885114028614321">"Aumentar minuto"</string>
+    <string name="time_picker_decrement_minute_button" msgid="6246834937080684791">"Diminuir minuto"</string>
+    <string name="time_picker_increment_hour_button" msgid="3652056055810223139">"Aumentar hora"</string>
+    <string name="time_picker_decrement_hour_button" msgid="1377479863429214792">"Diminuir hora"</string>
+    <string name="time_picker_increment_set_pm_button" msgid="4147590696151230863">"Configurar valor PM"</string>
+    <string name="time_picker_decrement_set_am_button" msgid="8302140353539486752">"Configurar valor AM"</string>
+    <string name="date_picker_increment_month_button" msgid="5369998479067934110">"Aumentar mês"</string>
+    <string name="date_picker_decrement_month_button" msgid="1832698995541726019">"Diminuir mês"</string>
+    <string name="date_picker_increment_day_button" msgid="7130465412308173903">"Aumentar dia"</string>
+    <string name="date_picker_decrement_day_button" msgid="4131881521818750031">"Diminuir dia"</string>
+    <string name="date_picker_increment_year_button" msgid="6318697384310808899">"Aumentar ano"</string>
+    <string name="date_picker_decrement_year_button" msgid="4482021813491121717">"Diminuir ano"</string>
+    <string name="date_picker_prev_month_button" msgid="2858244643992056505">"Mês passado"</string>
+    <string name="date_picker_next_month_button" msgid="5559507736887605055">"Próximo mês"</string>
+    <string name="keyboardview_keycode_alt" msgid="4856868820040051939">"Alt"</string>
+    <string name="keyboardview_keycode_cancel" msgid="1203984017245783244">"Cancelar"</string>
+    <string name="keyboardview_keycode_delete" msgid="3337914833206635744">"Excluir"</string>
+    <string name="keyboardview_keycode_done" msgid="1992571118466679775">"Concluído"</string>
+    <string name="keyboardview_keycode_mode_change" msgid="4547387741906537519">"Alteração do modo"</string>
+    <string name="keyboardview_keycode_shift" msgid="2270748814315147690">"Shift"</string>
+    <string name="keyboardview_keycode_enter" msgid="2985864015076059467">"Enter"</string>
+    <string name="activitychooserview_choose_application" msgid="2125168057199941199">"Selecione um app"</string>
+    <string name="activitychooserview_choose_application_error" msgid="8624618365481126668">"Não foi possível iniciar o <xliff:g id="APPLICATION_NAME">%s</xliff:g>"</string>
+    <string name="shareactionprovider_share_with" msgid="806688056141131819">"Compartilhar com"</string>
+    <string name="shareactionprovider_share_with_application" msgid="5627411384638389738">"Compartilhar com <xliff:g id="APPLICATION_NAME">%s</xliff:g>"</string>
+    <string name="content_description_sliding_handle" msgid="415975056159262248">"Recurso deslizante. Toque e segure."</string>
+    <string name="description_target_unlock_tablet" msgid="3833195335629795055">"Deslize para desbloquear."</string>
+    <string name="keyboard_headset_required_to_hear_password" msgid="7011927352267668657">"Conecte um fone de ouvido para ouvir as teclas da senha."</string>
+    <string name="keyboard_password_character_no_headset" msgid="2859873770886153678">"Ponto final."</string>
+    <string name="action_bar_home_description" msgid="5293600496601490216">"Navegar na página inicial"</string>
+    <string name="action_bar_up_description" msgid="2237496562952152589">"Navegar para cima"</string>
+    <string name="action_menu_overflow_description" msgid="2295659037509008453">"Mais opções"</string>
+    <string name="action_bar_home_description_format" msgid="7965984360903693903">"%1$s, %2$s"</string>
+    <string name="action_bar_home_subtitle_description_format" msgid="6985546530471780727">"%1$s, %2$s, %3$s"</string>
+    <string name="storage_internal" msgid="4891916833657929263">"Armazenamento interno"</string>
+    <string name="storage_sd_card" msgid="3282948861378286745">"Cartão SD"</string>
+    <string name="storage_sd_card_label" msgid="6347111320774379257">"Cartão SD <xliff:g id="MANUFACTURER">%s</xliff:g>"</string>
+    <string name="storage_usb_drive" msgid="6261899683292244209">"Drive USB"</string>
+    <string name="storage_usb_drive_label" msgid="4501418548927759953">"Drive USB <xliff:g id="MANUFACTURER">%s</xliff:g>"</string>
+    <string name="storage_usb" msgid="3017954059538517278">"Armazenamento USB"</string>
+    <string name="data_usage_warning_title" msgid="1955638862122232342">"Aviso sobre uso de dados"</string>
+    <string name="data_usage_warning_body" msgid="2814673551471969954">"Toque p/ ver uso e config."</string>
+    <string name="data_usage_3g_limit_title" msgid="4361523876818447683">"Limite de dados 2G-3G atingido"</string>
+    <string name="data_usage_4g_limit_title" msgid="4609566827219442376">"Limite de dados 4G atingido"</string>
+    <string name="data_usage_mobile_limit_title" msgid="557158376602636112">"Limite de dados celular atingido"</string>
+    <string name="data_usage_wifi_limit_title" msgid="5803363779034792676">"Limite de dados Wi-Fi atingido"</string>
+    <string name="data_usage_limit_body" msgid="291731708279614081">"Dados pausados no resto do ciclo"</string>
+    <string name="data_usage_3g_limit_snoozed_title" msgid="7026739121138005231">"Limite de dados 2G-3G excedido"</string>
+    <string name="data_usage_4g_limit_snoozed_title" msgid="1106562779311209039">"Limite de dados 4G excedido"</string>
+    <string name="data_usage_mobile_limit_snoozed_title" msgid="4941346653729943789">"Lim. de dados rede cel. excedido"</string>
+    <string name="data_usage_wifi_limit_snoozed_title" msgid="8743856006384825974">"Limite de dados Wi-Fi excedido"</string>
+    <string name="data_usage_limit_snoozed_body" msgid="7035490278298441767">"<xliff:g id="SIZE">%s</xliff:g> acima do limite especificado."</string>
+    <string name="data_usage_restricted_title" msgid="5965157361036321914">"Dados de segundo plano restritos"</string>
+    <string name="data_usage_restricted_body" msgid="6741521330997452990">"Toque para remover a restrição."</string>
+    <string name="ssl_certificate" msgid="6510040486049237639">"Certificado de segurança"</string>
+    <string name="ssl_certificate_is_valid" msgid="6825263250774569373">"Este certificado é válido."</string>
+    <string name="issued_to" msgid="454239480274921032">"Emitido para:"</string>
+    <string name="common_name" msgid="2233209299434172646">"Nome comum:"</string>
+    <string name="org_name" msgid="6973561190762085236">"Organização:"</string>
+    <string name="org_unit" msgid="7265981890422070383">"Unidade organizacional:"</string>
+    <string name="issued_by" msgid="2647584988057481566">"Emitido por:"</string>
+    <string name="validity_period" msgid="8818886137545983110">"Validade:"</string>
+    <string name="issued_on" msgid="5895017404361397232">"Emitido em:"</string>
+    <string name="expires_on" msgid="3676242949915959821">"Expira em:"</string>
+    <string name="serial_number" msgid="758814067660862493">"Número de série:"</string>
+    <string name="fingerprints" msgid="4516019619850763049">"Impressões digitais"</string>
+    <string name="sha256_fingerprint" msgid="4391271286477279263">"Impressão digital SHA-256"</string>
+    <string name="sha1_fingerprint" msgid="7930330235269404581">"Impressão digital SHA-1"</string>
+    <string name="activity_chooser_view_see_all" msgid="4292569383976636200">"Ver tudo"</string>
+    <string name="activity_chooser_view_dialog_title_default" msgid="4710013864974040615">"Selecione a atividade"</string>
+    <string name="share_action_provider_share_with" msgid="5247684435979149216">"Compartilhar com"</string>
+    <string name="list_delimeter" msgid="3975117572185494152">", "</string>
+    <string name="sending" msgid="3245653681008218030">"Enviando..."</string>
+    <string name="launchBrowserDefault" msgid="2057951947297614725">"Abrir Navegador?"</string>
+    <string name="SetupCallDefault" msgid="5834948469253758575">"Aceitar chamada?"</string>
+    <string name="activity_resolver_use_always" msgid="8017770747801494933">"Sempre"</string>
+    <string name="activity_resolver_use_once" msgid="2404644797149173758">"Só uma vez"</string>
+    <string name="activity_resolver_work_profiles_support" msgid="185598180676883455">"%1$s não aceita perfis de trabalho"</string>
+    <string name="default_audio_route_name" product="tablet" msgid="4617053898167127471">"Tablet"</string>
+    <string name="default_audio_route_name" product="tv" msgid="9158088547603019321">"TV"</string>
+    <string name="default_audio_route_name" product="default" msgid="4239291273420140123">"Telefone"</string>
+    <string name="default_audio_route_name_headphones" msgid="8119971843803439110">"Fones de ouvido"</string>
+    <string name="default_audio_route_name_dock_speakers" msgid="6240602982276591864">"Alto-falantes da dock"</string>
+    <string name="default_media_route_name_hdmi" msgid="2450970399023478055">"HDMI"</string>
+    <string name="default_audio_route_category_name" msgid="3722811174003886946">"Sistema"</string>
+    <string name="bluetooth_a2dp_audio_route_name" msgid="8575624030406771015">"Áudio Bluetooth"</string>
+    <string name="wireless_display_route_description" msgid="9070346425023979651">"Display sem fio"</string>
+    <string name="media_route_button_content_description" msgid="591703006349356016">"Transmitir"</string>
+    <string name="media_route_chooser_title" msgid="1751618554539087622">"Conectar ao dispositivo"</string>
+    <string name="media_route_chooser_title_for_remote_display" msgid="3395541745872017583">"Transmitir tela para dispositivo"</string>
+    <string name="media_route_chooser_searching" msgid="4776236202610828706">"Procurando dispositivos…"</string>
+    <string name="media_route_chooser_extended_settings" msgid="87015534236701604">"Configurações"</string>
+    <string name="media_route_controller_disconnect" msgid="8966120286374158649">"Desconectar"</string>
+    <string name="media_route_status_scanning" msgid="7279908761758293783">"Verificando..."</string>
+    <string name="media_route_status_connecting" msgid="6422571716007825440">"Conectando..."</string>
+    <string name="media_route_status_available" msgid="6983258067194649391">"Disponível"</string>
+    <string name="media_route_status_not_available" msgid="6739899962681886401">"Não disponível"</string>
+    <string name="media_route_status_in_use" msgid="4533786031090198063">"Em uso"</string>
+    <string name="display_manager_built_in_display_name" msgid="2583134294292563941">"Tela integrada"</string>
+    <string name="display_manager_hdmi_display_name" msgid="1555264559227470109">"Tela HDMI"</string>
+    <string name="display_manager_overlay_display_name" msgid="5142365982271620716">"Sobreposição nº <xliff:g id="ID">%1$d</xliff:g>"</string>
+    <string name="display_manager_overlay_display_title" msgid="652124517672257172">"<xliff:g id="NAME">%1$s</xliff:g>: <xliff:g id="WIDTH">%2$d</xliff:g>x<xliff:g id="HEIGHT">%3$d</xliff:g>, <xliff:g id="DPI">%4$d</xliff:g> dpi"</string>
+    <string name="display_manager_overlay_display_secure_suffix" msgid="6022119702628572080">", seguro"</string>
+    <string name="kg_forgot_pattern_button_text" msgid="8852021467868220608">"Esqueci o padrão"</string>
+    <string name="kg_wrong_pattern" msgid="1850806070801358830">"Padrão incorreto"</string>
+    <string name="kg_wrong_password" msgid="2333281762128113157">"Senha incorreta"</string>
+    <string name="kg_wrong_pin" msgid="1131306510833563801">"PIN incorreto"</string>
+    <string name="kg_too_many_failed_attempts_countdown" msgid="6358110221603297548">"Tente novamente em <xliff:g id="NUMBER">%1$d</xliff:g> segundos."</string>
+    <string name="kg_pattern_instructions" msgid="398978611683075868">"Desenhe seu padrão"</string>
+    <string name="kg_sim_pin_instructions" msgid="2319508550934557331">"Digite o PIN do cartão SIM"</string>
+    <string name="kg_pin_instructions" msgid="2377242233495111557">"Digite o PIN"</string>
+    <string name="kg_password_instructions" msgid="5753646556186936819">"Digite a senha"</string>
+    <string name="kg_puk_enter_puk_hint" msgid="453227143861735537">"O SIM foi desativado. Insira o código PUK para continuar. Entre em contato com a operadora para obter mais detalhes."</string>
+    <string name="kg_puk_enter_pin_hint" msgid="7871604527429602024">"Digite o código PIN desejado"</string>
+    <string name="kg_enter_confirm_pin_hint" msgid="325676184762529976">"Confirme o código PIN desejado"</string>
+    <string name="kg_sim_unlock_progress_dialog_message" msgid="8950398016976865762">"Desbloqueando o cartão SIM…"</string>
+    <string name="kg_password_wrong_pin_code" msgid="1139324887413846912">"Código PIN incorreto."</string>
+    <string name="kg_invalid_sim_pin_hint" msgid="8795159358110620001">"Digite um PIN com quatro a oito números."</string>
+    <string name="kg_invalid_sim_puk_hint" msgid="6025069204539532000">"O código PUK deve ter oito números."</string>
+    <string name="kg_invalid_puk" msgid="3638289409676051243">"Introduza novamente o código PUK correto. Muitas tentativas malsucedidas desativarão permanentemente o SIM."</string>
+    <string name="kg_invalid_confirm_pin_hint" product="default" msgid="7003469261464593516">"Os códigos PIN não coincidem"</string>
+    <string name="kg_login_too_many_attempts" msgid="6486842094005698475">"Muitas tentativas de padrão"</string>
+    <string name="kg_login_instructions" msgid="1100551261265506448">"Para desbloquear, faça login usando sua Conta do Google."</string>
+    <string name="kg_login_username_hint" msgid="5718534272070920364">"Nome de usuário (e-mail)"</string>
+    <string name="kg_login_password_hint" msgid="9057289103827298549">"Senha"</string>
+    <string name="kg_login_submit_button" msgid="5355904582674054702">"Fazer login"</string>
+    <string name="kg_login_invalid_input" msgid="5754664119319872197">"Nome de usuário ou senha inválidos."</string>
+    <string name="kg_login_account_recovery_hint" msgid="5690709132841752974">"Esqueceu seu nome de usuário ou senha?\nAcesse "<b>"google.com.br/accounts/recovery"</b>"."</string>
+    <string name="kg_login_checking_password" msgid="1052685197710252395">"Verificando a conta..."</string>
+    <string name="kg_too_many_failed_pin_attempts_dialog_message" msgid="8276745642049502550">"Você digitou seu PIN incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes. \n\nTente novamente em <xliff:g id="NUMBER_1">%d</xliff:g> segundos."</string>
+    <string name="kg_too_many_failed_password_attempts_dialog_message" msgid="7813713389422226531">"Você digitou sua senha incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes. \n\nTente novamente em <xliff:g id="NUMBER_1">%d</xliff:g> segundos."</string>
+    <string name="kg_too_many_failed_pattern_attempts_dialog_message" msgid="74089475965050805">"Você desenhou sua sequência de desbloqueio incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes. \n\nTente novamente em <xliff:g id="NUMBER_1">%d</xliff:g> segundos."</string>
+    <string name="kg_failed_attempts_almost_at_wipe" product="tablet" msgid="1575557200627128949">"Você tentou desbloquear incorretamente o tablet <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Após mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas malsucedidas, o tablet será redefinido para o padrão de fábrica e todos os dados do usuário serão perdidos."</string>
+    <string name="kg_failed_attempts_almost_at_wipe" product="tv" msgid="5621231220154419413">"Você tentou desbloquear a TV de forma incorreta <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Depois de mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas sem sucesso, a TV será redefinida para os padrões de fábrica e todos os dados do usuário serão perdidos."</string>
+    <string name="kg_failed_attempts_almost_at_wipe" product="default" msgid="4051015943038199910">"Você tentou desbloquear incorretamente o telefone <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Após mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas malsucedidas, o telefone será redefinido para o padrão de fábrica e todos os dados do usuário serão perdidos."</string>
+    <string name="kg_failed_attempts_now_wiping" product="tablet" msgid="2072996269148483637">"Você tentou desbloquear incorretamente o tablet <xliff:g id="NUMBER">%d</xliff:g> vezes. O tablet será redefinido para o padrão de fábrica."</string>
+    <string name="kg_failed_attempts_now_wiping" product="tv" msgid="4987878286750741463">"Você tentou desbloquear a TV de forma incorreta <xliff:g id="NUMBER">%d</xliff:g> vezes. A TV será redefinida agora para os padrões de fábrica."</string>
+    <string name="kg_failed_attempts_now_wiping" product="default" msgid="4817627474419471518">"Você tentou desbloquear incorretamente o telefone <xliff:g id="NUMBER">%d</xliff:g> vezes. O telefone será redefinido para o padrão de fábrica."</string>
+    <string name="kg_failed_attempts_almost_at_login" product="tablet" msgid="3253575572118914370">"Você desenhou sua sequência de desbloqueio incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Se fizer mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas incorretas, será solicitado que você use o login do Google para desbloquear seu tablet.\n\n Tente novamente em <xliff:g id="NUMBER_2">%d</xliff:g> segundos."</string>
+    <string name="kg_failed_attempts_almost_at_login" product="tv" msgid="4224651132862313471">"Você desenhou seu padrão de desbloqueio incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Depois de mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas sem sucesso, será pedido que você desbloqueie sua TV usando uma conta de e-mail.\n\n Tente novamente em <xliff:g id="NUMBER_2">%d</xliff:g> segundos."</string>
+    <string name="kg_failed_attempts_almost_at_login" product="default" msgid="1437638152015574839">"Você desenhou sua sequência de desbloqueio incorretamente <xliff:g id="NUMBER_0">%d</xliff:g> vezes. Se fizer mais <xliff:g id="NUMBER_1">%d</xliff:g> tentativas incorretas, será solicitado que você use o login do Google para desbloquear.\n\n Tente novamente em <xliff:g id="NUMBER_2">%d</xliff:g> segundos."</string>
+    <string name="kg_text_message_separator" product="default" msgid="4160700433287233771">" — "</string>
+    <string name="kg_reordering_delete_drop_target_text" msgid="7899202978204438708">"Remover"</string>
+    <string name="safe_media_volume_warning" product="default" msgid="2276318909314492312">"Aumentar o volume acima do nível recomendado?\n\nOuvir em volume alto por longos períodos pode danificar sua audição."</string>
+    <string name="continue_to_enable_accessibility" msgid="1626427372316070258">"Mantenha pressionado com dois dedos para ativar a acessibilidade."</string>
+    <string name="accessibility_enabled" msgid="1381972048564547685">"Acessibilidade ativada."</string>
+    <string name="enable_accessibility_canceled" msgid="3833923257966635673">"Acessibilidade cancelada."</string>
+    <string name="user_switched" msgid="3768006783166984410">"Usuário atual <xliff:g id="NAME">%1$s</xliff:g>."</string>
+    <string name="user_switching_message" msgid="2871009331809089783">"Alternando para <xliff:g id="NAME">%1$s</xliff:g>…"</string>
+    <string name="owner_name" msgid="2716755460376028154">"Proprietário"</string>
+    <string name="error_message_title" msgid="4510373083082500195">"Erro"</string>
+    <string name="error_message_change_not_allowed" msgid="1347282344200417578">"Esta alteração não é permitida pelo administrador"</string>
+    <string name="app_not_found" msgid="3429141853498927379">"Nenhum app encontrado para executar a ação"</string>
+    <string name="revoke" msgid="5404479185228271586">"Revogar"</string>
+    <string name="mediasize_iso_a0" msgid="1994474252931294172">"ISO A0"</string>
+    <string name="mediasize_iso_a1" msgid="3333060421529791786">"ISO A1"</string>
+    <string name="mediasize_iso_a2" msgid="3097535991925798280">"ISO A2"</string>
+    <string name="mediasize_iso_a3" msgid="3023213259314236123">"ISO A3"</string>
+    <string name="mediasize_iso_a4" msgid="231745325296873764">"ISO A4"</string>
+    <string name="mediasize_iso_a5" msgid="3484327407340865411">"ISO A5"</string>
+    <string name="mediasize_iso_a6" msgid="4861908487129577530">"ISO A6"</string>
+    <string name="mediasize_iso_a7" msgid="5890208588072936130">"ISO A7"</string>
+    <string name="mediasize_iso_a8" msgid="4319425041085816612">"ISO A8"</string>
+    <string name="mediasize_iso_a9" msgid="4882220529506432008">"ISO A9"</string>
+    <string name="mediasize_iso_a10" msgid="2382866026365359391">"ISO A10"</string>
+    <string name="mediasize_iso_b0" msgid="3651827147402009675">"ISO B0"</string>
+    <string name="mediasize_iso_b1" msgid="6072859628278739957">"ISO B1"</string>
+    <string name="mediasize_iso_b2" msgid="1348731852150380378">"ISO B2"</string>
+    <string name="mediasize_iso_b3" msgid="2612510181259261379">"ISO B3"</string>
+    <string name="mediasize_iso_b4" msgid="695151378838115434">"ISO B4"</string>
+    <string name="mediasize_iso_b5" msgid="4863754285582212487">"ISO B5"</string>
+    <string name="mediasize_iso_b6" msgid="5305816292139647241">"ISO B6"</string>
+    <string name="mediasize_iso_b7" msgid="531673542602786624">"ISO B7"</string>
+    <string name="mediasize_iso_b8" msgid="9164474595708850034">"ISO B8"</string>
+    <string name="mediasize_iso_b9" msgid="282102976764774160">"ISO B9"</string>
+    <string name="mediasize_iso_b10" msgid="4517141714407898976">"ISO B10"</string>
+    <string name="mediasize_iso_c0" msgid="3103521357901591100">"ISO C0"</string>
+    <string name="mediasize_iso_c1" msgid="1231954105985048595">"ISO C1"</string>
+    <string name="mediasize_iso_c2" msgid="927702816980087462">"ISO C2"</string>
+    <string name="mediasize_iso_c3" msgid="835154173518304159">"ISO C3"</string>
+    <string name="mediasize_iso_c4" msgid="5095951985108194011">"ISO C4"</string>
+    <string name="mediasize_iso_c5" msgid="1985397450332305739">"ISO C5"</string>
+    <string name="mediasize_iso_c6" msgid="8147421924174693013">"ISO C6"</string>
+    <string name="mediasize_iso_c7" msgid="8993994925276122950">"ISO C7"</string>
+    <string name="mediasize_iso_c8" msgid="6871178104139598957">"ISO C8"</string>
+    <string name="mediasize_iso_c9" msgid="7983532635227561362">"ISO C9"</string>
+    <string name="mediasize_iso_c10" msgid="5040764293406765584">"ISO C10"</string>
+    <string name="mediasize_na_letter" msgid="2841414839888344296">"Carta"</string>
+    <string name="mediasize_na_gvrnmt_letter" msgid="5295836838862962809">"Government Letter"</string>
+    <string name="mediasize_na_legal" msgid="8621364037680465666">"Ofício"</string>
+    <string name="mediasize_na_junior_legal" msgid="3309324162155085904">"Junior Legal"</string>
+    <string name="mediasize_na_ledger" msgid="5567030340509075333">"Ledger"</string>
+    <string name="mediasize_na_tabloid" msgid="4571735038501661757">"Tabloide"</string>
+    <string name="mediasize_na_index_3x5" msgid="5182901917818625126">"Index Card 3x5"</string>
+    <string name="mediasize_na_index_4x6" msgid="7687620625422312396">"Index Card 4x6"</string>
+    <string name="mediasize_na_index_5x8" msgid="8834215284646872800">"Index Card 5x8"</string>
+    <string name="mediasize_na_monarch" msgid="213639906956550754">"Monarch"</string>
+    <string name="mediasize_na_quarto" msgid="835778493593023223">"Quarto"</string>
+    <string name="mediasize_na_foolscap" msgid="1573911237983677138">"Foolscap"</string>
+    <string name="mediasize_chinese_roc_8k" msgid="3626855847189438896">"ROC 8K"</string>
+    <string name="mediasize_chinese_roc_16k" msgid="9182191577022943355">"ROC 16K"</string>
+    <string name="mediasize_chinese_prc_1" msgid="4793232644980170500">"PRC 1"</string>
+    <string name="mediasize_chinese_prc_2" msgid="5404109730975720670">"PRC 2"</string>
+    <string name="mediasize_chinese_prc_3" msgid="1335092253339363526">"PRC 3"</string>
+    <string name="mediasize_chinese_prc_4" msgid="9167997800486569834">"PRC 4"</string>
+    <string name="mediasize_chinese_prc_5" msgid="845875168823541497">"PRC 5"</string>
+    <string name="mediasize_chinese_prc_6" msgid="3220325667692648789">"PRC 6"</string>
+    <string name="mediasize_chinese_prc_7" msgid="1776792138507038527">"PRC 7"</string>
+    <string name="mediasize_chinese_prc_8" msgid="1417176642687456692">"PRC 8"</string>
+    <string name="mediasize_chinese_prc_9" msgid="4785983473123798365">"PRC 9"</string>
+    <string name="mediasize_chinese_prc_10" msgid="7847982299391851899">"PRC 10"</string>
+    <string name="mediasize_chinese_prc_16k" msgid="262793383539980677">"PRC 16K"</string>
+    <string name="mediasize_chinese_om_pa_kai" msgid="5256815579447959814">"Pa Kai"</string>
+    <string name="mediasize_chinese_om_dai_pa_kai" msgid="7336412963441354407">"Dai Pa Kai"</string>
+    <string name="mediasize_chinese_om_jurro_ku_kai" msgid="6324465444100490742">"Jurro Ku Kai"</string>
+    <string name="mediasize_japanese_jis_b10" msgid="1787262845627694376">"JIS B10"</string>
+    <string name="mediasize_japanese_jis_b9" msgid="3336035783663287470">"JIS B9"</string>
+    <string name="mediasize_japanese_jis_b8" msgid="6195398299104345731">"JIS B8"</string>
+    <string name="mediasize_japanese_jis_b7" msgid="1674621886902828884">"JIS B7"</string>
+    <string name="mediasize_japanese_jis_b6" msgid="4170576286062657435">"JIS B6"</string>
+    <string name="mediasize_japanese_jis_b5" msgid="4899297958100032533">"JIS B5"</string>
+    <string name="mediasize_japanese_jis_b4" msgid="4213158129126666847">"JIS B4"</string>
+    <string name="mediasize_japanese_jis_b3" msgid="8513715307410310696">"JIS B3"</string>
+    <string name="mediasize_japanese_jis_b2" msgid="4777690211897131190">"JIS B2"</string>
+    <string name="mediasize_japanese_jis_b1" msgid="4608142385457034603">"JIS B1"</string>
+    <string name="mediasize_japanese_jis_b0" msgid="7587108366572243991">"JIS B0"</string>
+    <string name="mediasize_japanese_jis_exec" msgid="5244075432263649068">"JIS Exec"</string>
+    <string name="mediasize_japanese_chou4" msgid="4941652015032631361">"Chou4"</string>
+    <string name="mediasize_japanese_chou3" msgid="6387319169263957010">"Chou3"</string>
+    <string name="mediasize_japanese_chou2" msgid="1299112025415343982">"Chou2"</string>
+    <string name="mediasize_japanese_hagaki" msgid="8070115620644254565">"Hagaki"</string>
+    <string name="mediasize_japanese_oufuku" msgid="6049065587307896564">"Oufuku"</string>
+    <string name="mediasize_japanese_kahu" msgid="6872696027560065173">"Kahu"</string>
+    <string name="mediasize_japanese_kaku2" msgid="2359077233775455405">"Kaku2"</string>
+    <string name="mediasize_japanese_you4" msgid="2091777168747058008">"You4"</string>
+    <string name="mediasize_unknown_portrait" msgid="3088043641616409762">"Retrato desconhecido"</string>
+    <string name="mediasize_unknown_landscape" msgid="4876995327029361552">"Paisagem desconhecido"</string>
+    <string name="write_fail_reason_cancelled" msgid="7091258378121627624">"Cancelado"</string>
+    <string name="write_fail_reason_cannot_write" msgid="8132505417935337724">"Erro ao gravar o conteúdo"</string>
+    <string name="reason_unknown" msgid="6048913880184628119">"desconhecido"</string>
+    <string name="reason_service_unavailable" msgid="7824008732243903268">"Serviço de impressão não ativado"</string>
+    <string name="print_service_installed_title" msgid="2246317169444081628">"Serviço <xliff:g id="NAME">%s</xliff:g> instalado"</string>
+    <string name="print_service_installed_message" msgid="5897362931070459152">"Toque para ativar"</string>
+    <string name="restr_pin_enter_admin_pin" msgid="783643731895143970">"Inserir PIN do administrador"</string>
+    <string name="restr_pin_enter_pin" msgid="3395953421368476103">"Insira o PIN"</string>
+    <string name="restr_pin_incorrect" msgid="8571512003955077924">"Incorreto"</string>
+    <string name="restr_pin_enter_old_pin" msgid="1462206225512910757">"PIN atual"</string>
+    <string name="restr_pin_enter_new_pin" msgid="5959606691619959184">"Novo PIN"</string>
+    <string name="restr_pin_confirm_pin" msgid="8501523829633146239">"Confirme o novo PIN"</string>
+    <string name="restr_pin_create_pin" msgid="8017600000263450337">"Crie um PIN para modificar restrições"</string>
+    <string name="restr_pin_error_doesnt_match" msgid="2224214190906994548">"Os PINs não coincidem. Tente novamente."</string>
+    <string name="restr_pin_error_too_short" msgid="8173982756265777792">"O PIN é curto demais. Deve ter pelo menos 4 dígitos."</string>
+    <plurals name="restr_pin_countdown" formatted="false" msgid="9061246974881224688">
+      <item quantity="one">Tente novamente em <xliff:g id="COUNT">%d</xliff:g> segundos</item>
+      <item quantity="other">Tente novamente em <xliff:g id="COUNT">%d</xliff:g> segundos</item>
+    </plurals>
+    <string name="restr_pin_try_later" msgid="973144472490532377">"Tente novamente mais tarde"</string>
+    <string name="immersive_cling_title" msgid="8394201622932303336">"Visualização em tela cheia"</string>
+    <string name="immersive_cling_description" msgid="3482371193207536040">"Para sair, deslize de cima para baixo."</string>
+    <string name="immersive_cling_positive" msgid="5016839404568297683">"Entendi"</string>
+    <string name="done_label" msgid="2093726099505892398">"Concluído"</string>
+    <string name="hour_picker_description" msgid="6698199186859736512">"Controle deslizante circular das horas"</string>
+    <string name="minute_picker_description" msgid="8606010966873791190">"Controle deslizante circular dos minutos"</string>
+    <string name="select_hours" msgid="6043079511766008245">"Selecione as horas"</string>
+    <string name="select_minutes" msgid="3974345615920336087">"Selecione os minutos"</string>
+    <string name="select_day" msgid="7774759604701773332">"Selecione o mês e o dia"</string>
+    <string name="select_year" msgid="7952052866994196170">"Selecione o ano"</string>
+    <string name="deleted_key" msgid="7659477886625566590">"<xliff:g id="KEY">%1$s</xliff:g> excluído"</string>
+    <string name="managed_profile_label_badge" msgid="2355652472854327647">"Trabalho: <xliff:g id="LABEL">%1$s</xliff:g>"</string>
+    <string name="lock_to_app_toast" msgid="7570091317001980053">"Para liberar esta tela, toque e mantenha pressionados \"Voltar\" e \"Visão geral\" ao mesmo tempo."</string>
+    <string name="lock_to_app_toast_accessible" msgid="8239120109365070664">"Para liberar esta tela, toque e mantenha pressionado \"Visão geral\"."</string>
+    <string name="lock_to_app_toast_locked" msgid="9125176335701699164">"O app está fixado. A liberação não é permitida neste dispositivo."</string>
+    <string name="lock_to_app_start" msgid="6643342070839862795">"Tela fixada"</string>
+    <string name="lock_to_app_exit" msgid="8598219838213787430">"Tela liberada"</string>
+    <string name="lock_to_app_unlock_pin" msgid="2552556656504331634">"Pedir PIN antes de liberar"</string>
+    <string name="lock_to_app_unlock_pattern" msgid="4182192144797225137">"Pedir padrão de desbloqueio antes de liberar"</string>
+    <string name="lock_to_app_unlock_password" msgid="6380979775916974414">"Pedir senha antes de liberar"</string>
+    <string name="package_installed_device_owner" msgid="8420696545959087545">"Instalado pelo seu administrador"</string>
+    <string name="package_updated_device_owner" msgid="8856631322440187071">"Atualizado pelo administrador"</string>
+    <string name="package_deleted_device_owner" msgid="7650577387493101353">"Excluído pelo seu administrador"</string>
+    <string name="battery_saver_description" msgid="1960431123816253034">"Para ajudar a melhorar a duração da bateria, o economizador de bateria reduz o desempenho e os limites de vibração do dispositivo, os serviços de localização e a maioria dos dados de segundo plano. E-mail, mensagens e outros aplicativos que dependem de sincronização não podem ser atualizados, a não ser que você os abra.\n\nO economizador de bateria é desligado automaticamente quando o dispositivo está sendo carregado."</string>
+    <plurals name="zen_mode_duration_minutes_summary" formatted="false" msgid="4367877408072000848">
+      <item quantity="one">Por %1$d minutos (até às <xliff:g id="FORMATTEDTIME_1">%2$s</xliff:g>)</item>
+      <item quantity="other">Por %1$d minutos (até às <xliff:g id="FORMATTEDTIME_1">%2$s</xliff:g>)</item>
+    </plurals>
+    <plurals name="zen_mode_duration_minutes_summary_short" formatted="false" msgid="6830154222366042597">
+      <item quantity="one">Por %1$d min (até <xliff:g id="FORMATTEDTIME_1">%2$s</xliff:g>)</item>
+      <item quantity="other">Por %1$d min (até <xliff:g id="FORMATTEDTIME_1">%2$s</xliff:g>)</item>
+    </plurals>
+    <plurals name="zen_mode_duration_hours_summary" formatted="false" msgid="8152974162096743862">
+      <item quantity="one">Por %1$d horas (até às <xliff:g id="FORMATTEDTIME_1">%2$s</xliff:g>)</item>
+      <item quantity="other">Por %1$d horas (até às <xliff:g id="FORMATTEDTIME_1">%2$s</xliff:g>)</item>
+    </plurals>
+    <plurals name="zen_mode_duration_hours_summary_short" formatted="false" msgid="4787552595253082371">
+      <item quantity="one">Por %1$d horas (até <xliff:g id="FORMATTEDTIME_1">%2$s</xliff:g>)</item>
+      <item quantity="other">Por %1$d horas (até <xliff:g id="FORMATTEDTIME_1">%2$s</xliff:g>)</item>
+    </plurals>
+    <plurals name="zen_mode_duration_minutes" formatted="false" msgid="5127407202506485571">
+      <item quantity="one">Por %d minutos</item>
+      <item quantity="other">Por %d minutos</item>
+    </plurals>
+    <plurals name="zen_mode_duration_minutes_short" formatted="false" msgid="2199350154433426128">
+      <item quantity="one">Por %d min</item>
+      <item quantity="other">Por %d min</item>
+    </plurals>
+    <plurals name="zen_mode_duration_hours" formatted="false" msgid="3938821308277433854">
+      <item quantity="one">Por %d horas</item>
+      <item quantity="other">Por %d horas</item>
+    </plurals>
+    <plurals name="zen_mode_duration_hours_short" formatted="false" msgid="6748277774662434217">
+      <item quantity="one">Por %d horas</item>
+      <item quantity="other">Por %d horas</item>
+    </plurals>
+    <string name="zen_mode_until" msgid="7336308492289875088">"Até às <xliff:g id="FORMATTEDTIME">%1$s</xliff:g>"</string>
+    <string name="zen_mode_forever" msgid="7420011936770086993">"Até você desativar"</string>
+    <string name="zen_mode_forever_dnd" msgid="3792132696572189081">"Até que você desative \"Não perturbe\""</string>
+    <string name="zen_mode_rule_name_combination" msgid="191109939968076477">"<xliff:g id="FIRST">%1$s</xliff:g> / <xliff:g id="REST">%2$s</xliff:g>"</string>
+    <string name="toolbar_collapse_description" msgid="2821479483960330739">"Recolher"</string>
+    <string name="zen_mode_feature_name" msgid="5254089399895895004">"Não perturbe"</string>
+    <string name="zen_mode_downtime_feature_name" msgid="2626974636779860146">"Tempo de inatividade"</string>
+    <string name="zen_mode_default_weeknights_name" msgid="3081318299464998143">"Durante a semana à noite"</string>
+    <string name="zen_mode_default_weekends_name" msgid="2786495801019345244">"Fim de semana"</string>
+    <string name="zen_mode_default_events_name" msgid="8158334939013085363">"Evento"</string>
+    <string name="muted_by" msgid="6147073845094180001">"Som desativado por <xliff:g id="THIRD_PARTY">%1$s</xliff:g>"</string>
+    <string name="system_error_wipe_data" msgid="6608165524785354962">"Há um problema interno com seu dispositivo. Ele pode ficar instável até que você faça a redefinição para configuração original."</string>
+    <string name="system_error_manufacturer" msgid="8086872414744210668">"Há um problema interno com seu dispositivo. Entre em contato com o fabricante para saber mais detalhes."</string>
+    <string name="stk_cc_ussd_to_dial" msgid="5202342984749947872">"A solicitação USSD foi modificada para a solicitação DIAL."</string>
+    <string name="stk_cc_ussd_to_ss" msgid="2345360594181405482">"A solicitação USSD foi modificada para a solicitação SS."</string>
+    <string name="stk_cc_ussd_to_ussd" msgid="7466087659967191653">"A solicitação USSD foi modificada para a nova solicitação USSD."</string>
+    <string name="stk_cc_ss_to_dial" msgid="2151304435775557162">"A solicitação SS foi modificada para a solicitação DIAL."</string>
+    <string name="stk_cc_ss_to_ussd" msgid="3951862188105305589">"A solicitação SS foi modificada para a solicitação USSD."</string>
+    <string name="stk_cc_ss_to_ss" msgid="5470768854991452695">"A solicitação SS foi modificada para a nova solicitação SS."</string>
+    <string name="notification_work_profile_content_description" msgid="4600554564103770764">"Perfil de trabalho"</string>
+    <string name="usb_midi_peripheral_name" msgid="7221113987741003817">"Porta USB periférica Android"</string>
+    <string name="usb_midi_peripheral_manufacturer_name" msgid="7176526170008970168">"Android"</string>
+    <string name="usb_midi_peripheral_product_name" msgid="4971827859165280403">"Porta USB periférica"</string>
+    <string name="floating_toolbar_open_overflow_description" msgid="4797287862999444631">"Mais opções"</string>
+    <string name="floating_toolbar_close_overflow_description" msgid="559796923090723804">"Fechar barra flutuante"</string>
+    <plurals name="selected_count" formatted="false" msgid="7187339492915744615">
+      <item quantity="one"><xliff:g id="COUNT_1">%1$d</xliff:g> selecionados</item>
+      <item quantity="other"><xliff:g id="COUNT_1">%1$d</xliff:g> selecionados</item>
+    </plurals>
+</resources>
diff --git a/core/res/res/values-pt/strings.xml b/core/res/res/values-pt/strings.xml
index 9e8bb89..ffbe8d6 100644
--- a/core/res/res/values-pt/strings.xml
+++ b/core/res/res/values-pt/strings.xml
@@ -229,17 +229,17 @@
     <string name="permgrouplab_contacts" msgid="3657758145679177612">"Contatos"</string>
     <string name="permgroupdesc_contacts" msgid="6951499528303668046">"acessar seus contatos"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"Local"</string>
-    <string name="permgroupdesc_location" msgid="1346617465127855033">"acessar o local do dispositivo"</string>
+    <string name="permgroupdesc_location" msgid="1346617465127855033">"acesse o local do dispositivo"</string>
     <string name="permgrouplab_calendar" msgid="5863508437783683902">"Agenda"</string>
     <string name="permgroupdesc_calendar" msgid="3889615280211184106">"acessar sua agenda"</string>
     <string name="permgrouplab_sms" msgid="228308803364967808">"SMS"</string>
     <string name="permgroupdesc_sms" msgid="4656988620100940350">"enviar e ver mensagens SMS"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"Armazenamento"</string>
-    <string name="permgroupdesc_storage" msgid="637758554581589203">"acessar fotos, mídia e arquivos do seu dispositivo"</string>
+    <string name="permgroupdesc_storage" msgid="637758554581589203">"acesse fotos, mídia e arquivos do seu dispositivo"</string>
     <string name="permgrouplab_microphone" msgid="171539900250043464">"Microfone"</string>
-    <string name="permgroupdesc_microphone" msgid="4988812113943554584">"gravar áudio"</string>
+    <string name="permgroupdesc_microphone" msgid="4988812113943554584">"grave áudio"</string>
     <string name="permgrouplab_camera" msgid="4820372495894586615">"Câmera"</string>
-    <string name="permgroupdesc_camera" msgid="3250611594678347720">"tirar fotos e gravar vídeos"</string>
+    <string name="permgroupdesc_camera" msgid="3250611594678347720">"tire fotos e grave vídeos"</string>
     <string name="permgrouplab_phone" msgid="5229115638567440675">"Telefone"</string>
     <string name="permgroupdesc_phone" msgid="6234224354060641055">"fazer e gerenciar chamadas telefônicas"</string>
     <string name="permgrouplab_sensors" msgid="416037179223226722">"Sensores corporais"</string>
diff --git a/core/res/res/values-ru/strings.xml b/core/res/res/values-ru/strings.xml
index 5194017..fc67b8c 100644
--- a/core/res/res/values-ru/strings.xml
+++ b/core/res/res/values-ru/strings.xml
@@ -1060,7 +1060,7 @@
     <string name="select_input_method" msgid="8547250819326693584">"Выбор раскладки"</string>
     <string name="configure_input_methods" msgid="4769971288371946846">"Выбрать раскладку"</string>
     <string name="show_ime" msgid="9157568568695230830">"Показать способ ввода"</string>
-    <string name="hardware" msgid="7517821086888990278">"Аппаратура"</string>
+    <string name="hardware" msgid="7517821086888990278">"Аппаратная"</string>
     <string name="select_keyboard_layout_notification_title" msgid="1407367017263030773">"Выберите раскладку клавиатуры"</string>
     <string name="select_keyboard_layout_notification_message" msgid="4465907700449257063">"Нажмите, чтобы выбрать раскладку клавиатуры."</string>
     <string name="fast_scroll_alphabet" msgid="5433275485499039199">" ABCDEFGHIJKLMNOPQRSTUVWXYZ"</string>
@@ -1342,87 +1342,87 @@
     <string name="error_message_change_not_allowed" msgid="1347282344200417578">"Это действие запрещено администратором"</string>
     <string name="app_not_found" msgid="3429141853498927379">"Невозможно обработать это действие"</string>
     <string name="revoke" msgid="5404479185228271586">"Отменить"</string>
-    <string name="mediasize_iso_a0" msgid="1994474252931294172">"ISO A0 (841х1189 мм)"</string>
-    <string name="mediasize_iso_a1" msgid="3333060421529791786">"ISO A1 (594х841 мм)"</string>
-    <string name="mediasize_iso_a2" msgid="3097535991925798280">"ISO A2 (420х594 мм)"</string>
-    <string name="mediasize_iso_a3" msgid="3023213259314236123">"ISO A3 (297х420 мм)"</string>
-    <string name="mediasize_iso_a4" msgid="231745325296873764">"ISO A4 (210х297 мм)"</string>
-    <string name="mediasize_iso_a5" msgid="3484327407340865411">"ISO A5 (148х210 мм)"</string>
-    <string name="mediasize_iso_a6" msgid="4861908487129577530">"ISO A6 (105х148 мм)"</string>
-    <string name="mediasize_iso_a7" msgid="5890208588072936130">"ISO A7 (74х105 мм)"</string>
-    <string name="mediasize_iso_a8" msgid="4319425041085816612">"ISO A8 (52х74 мм)"</string>
-    <string name="mediasize_iso_a9" msgid="4882220529506432008">"ISO A9 (37х52 мм)"</string>
-    <string name="mediasize_iso_a10" msgid="2382866026365359391">"ISO A10 (26х37 мм)"</string>
-    <string name="mediasize_iso_b0" msgid="3651827147402009675">"ISO B0 (1000х1414 мм)"</string>
-    <string name="mediasize_iso_b1" msgid="6072859628278739957">"ISO B1 (707х1000 мм)"</string>
-    <string name="mediasize_iso_b2" msgid="1348731852150380378">"ISO B2 (500х707 мм)"</string>
-    <string name="mediasize_iso_b3" msgid="2612510181259261379">"ISO B3 (353х500 мм)"</string>
-    <string name="mediasize_iso_b4" msgid="695151378838115434">"ISO B4 (250х353 мм)"</string>
-    <string name="mediasize_iso_b5" msgid="4863754285582212487">"ISO B5 (176х250 мм)"</string>
-    <string name="mediasize_iso_b6" msgid="5305816292139647241">"ISO B6 (125х176 мм)"</string>
-    <string name="mediasize_iso_b7" msgid="531673542602786624">"ISO B7 (88х125 мм)"</string>
-    <string name="mediasize_iso_b8" msgid="9164474595708850034">"ISO B8 (62х88 мм)"</string>
-    <string name="mediasize_iso_b9" msgid="282102976764774160">"ISO B9 (44х62 мм)"</string>
-    <string name="mediasize_iso_b10" msgid="4517141714407898976">"ISO B10 (31х44 мм)"</string>
-    <string name="mediasize_iso_c0" msgid="3103521357901591100">"ISO C0 (917х1297 мм)"</string>
-    <string name="mediasize_iso_c1" msgid="1231954105985048595">"ISO C1 (648х917 мм)"</string>
-    <string name="mediasize_iso_c2" msgid="927702816980087462">"ISO C2 (458х648 мм)"</string>
-    <string name="mediasize_iso_c3" msgid="835154173518304159">"ISO C3 (324х458 мм)"</string>
-    <string name="mediasize_iso_c4" msgid="5095951985108194011">"ISO C4 (229х324 мм)"</string>
-    <string name="mediasize_iso_c5" msgid="1985397450332305739">"ISO C5 (162х229 мм)"</string>
-    <string name="mediasize_iso_c6" msgid="8147421924174693013">"ISO C6 (114х162 мм)"</string>
-    <string name="mediasize_iso_c7" msgid="8993994925276122950">"ISO C7 (81х114 мм)"</string>
-    <string name="mediasize_iso_c8" msgid="6871178104139598957">"ISO C8 (57х81 мм)"</string>
-    <string name="mediasize_iso_c9" msgid="7983532635227561362">"ISO C9 (40х57 мм)"</string>
-    <string name="mediasize_iso_c10" msgid="5040764293406765584">"ISO C10 (28х40 мм)"</string>
-    <string name="mediasize_na_letter" msgid="2841414839888344296">"Letter (216х279 мм)"</string>
-    <string name="mediasize_na_gvrnmt_letter" msgid="5295836838862962809">"Government Letter (203х267 мм)"</string>
-    <string name="mediasize_na_legal" msgid="8621364037680465666">"Legal (216х356 мм)"</string>
-    <string name="mediasize_na_junior_legal" msgid="3309324162155085904">"Junior Legal (203 х 127 мм)"</string>
-    <string name="mediasize_na_ledger" msgid="5567030340509075333">"Ledger (432х279 мм)"</string>
-    <string name="mediasize_na_tabloid" msgid="4571735038501661757">"Tabloid (279х432 мм)"</string>
-    <string name="mediasize_na_index_3x5" msgid="5182901917818625126">"Index Card 3x5 (76x127 мм)"</string>
-    <string name="mediasize_na_index_4x6" msgid="7687620625422312396">"Index Card 4x6 (102x152 мм)"</string>
-    <string name="mediasize_na_index_5x8" msgid="8834215284646872800">"Index Card 5x8 (127x203 мм)"</string>
-    <string name="mediasize_na_monarch" msgid="213639906956550754">"Monarch (184x267 мм)"</string>
-    <string name="mediasize_na_quarto" msgid="835778493593023223">"Quarto (203x254 мм)"</string>
-    <string name="mediasize_na_foolscap" msgid="1573911237983677138">"Foolscap (203x330 мм)"</string>
-    <string name="mediasize_chinese_roc_8k" msgid="3626855847189438896">"ROC 8K (270x390 мм)"</string>
-    <string name="mediasize_chinese_roc_16k" msgid="9182191577022943355">"ROC 16K (195x270 мм)"</string>
-    <string name="mediasize_chinese_prc_1" msgid="4793232644980170500">"PRC 1 (102x165 мм)"</string>
-    <string name="mediasize_chinese_prc_2" msgid="5404109730975720670">"PRC 2 (102x176 мм)"</string>
-    <string name="mediasize_chinese_prc_3" msgid="1335092253339363526">"PRC 3 (125x176 мм)"</string>
-    <string name="mediasize_chinese_prc_4" msgid="9167997800486569834">"PRC 4 (110x208 мм)"</string>
-    <string name="mediasize_chinese_prc_5" msgid="845875168823541497">"PRC 5 (110x220 мм)"</string>
-    <string name="mediasize_chinese_prc_6" msgid="3220325667692648789">"PRC 6 (120x320 мм)"</string>
-    <string name="mediasize_chinese_prc_7" msgid="1776792138507038527">"PRC 7 (160x230 мм)"</string>
-    <string name="mediasize_chinese_prc_8" msgid="1417176642687456692">"PRC 8 (120x309 мм)"</string>
-    <string name="mediasize_chinese_prc_9" msgid="4785983473123798365">"PRC 9 (229x324 мм)"</string>
-    <string name="mediasize_chinese_prc_10" msgid="7847982299391851899">"PRC 10 (324x458 мм)"</string>
-    <string name="mediasize_chinese_prc_16k" msgid="262793383539980677">"PRC 16K (146x215 мм)"</string>
-    <string name="mediasize_chinese_om_pa_kai" msgid="5256815579447959814">"Pa Kai (146x215 мм)"</string>
-    <string name="mediasize_chinese_om_dai_pa_kai" msgid="7336412963441354407">"Dai Pa Kai (275х395 мм)"</string>
-    <string name="mediasize_chinese_om_jurro_ku_kai" msgid="6324465444100490742">"Jurro Ku Kai (275x395 мм)"</string>
-    <string name="mediasize_japanese_jis_b10" msgid="1787262845627694376">"JIS B10 (32x45 мм)"</string>
-    <string name="mediasize_japanese_jis_b9" msgid="3336035783663287470">"JIS B9 (45x64 мм)"</string>
-    <string name="mediasize_japanese_jis_b8" msgid="6195398299104345731">"JIS B8 (64x91 мм)"</string>
-    <string name="mediasize_japanese_jis_b7" msgid="1674621886902828884">"JIS B7 (91x128 мм)"</string>
-    <string name="mediasize_japanese_jis_b6" msgid="4170576286062657435">"JIS B6 (128x182 мм)"</string>
-    <string name="mediasize_japanese_jis_b5" msgid="4899297958100032533">"JIS B5 (182x257 мм)"</string>
-    <string name="mediasize_japanese_jis_b4" msgid="4213158129126666847">"JIS B4 (257x364 мм)"</string>
-    <string name="mediasize_japanese_jis_b3" msgid="8513715307410310696">"JIS B3 (364x515 мм)"</string>
-    <string name="mediasize_japanese_jis_b2" msgid="4777690211897131190">"JIS B2 (515x728 мм)"</string>
-    <string name="mediasize_japanese_jis_b1" msgid="4608142385457034603">"JIS B1 (728x1030 мм)"</string>
-    <string name="mediasize_japanese_jis_b0" msgid="7587108366572243991">"JIS B0 (1030x1456 мм)"</string>
-    <string name="mediasize_japanese_jis_exec" msgid="5244075432263649068">"JIS Exec (216x330 мм)"</string>
-    <string name="mediasize_japanese_chou4" msgid="4941652015032631361">"Chou4 (90x205 мм)"</string>
-    <string name="mediasize_japanese_chou3" msgid="6387319169263957010">"Chou3 (120x235 мм)"</string>
-    <string name="mediasize_japanese_chou2" msgid="1299112025415343982">"Chou2 (111,1x146 мм)"</string>
-    <string name="mediasize_japanese_hagaki" msgid="8070115620644254565">"Hagaki (100x148 мм)"</string>
-    <string name="mediasize_japanese_oufuku" msgid="6049065587307896564">"Oufuku (148x200 мм)"</string>
-    <string name="mediasize_japanese_kahu" msgid="6872696027560065173">"Kaku (240x322,1 мм)"</string>
-    <string name="mediasize_japanese_kaku2" msgid="2359077233775455405">"Kaku2 (240x332 мм)"</string>
-    <string name="mediasize_japanese_you4" msgid="2091777168747058008">"You4 (105x235 мм)"</string>
+    <string name="mediasize_iso_a0" msgid="1994474252931294172">"ISO A0"</string>
+    <string name="mediasize_iso_a1" msgid="3333060421529791786">"ISO A1"</string>
+    <string name="mediasize_iso_a2" msgid="3097535991925798280">"ISO A2"</string>
+    <string name="mediasize_iso_a3" msgid="3023213259314236123">"ISO A3"</string>
+    <string name="mediasize_iso_a4" msgid="231745325296873764">"ISO A4"</string>
+    <string name="mediasize_iso_a5" msgid="3484327407340865411">"ISO A5"</string>
+    <string name="mediasize_iso_a6" msgid="4861908487129577530">"ISO A6"</string>
+    <string name="mediasize_iso_a7" msgid="5890208588072936130">"ISO A7"</string>
+    <string name="mediasize_iso_a8" msgid="4319425041085816612">"ISO A8"</string>
+    <string name="mediasize_iso_a9" msgid="4882220529506432008">"ISO A9"</string>
+    <string name="mediasize_iso_a10" msgid="2382866026365359391">"ISO A10"</string>
+    <string name="mediasize_iso_b0" msgid="3651827147402009675">"ISO B0"</string>
+    <string name="mediasize_iso_b1" msgid="6072859628278739957">"ISO B1"</string>
+    <string name="mediasize_iso_b2" msgid="1348731852150380378">"ISO B2"</string>
+    <string name="mediasize_iso_b3" msgid="2612510181259261379">"ISO B3"</string>
+    <string name="mediasize_iso_b4" msgid="695151378838115434">"ISO B4"</string>
+    <string name="mediasize_iso_b5" msgid="4863754285582212487">"ISO B5"</string>
+    <string name="mediasize_iso_b6" msgid="5305816292139647241">"ISO B6"</string>
+    <string name="mediasize_iso_b7" msgid="531673542602786624">"ISO B7"</string>
+    <string name="mediasize_iso_b8" msgid="9164474595708850034">"ISO B8"</string>
+    <string name="mediasize_iso_b9" msgid="282102976764774160">"ISO B9"</string>
+    <string name="mediasize_iso_b10" msgid="4517141714407898976">"ISO B10"</string>
+    <string name="mediasize_iso_c0" msgid="3103521357901591100">"ISO C0"</string>
+    <string name="mediasize_iso_c1" msgid="1231954105985048595">"ISO C1"</string>
+    <string name="mediasize_iso_c2" msgid="927702816980087462">"ISO C2"</string>
+    <string name="mediasize_iso_c3" msgid="835154173518304159">"ISO C3"</string>
+    <string name="mediasize_iso_c4" msgid="5095951985108194011">"ISO C4"</string>
+    <string name="mediasize_iso_c5" msgid="1985397450332305739">"ISO C5"</string>
+    <string name="mediasize_iso_c6" msgid="8147421924174693013">"ISO C6"</string>
+    <string name="mediasize_iso_c7" msgid="8993994925276122950">"ISO C7"</string>
+    <string name="mediasize_iso_c8" msgid="6871178104139598957">"ISO C8"</string>
+    <string name="mediasize_iso_c9" msgid="7983532635227561362">"ISO C9"</string>
+    <string name="mediasize_iso_c10" msgid="5040764293406765584">"ISO C10"</string>
+    <string name="mediasize_na_letter" msgid="2841414839888344296">"Letter"</string>
+    <string name="mediasize_na_gvrnmt_letter" msgid="5295836838862962809">"Government Letter"</string>
+    <string name="mediasize_na_legal" msgid="8621364037680465666">"Legal"</string>
+    <string name="mediasize_na_junior_legal" msgid="3309324162155085904">"Junior Legal"</string>
+    <string name="mediasize_na_ledger" msgid="5567030340509075333">"Ledger"</string>
+    <string name="mediasize_na_tabloid" msgid="4571735038501661757">"Tabloid"</string>
+    <string name="mediasize_na_index_3x5" msgid="5182901917818625126">"Index Card 3x5"</string>
+    <string name="mediasize_na_index_4x6" msgid="7687620625422312396">"Index Card 4x6"</string>
+    <string name="mediasize_na_index_5x8" msgid="8834215284646872800">"Index Card 5x8"</string>
+    <string name="mediasize_na_monarch" msgid="213639906956550754">"Monarch"</string>
+    <string name="mediasize_na_quarto" msgid="835778493593023223">"Quarto"</string>
+    <string name="mediasize_na_foolscap" msgid="1573911237983677138">"Foolscap"</string>
+    <string name="mediasize_chinese_roc_8k" msgid="3626855847189438896">"ROC 8K"</string>
+    <string name="mediasize_chinese_roc_16k" msgid="9182191577022943355">"ROC 16K"</string>
+    <string name="mediasize_chinese_prc_1" msgid="4793232644980170500">"PRC 1"</string>
+    <string name="mediasize_chinese_prc_2" msgid="5404109730975720670">"PRC 2"</string>
+    <string name="mediasize_chinese_prc_3" msgid="1335092253339363526">"PRC 3"</string>
+    <string name="mediasize_chinese_prc_4" msgid="9167997800486569834">"PRC 4"</string>
+    <string name="mediasize_chinese_prc_5" msgid="845875168823541497">"PRC 5"</string>
+    <string name="mediasize_chinese_prc_6" msgid="3220325667692648789">"PRC 6"</string>
+    <string name="mediasize_chinese_prc_7" msgid="1776792138507038527">"PRC 7"</string>
+    <string name="mediasize_chinese_prc_8" msgid="1417176642687456692">"PRC 8"</string>
+    <string name="mediasize_chinese_prc_9" msgid="4785983473123798365">"PRC 9"</string>
+    <string name="mediasize_chinese_prc_10" msgid="7847982299391851899">"PRC 10"</string>
+    <string name="mediasize_chinese_prc_16k" msgid="262793383539980677">"PRC 16K"</string>
+    <string name="mediasize_chinese_om_pa_kai" msgid="5256815579447959814">"Pa Kai"</string>
+    <string name="mediasize_chinese_om_dai_pa_kai" msgid="7336412963441354407">"Dai Pa Kai"</string>
+    <string name="mediasize_chinese_om_jurro_ku_kai" msgid="6324465444100490742">"Jurro Ku Kai"</string>
+    <string name="mediasize_japanese_jis_b10" msgid="1787262845627694376">"JIS B10"</string>
+    <string name="mediasize_japanese_jis_b9" msgid="3336035783663287470">"JIS B9"</string>
+    <string name="mediasize_japanese_jis_b8" msgid="6195398299104345731">"JIS B8"</string>
+    <string name="mediasize_japanese_jis_b7" msgid="1674621886902828884">"JIS B7"</string>
+    <string name="mediasize_japanese_jis_b6" msgid="4170576286062657435">"JIS B6"</string>
+    <string name="mediasize_japanese_jis_b5" msgid="4899297958100032533">"JIS B5"</string>
+    <string name="mediasize_japanese_jis_b4" msgid="4213158129126666847">"JIS B4"</string>
+    <string name="mediasize_japanese_jis_b3" msgid="8513715307410310696">"JIS B3"</string>
+    <string name="mediasize_japanese_jis_b2" msgid="4777690211897131190">"JIS B2"</string>
+    <string name="mediasize_japanese_jis_b1" msgid="4608142385457034603">"JIS B1"</string>
+    <string name="mediasize_japanese_jis_b0" msgid="7587108366572243991">"JIS B0"</string>
+    <string name="mediasize_japanese_jis_exec" msgid="5244075432263649068">"JIS Exec"</string>
+    <string name="mediasize_japanese_chou4" msgid="4941652015032631361">"Chou4"</string>
+    <string name="mediasize_japanese_chou3" msgid="6387319169263957010">"Chou3"</string>
+    <string name="mediasize_japanese_chou2" msgid="1299112025415343982">"Chou2"</string>
+    <string name="mediasize_japanese_hagaki" msgid="8070115620644254565">"Hagaki"</string>
+    <string name="mediasize_japanese_oufuku" msgid="6049065587307896564">"Oufuku"</string>
+    <string name="mediasize_japanese_kahu" msgid="6872696027560065173">"Kaku"</string>
+    <string name="mediasize_japanese_kaku2" msgid="2359077233775455405">"Kaku2"</string>
+    <string name="mediasize_japanese_you4" msgid="2091777168747058008">"You4"</string>
     <string name="mediasize_unknown_portrait" msgid="3088043641616409762">"Неизвестный вертикальный формат"</string>
     <string name="mediasize_unknown_landscape" msgid="4876995327029361552">"Неизвестный горизонтальный формат"</string>
     <string name="write_fail_reason_cancelled" msgid="7091258378121627624">"Печать отменена"</string>
diff --git a/core/res/res/values-sr/strings.xml b/core/res/res/values-sr/strings.xml
index 112549a..d46b007 100644
--- a/core/res/res/values-sr/strings.xml
+++ b/core/res/res/values-sr/strings.xml
@@ -228,15 +228,15 @@
     <string name="user_owner_label" msgid="2804351898001038951">"Лично"</string>
     <string name="managed_profile_label" msgid="6260850669674791528">"Посао"</string>
     <string name="permgrouplab_contacts" msgid="3657758145679177612">"Контакти"</string>
-    <string name="permgroupdesc_contacts" msgid="6951499528303668046">"приступ контактима"</string>
+    <string name="permgroupdesc_contacts" msgid="6951499528303668046">"приступи контактима"</string>
     <string name="permgrouplab_location" msgid="7275582855722310164">"Локација"</string>
     <string name="permgroupdesc_location" msgid="1346617465127855033">"приступ локацији овог уређаја"</string>
     <string name="permgrouplab_calendar" msgid="5863508437783683902">"Календар"</string>
-    <string name="permgroupdesc_calendar" msgid="3889615280211184106">"приступ календару"</string>
+    <string name="permgroupdesc_calendar" msgid="3889615280211184106">"приступи календару"</string>
     <string name="permgrouplab_sms" msgid="228308803364967808">"SMS"</string>
-    <string name="permgroupdesc_sms" msgid="4656988620100940350">"слање и преглед SMS порука"</string>
+    <string name="permgroupdesc_sms" msgid="4656988620100940350">"шаље и прегледа SMS поруке"</string>
     <string name="permgrouplab_storage" msgid="1971118770546336966">"Складиште"</string>
-    <string name="permgroupdesc_storage" msgid="637758554581589203">"приступ сликама, медијима и датотекама на уређају"</string>
+    <string name="permgroupdesc_storage" msgid="637758554581589203">"приступи сликама, медијима и датотекама на уређају"</string>
     <string name="permgrouplab_microphone" msgid="171539900250043464">"Микрофон"</string>
     <string name="permgroupdesc_microphone" msgid="4988812113943554584">"снимање аудио снимака"</string>
     <string name="permgrouplab_camera" msgid="4820372495894586615">"Камера"</string>
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 82eb2c4..54848e9 100755
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -408,6 +408,7 @@
     <integer translatable="false" name="config_wifi_framework_wifi_score_good_link_speed_24">24</integer>
     <integer translatable="false" name="config_wifi_framework_wifi_score_good_link_speed_5">36</integer>
     <string  translatable="false" name="config_wifi_random_mac_oui">DA-A1-19</string>
+    <string  translatable="false" name="config_wifi_framework_sap_2G_channel_list">1,6,11</string>
 
     <bool translatable="false" name="config_wifi_framework_cellular_handover_enable_user_triggered_adjustment">true</bool>
 
@@ -480,9 +481,6 @@
     <!-- Integer indicating how to handle beacons with uninitialized RSSI value of 0 -->
     <integer translatable="false" name="config_wifi_framework_scan_result_rssi_level_patchup_value">-85</integer>
 
-    <!-- Boolean indicating associated scan are allowed -->
-    <bool translatable="false" name="config_wifi_framework_enable_associated_autojoin_scan">true</bool>
-
     <!-- Boolean indicating associated network selection is allowed -->
     <bool translatable="false" name="config_wifi_framework_enable_associated_network_selection">true</bool>
 
@@ -2264,4 +2262,12 @@
  
     <!-- How long history of previous vibrations should be kept for the dumpsys. -->
     <integer name="config_previousVibrationsDumpLimit">20</integer>
+
+    <!-- Number of retries Cell Data should attempt for a given error code before
+         restarting the modem.
+         Error codes not listed will not lead to modem restarts.
+         Array of "code#,retry#"  -->
+    <string-array name="config_cell_retries_per_error_code">
+    </string-array>
+
 </resources>
diff --git a/core/res/res/values/dimens_material.xml b/core/res/res/values/dimens_material.xml
index b980777..558afa7 100644
--- a/core/res/res/values/dimens_material.xml
+++ b/core/res/res/values/dimens_material.xml
@@ -127,7 +127,7 @@
     <!-- Text size for the time picker header HH:MM label. This value is large
          enough that we don't need to use scaled pixels, dp is fine. -->
     <dimen name="timepicker_time_label_size">60dp</dimen>
-    <dimen name="timepicker_ampm_label_size">16sp</dimen>
+    <dimen name="timepicker_ampm_label_size">16dp</dimen>
     <dimen name="timepicker_ampm_horizontal_padding">16dp</dimen>
     <dimen name="timepicker_am_top_padding">4dp</dimen>
     <dimen name="timepicker_pm_top_padding">4dp</dimen>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index d41031c..8070986 100755
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -297,7 +297,6 @@
   <java-symbol type="bool" name="config_hasRecents" />
   <java-symbol type="bool" name="config_windowShowCircularMask" />
   <java-symbol type="bool" name="config_windowEnableCircularEmulatorDisplayOverlay" />
-  <java-symbol type="bool" name="config_wifi_framework_enable_associated_autojoin_scan" />
   <java-symbol type="bool" name="config_wifi_framework_enable_associated_network_selection" />
   <java-symbol type="bool" name="config_wifi_only_link_same_credential_configurations" />
   <java-symbol type="bool" name="config_wifi_enable_disconnection_debounce" />
@@ -338,6 +337,7 @@
   <java-symbol type="integer"  name="config_wifi_active_rx_cur_ma" />
   <java-symbol type="integer"  name="config_wifi_tx_cur_ma" />
   <java-symbol type="integer"  name="config_wifi_operating_voltage_mv" />
+  <java-symbol type="string"  name="config_wifi_framework_sap_2G_channel_list" />
 
   <java-symbol type="bool" name="editable_voicemailnumber" />
 
@@ -1360,6 +1360,7 @@
   <java-symbol type="layout" name="restrictions_pin_setup" />
   <java-symbol type="layout" name="immersive_mode_cling" />
   <java-symbol type="layout" name="user_switching_dialog" />
+  <java-symbol type="layout" name="common_tab_settings" />
 
   <java-symbol type="anim" name="slide_in_child_bottom" />
   <java-symbol type="anim" name="slide_in_right" />
@@ -2311,4 +2312,8 @@
 
   <java-symbol type="bool" name="allow_stacked_button_bar" />
   <java-symbol type="bool" name="config_eap_sim_based_auth_supported" />
+
+  <java-symbol type="array" name="config_cell_retries_per_error_code" />
+  <java-symbol type="drawable" name="ic_more_items" />
+
 </resources>
diff --git a/docs/html/design/wear/structure.jd b/docs/html/design/wear/structure.jd
index c1d9ef9..768aa7f 100644
--- a/docs/html/design/wear/structure.jd
+++ b/docs/html/design/wear/structure.jd
@@ -166,8 +166,11 @@
   <li>A map that asks the user to drop a pin should exit when the pin is dropped.</li>
   <li>A short game can exit when the game finishes.</li>
   <li>A drawing app can finish after 5 seconds of inactivity.</li>
+
+  <p class="note">An app generally should not exit in {@link android.app.Activity#onPause onPause()}.  This is because events such as <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#Heads-up">Heads-up Notifications</a> can trigger the {@link android.app.Activity#onPause() onPause()} callback.</p>
 </ul>
 
+
 <h3>Manually exiting</h3>
 
 <p>Even with logical exit points like these, some cases may exist where the user may want to
diff --git a/docs/html/distribute/essentials/quality/tv.jd b/docs/html/distribute/essentials/quality/tv.jd
index 20018c3..c7f6fcb 100644
--- a/docs/html/distribute/essentials/quality/tv.jd
+++ b/docs/html/distribute/essentials/quality/tv.jd
@@ -418,9 +418,9 @@
   </td>
   <td>
     <p style="margin-bottom:.5em;">
-      If the app continues to play sound after the user has left, the app provides a <em>Now
-      Playing</em> card on the home screen recommendation row so users can return to the app to
-      control playback.
+      If the app continues to play sound or video after the user has left, the
+      app provides a <em>Now Playing</em> card on the home screen recommendation
+      row so users can return to the app to control playback.
       (<a href="{@docRoot}training/tv/playback/now-playing.html">Learn how</a>)
     </p>
   </td>
diff --git a/docs/html/preview/behavior-changes.jd b/docs/html/preview/behavior-changes.jd
index 6ee0af0..5c8ef41 100644
--- a/docs/html/preview/behavior-changes.jd
+++ b/docs/html/preview/behavior-changes.jd
@@ -373,7 +373,7 @@
 <h2 id="behavior-afw">Android for Work Changes</h2>
 <p>This preview includes the following behavior changes for Android for Work:</p>
 <ul>
-<li><strong>Work contacts in personal contexts.</strong> The Google Dialer
+  <li><strong>Work contacts in personal contexts.</strong> The Google Dialer
 Call Log now displays work contacts when the user views past calls.
 Setting
 {@link android.app.admin.DevicePolicyManager#setCrossProfileCallerIdDisabled(android.content.ComponentName, boolean) setCrossProfileCallerIdDisabled()}
@@ -381,21 +381,19 @@
 displayed along with personal contacts to devices over Bluetooth only if
 you set {@code DevicePolicyManager.setBluetoothContactSharingDisabled()} to {@code false}. By
 default, it is set to {@code true}.
-</li>
-<li><strong>WiFi configuration removal:</strong> WiFi configurations added by a Profile Owner
+  </li>
+  <li><strong>WiFi configuration removal:</strong> WiFi configurations added by a Profile Owner
 (for example, through calls to the
 {@link android.net.wifi.WifiManager#addNetwork(android.net.wifi.WifiConfiguration)
-addNetwork()} method) are now removed if that work profile is deleted.</li>
-
-<li><strong>WiFi configuration lockdown:</strong> Any WiFi configuration created by
+addNetwork()} method) are now removed if that work profile is deleted.
+  </li>
+  <li><strong>WiFi configuration lockdown:</strong> Any WiFi configuration created by
   an active Device Owner can no longer be modified or deleted by the user if
   <code>Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN</code> is non-zero.
   The user can still create and modify their own WiFi configurations. Active Device
   Owners have the privilege of editing/removing any WiFi configurations, including
   those not created by them.
-</li>
-
-</li>
+  </li>
 <li><strong>Download Work Policy Controller via Google account addition:</strong> When a Google
 account that requires management via a Work Policy Controller (WPC) app is added to a device
 outside of a managed context, the add account flow now prompts the user to install the
@@ -408,7 +406,7 @@
 affect camera apps running on the primary user. </li>
   <li>In addition, the
 {@link android.app.admin.DevicePolicyManager#setKeyguardDisabledFeatures(android.content.ComponentName,int) setKeyguardDisabledFeatures()}
-    method is now available for Profile Owners, in addition to Device Owners. </li>
+    method is now available for Profile Owners, as well as to Device Owners. </li>
   <li>A Profile Owner can set these keyguard restrictions:
     <ul>
     <li>{@link android.app.admin.DevicePolicyManager#KEYGUARD_DISABLE_TRUST_AGENTS} and
@@ -422,9 +420,19 @@
   <li>The {@link android.app.admin.DevicePolicyManager#setScreenCaptureDisabled(android.content.ComponentName, boolean) setScreenCaptureDisabled()} method now also blocks the assist structure when an app of the given user is in the foreground. </li>
   <li><code>EXTRA_PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM</code> now defaults to SHA-256. SHA-1 is still supported for backwards compatibility but will be removed in future. <code>EXTRA_PROVISIONING_DEVICE_ADMIN_SIGNATURE_CHECKSUM</code> now only accepts SHA-256.</li>
   <li>Device initializer APIs which existed in the MNC preview are now removed. They will not appear in the final M release.</li>
-    <li>Android for Work APIs are optimized for M runtime permissions, including Work profiles, assist layer, and others. New DevicePolicyManager permission APIs don't affect pre-M apps.</li>
-    </ul>
-    <li><strong>Changes to global settings</strong> &mdash; the settings below can no longer be set via {@link android.app.admin.DevicePolicyManager#setGlobalSetting(android.content.ComponentName, java.lang.String, java.lang.String) setGlobalSettings()}</code>:
+    <li><code>EXTRA_PROVISIONING_RESET_PROTECTION_PARAMETERS</code> is removed so NFC bump provisioning cannot programmatically unlock a factory reset protected device.</li>
+    <li>Android for Work APIs are optimized for M runtime permissions, including Work profiles, assist layer, and others. New <code>DevicePolicyManager</code> permission APIs don't affect pre-M apps.</li>
+    </ul></li>
+
+<li><strong>Changes to other APIs</strong>:
+<ul>
+    <li>Data Usage: The {@code android.app.usage.NetworkUsageStats} class has been renamed {@code android.app.usage.NetworkStats}.</li>
+</ul>
+    </li>
+
+    <li><strong>Changes to global settings</strong>:
+    <ul>
+    <li>These settings can no longer be set via {@link android.app.admin.DevicePolicyManager#setGlobalSetting(android.content.ComponentName, java.lang.String, java.lang.String) setGlobalSettings()}</code>:
 <ul>
     <li><code>BLUETOOTH_ON</code></li>
     <li><code>DEVELOPMENT_SETTINGS_ENABLED</code></li>
@@ -433,4 +441,10 @@
     <li><code>WIFI_ON</code></li> 
 </ul>
     </li>
+    <li>These global settings can now be set via <code><a href="/reference/android/app/admin/DevicePolicyManager.html#setGlobalSetting(android.content.ComponentName, java.lang.String, java.lang.String)">setGlobalSettings()</a></code>:
+    <ul>
+    <li><code>WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN</code></li>
+    </ul>
+    </li>
+    </ul>
 </ul>
diff --git a/docs/html/training/tv/start/hardware.jd b/docs/html/training/tv/start/hardware.jd
index 57651e6..5747b56 100644
--- a/docs/html/training/tv/start/hardware.jd
+++ b/docs/html/training/tv/start/hardware.jd
@@ -163,7 +163,7 @@
         android:required="false"/&gt;
 &lt;uses-feature android:name="android.hardware.nfc"
         android:required="false"/&gt;
-&lt;uses-feature android:name="android.hardware.gps"
+&lt;uses-feature android:name="android.hardware.location.gps"
         android:required="false"/&gt;
 &lt;uses-feature android:name="android.hardware.microphone"
         android:required="false"/&gt;
diff --git a/graphics/java/android/graphics/drawable/VectorDrawable.java b/graphics/java/android/graphics/drawable/VectorDrawable.java
index 24cb055..1cfccc4 100644
--- a/graphics/java/android/graphics/drawable/VectorDrawable.java
+++ b/graphics/java/android/graphics/drawable/VectorDrawable.java
@@ -200,6 +200,11 @@
     private static final int LINEJOIN_ROUND = 1;
     private static final int LINEJOIN_BEVEL = 2;
 
+    // Cap the bitmap size, such that it won't hurt the performance too much
+    // and it won't crash due to a very large scale.
+    // The drawable will look blurry above this size.
+    private static final int MAX_CACHED_BITMAP_SIZE = 2048;
+
     private static final boolean DBG_VECTOR_DRAWABLE = false;
 
     private VectorDrawableState mVectorState;
@@ -219,6 +224,11 @@
     private int mDpiScaledHeight = 0;
     private Insets mDpiScaleInsets = Insets.NONE;
 
+    // Temp variable, only for saving "new" operation at the draw() time.
+    private final float[] mTmpFloats = new float[9];
+    private final Matrix mTmpMatrix = new Matrix();
+    private final Rect mTmpBounds = new Rect();
+
     public VectorDrawable() {
         this(null, null);
     }
@@ -262,44 +272,59 @@
 
     @Override
     public void draw(Canvas canvas) {
-        final Rect bounds = getBounds();
-        if (bounds.width() <= 0 || bounds.height() <= 0) {
+        // We will offset the bounds for drawBitmap, so copyBounds() here instead
+        // of getBounds().
+        copyBounds(mTmpBounds);
+        if (mTmpBounds.width() <= 0 || mTmpBounds.height() <= 0) {
             // Nothing to draw
             return;
         }
 
-        final int saveCount = canvas.save();
-        final boolean needMirroring = needMirroring();
+        // Color filters always override tint filters.
+        final ColorFilter colorFilter = (mColorFilter == null ? mTintFilter : mColorFilter);
 
-        canvas.translate(bounds.left, bounds.top);
+        // The imageView can scale the canvas in different ways, in order to
+        // avoid blurry scaling, we have to draw into a bitmap with exact pixel
+        // size first. This bitmap size is determined by the bounds and the
+        // canvas scale.
+        canvas.getMatrix(mTmpMatrix);
+        mTmpMatrix.getValues(mTmpFloats);
+        float canvasScaleX = Math.abs(mTmpFloats[Matrix.MSCALE_X]);
+        float canvasScaleY = Math.abs(mTmpFloats[Matrix.MSCALE_Y]);
+        int scaledWidth = (int) (mTmpBounds.width() * canvasScaleX);
+        int scaledHeight = (int) (mTmpBounds.height() * canvasScaleY);
+        scaledWidth = Math.min(MAX_CACHED_BITMAP_SIZE, scaledWidth);
+        scaledHeight = Math.min(MAX_CACHED_BITMAP_SIZE, scaledHeight);
+
+        if (scaledWidth <= 0 || scaledHeight <= 0) {
+            return;
+        }
+
+        final int saveCount = canvas.save();
+        canvas.translate(mTmpBounds.left, mTmpBounds.top);
+
+        // Handle RTL mirroring.
+        final boolean needMirroring = needMirroring();
         if (needMirroring) {
-            canvas.translate(bounds.width(), 0);
+            canvas.translate(mTmpBounds.width(), 0);
             canvas.scale(-1.0f, 1.0f);
         }
 
-        // Color filters always override tint filters.
-        final ColorFilter colorFilter = mColorFilter == null ? mTintFilter : mColorFilter;
+        // At this point, canvas has been translated to the right position.
+        // And we use this bound for the destination rect for the drawBitmap, so
+        // we offset to (0, 0);
+        mTmpBounds.offsetTo(0, 0);
 
+        mVectorState.createCachedBitmapIfNeeded(scaledWidth, scaledHeight);
         if (!mAllowCaching) {
-            // AnimatedVectorDrawable
-            if (!mVectorState.hasTranslucentRoot()) {
-                mVectorState.mVPathRenderer.draw(
-                        canvas, bounds.width(), bounds.height(), colorFilter);
-            } else {
-                mVectorState.createCachedBitmapIfNeeded(bounds);
-                mVectorState.updateCachedBitmap(bounds);
-                mVectorState.drawCachedBitmapWithRootAlpha(canvas, colorFilter);
-            }
+            mVectorState.updateCachedBitmap(scaledWidth, scaledHeight);
         } else {
-            // Static Vector Drawable case.
-            mVectorState.createCachedBitmapIfNeeded(bounds);
             if (!mVectorState.canReuseCache()) {
-                mVectorState.updateCachedBitmap(bounds);
+                mVectorState.updateCachedBitmap(scaledWidth, scaledHeight);
                 mVectorState.updateCacheStates();
             }
-            mVectorState.drawCachedBitmapWithRootAlpha(canvas, colorFilter);
         }
-
+        mVectorState.drawCachedBitmapWithRootAlpha(canvas, colorFilter, mTmpBounds);
         canvas.restoreToCount(saveCount);
     }
 
@@ -770,10 +795,11 @@
             }
         }
 
-        public void drawCachedBitmapWithRootAlpha(Canvas canvas, ColorFilter filter) {
+        public void drawCachedBitmapWithRootAlpha(Canvas canvas, ColorFilter filter,
+                Rect originalBounds) {
             // The bitmap's size is the same as the bounds.
             final Paint p = getPaint(filter);
-            canvas.drawBitmap(mCachedBitmap, 0, 0, p);
+            canvas.drawBitmap(mCachedBitmap, null, originalBounds, p);
         }
 
         public boolean hasTranslucentRoot() {
@@ -797,16 +823,15 @@
             return mTempPaint;
         }
 
-        public void updateCachedBitmap(Rect bounds) {
+        public void updateCachedBitmap(int width, int height) {
             mCachedBitmap.eraseColor(Color.TRANSPARENT);
             Canvas tmpCanvas = new Canvas(mCachedBitmap);
-            mVPathRenderer.draw(tmpCanvas, bounds.width(), bounds.height(), null);
+            mVPathRenderer.draw(tmpCanvas, width, height, null);
         }
 
-        public void createCachedBitmapIfNeeded(Rect bounds) {
-            if (mCachedBitmap == null || !canReuseBitmap(bounds.width(),
-                    bounds.height())) {
-                mCachedBitmap = Bitmap.createBitmap(bounds.width(), bounds.height(),
+        public void createCachedBitmapIfNeeded(int width, int height) {
+            if (mCachedBitmap == null || !canReuseBitmap(width, height)) {
+                mCachedBitmap = Bitmap.createBitmap(width, height,
                         Bitmap.Config.ARGB_8888);
                 mCacheDirty = true;
             }
diff --git a/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java b/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
index 5459bea..441ee66 100644
--- a/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
+++ b/keystore/java/android/security/keystore/AndroidKeyStoreAuthenticatedAESCipherSpi.java
@@ -51,7 +51,7 @@
 abstract class AndroidKeyStoreAuthenticatedAESCipherSpi extends AndroidKeyStoreCipherSpiBase {
 
     abstract static class GCM extends AndroidKeyStoreAuthenticatedAESCipherSpi {
-        private static final int MIN_SUPPORTED_TAG_LENGTH_BITS = 96;
+        static final int MIN_SUPPORTED_TAG_LENGTH_BITS = 96;
         private static final int MAX_SUPPORTED_TAG_LENGTH_BITS = 128;
         private static final int DEFAULT_TAG_LENGTH_BITS = 128;
         private static final int IV_LENGTH_BYTES = 12;
diff --git a/keystore/java/android/security/keystore/AndroidKeyStoreKeyGeneratorSpi.java b/keystore/java/android/security/keystore/AndroidKeyStoreKeyGeneratorSpi.java
index 6a7930a..4c174f1 100644
--- a/keystore/java/android/security/keystore/AndroidKeyStoreKeyGeneratorSpi.java
+++ b/keystore/java/android/security/keystore/AndroidKeyStoreKeyGeneratorSpi.java
@@ -171,7 +171,7 @@
                         "Key size must be positive: " + mKeySizeBits);
             } else if ((mKeySizeBits % 8) != 0) {
                 throw new InvalidAlgorithmParameterException(
-                        "Key size in must be a multiple of 8: " + mKeySizeBits);
+                        "Key size must be a multiple of 8: " + mKeySizeBits);
             }
 
             try {
@@ -197,48 +197,36 @@
                         }
                     }
                 }
-                if (spec.isDigestsSpecified()) {
-                    // Digest(s) explicitly specified in the spec
-                    mKeymasterDigests = KeyProperties.Digest.allToKeymaster(spec.getDigests());
-                    if (mKeymasterDigest != -1) {
-                        // Key algorithm implies a digest -- ensure it's specified in the spec as
-                        // first digest.
-                        if (!com.android.internal.util.ArrayUtils.contains(
-                                mKeymasterDigests, mKeymasterDigest)) {
+
+                if (mKeymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_HMAC) {
+                    // JCA HMAC key algorithm implies a digest (e.g., HmacSHA256 key algorithm
+                    // implies SHA-256 digest). Because keymaster HMAC key is authorized only for
+                    // one digest, we don't let algorithm parameter spec override the digest implied
+                    // by the key. If the spec specifies digests at all, it must specify only one
+                    // digest, the only implied by key algorithm.
+                    mKeymasterDigests = new int[] {mKeymasterDigest};
+                    if (spec.isDigestsSpecified()) {
+                        // Digest(s) explicitly specified in the spec. Check that the list
+                        // consists of exactly one digest, the one implied by key algorithm.
+                        int[] keymasterDigestsFromSpec =
+                                KeyProperties.Digest.allToKeymaster(spec.getDigests());
+                        if ((keymasterDigestsFromSpec.length != 1)
+                                || (keymasterDigestsFromSpec[0] != mKeymasterDigest)) {
                             throw new InvalidAlgorithmParameterException(
-                                    "Digests specified in algorithm parameters ("
-                                    + Arrays.asList(spec.getDigests()) + ") must include "
-                                    + " the digest "
+                                    "Unsupported digests specification: "
+                                    + Arrays.asList(spec.getDigests()) + ". Only "
                                     + KeyProperties.Digest.fromKeymaster(mKeymasterDigest)
-                                    + " implied by key algorithm");
-                        }
-                        if (mKeymasterDigests[0] != mKeymasterDigest) {
-                            // The first digest is not the one implied by the key algorithm.
-                            // Swap the implied digest with the first one.
-                            for (int i = 0; i < mKeymasterDigests.length; i++) {
-                                if (mKeymasterDigests[i] == mKeymasterDigest) {
-                                    mKeymasterDigests[i] = mKeymasterDigests[0];
-                                    mKeymasterDigests[0] = mKeymasterDigest;
-                                    break;
-                                }
-                            }
+                                    + " supported for this HMAC key algorithm");
                         }
                     }
                 } else {
-                    // No digest specified in the spec
-                    if (mKeymasterDigest != -1) {
-                        // Key algorithm implies a digest -- use that digest
-                        mKeymasterDigests = new int[] {mKeymasterDigest};
+                    // Key algorithm does not imply a digest.
+                    if (spec.isDigestsSpecified()) {
+                        mKeymasterDigests = KeyProperties.Digest.allToKeymaster(spec.getDigests());
                     } else {
                         mKeymasterDigests = EmptyArray.INT;
                     }
                 }
-                if (mKeymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_HMAC) {
-                    if (mKeymasterDigests.length == 0) {
-                        throw new InvalidAlgorithmParameterException(
-                                "At least one digest algorithm must be specified");
-                    }
-                }
 
                 // Check that user authentication related parameters are acceptable. This method
                 // will throw an IllegalStateException if there are issues (e.g., secure lock screen
@@ -284,6 +272,11 @@
         KeymasterUtils.addUserAuthArgs(args,
                 spec.isUserAuthenticationRequired(),
                 spec.getUserAuthenticationValidityDurationSeconds());
+        KeymasterUtils.addMinMacLengthAuthorizationIfNecessary(
+                args,
+                mKeymasterAlgorithm,
+                mKeymasterBlockModes,
+                mKeymasterDigests);
         args.addDateIfNotNull(KeymasterDefs.KM_TAG_ACTIVE_DATETIME, spec.getKeyValidityStart());
         args.addDateIfNotNull(KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME,
                 spec.getKeyValidityForOriginationEnd());
diff --git a/keystore/java/android/security/keystore/AndroidKeyStoreSpi.java b/keystore/java/android/security/keystore/AndroidKeyStoreSpi.java
index e9f19cd..915d86f 100644
--- a/keystore/java/android/security/keystore/AndroidKeyStoreSpi.java
+++ b/keystore/java/android/security/keystore/AndroidKeyStoreSpi.java
@@ -41,6 +41,7 @@
 import java.security.KeyStoreSpi;
 import java.security.NoSuchAlgorithmException;
 import java.security.PrivateKey;
+import java.security.ProviderException;
 import java.security.PublicKey;
 import java.security.UnrecoverableKeyException;
 import java.security.cert.Certificate;
@@ -605,50 +606,43 @@
             args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, keymasterAlgorithm);
 
             int[] keymasterDigests;
-            int keymasterDigest = KeyProperties.KeyAlgorithm.toKeymasterDigest(key.getAlgorithm());
-            if (params.isDigestsSpecified()) {
-                // Digest(s) specified in parameters
-                keymasterDigests = KeyProperties.Digest.allToKeymaster(params.getDigests());
-                if (keymasterDigest != -1) {
-                    // Digest also specified in the JCA key algorithm name.
-                    if (!com.android.internal.util.ArrayUtils.contains(
-                            keymasterDigests, keymasterDigest)) {
-                        throw new KeyStoreException("Digest specified in key algorithm "
-                                + key.getAlgorithm() + " not specified in protection parameters: "
-                                + Arrays.asList(params.getDigests()));
-                    }
-                    // When the key is read back from keystore we reconstruct the JCA key algorithm
-                    // name from the KM_TAG_ALGORITHM and the first KM_TAG_DIGEST. Thus we need to
-                    // ensure that the digest reflected in the JCA key algorithm name is the first
-                    // KM_TAG_DIGEST tag.
-                    if (keymasterDigests[0] != keymasterDigest) {
-                        // The first digest is not the one implied by the JCA key algorithm name.
-                        // Swap the implied digest with the first one.
-                        for (int i = 0; i < keymasterDigests.length; i++) {
-                            if (keymasterDigests[i] == keymasterDigest) {
-                                keymasterDigests[i] = keymasterDigests[0];
-                                keymasterDigests[0] = keymasterDigest;
-                                break;
-                            }
-                        }
+            if (keymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_HMAC) {
+                // JCA HMAC key algorithm implies a digest (e.g., HmacSHA256 key algorithm
+                // implies SHA-256 digest). Because keymaster HMAC key is authorized only for one
+                // digest, we don't let import parameters override the digest implied by the key.
+                // If the parameters specify digests at all, they must specify only one digest, the
+                // only implied by key algorithm.
+                int keymasterImpliedDigest =
+                        KeyProperties.KeyAlgorithm.toKeymasterDigest(key.getAlgorithm());
+                if (keymasterImpliedDigest == -1) {
+                    throw new ProviderException(
+                            "HMAC key algorithm digest unknown for key algorithm "
+                                    + key.getAlgorithm());
+                }
+                keymasterDigests = new int[] {keymasterImpliedDigest};
+                if (params.isDigestsSpecified()) {
+                    // Digest(s) explicitly specified in params -- check that the list consists of
+                    // exactly one digest, the one implied by key algorithm.
+                    int[] keymasterDigestsFromParams =
+                            KeyProperties.Digest.allToKeymaster(params.getDigests());
+                    if ((keymasterDigestsFromParams.length != 1)
+                            || (keymasterDigestsFromParams[0] != keymasterImpliedDigest)) {
+                        throw new KeyStoreException(
+                                "Unsupported digests specification: "
+                                + Arrays.asList(params.getDigests()) + ". Only "
+                                + KeyProperties.Digest.fromKeymaster(keymasterImpliedDigest)
+                                + " supported for HMAC key algorithm " + key.getAlgorithm());
                     }
                 }
             } else {
-                // No digest specified in parameters
-                if (keymasterDigest != -1) {
-                    // Digest specified in the JCA key algorithm name.
-                    keymasterDigests = new int[] {keymasterDigest};
+                // Key algorithm does not imply a digest.
+                if (params.isDigestsSpecified()) {
+                    keymasterDigests = KeyProperties.Digest.allToKeymaster(params.getDigests());
                 } else {
                     keymasterDigests = EmptyArray.INT;
                 }
             }
             args.addEnums(KeymasterDefs.KM_TAG_DIGEST, keymasterDigests);
-            if (keymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_HMAC) {
-                if (keymasterDigests.length == 0) {
-                    throw new KeyStoreException("At least one digest algorithm must be specified"
-                            + " for key algorithm " + key.getAlgorithm());
-                }
-            }
 
             @KeyProperties.PurposeEnum int purposes = params.getPurposes();
             int[] keymasterBlockModes =
@@ -678,6 +672,11 @@
             KeymasterUtils.addUserAuthArgs(args,
                     params.isUserAuthenticationRequired(),
                     params.getUserAuthenticationValidityDurationSeconds());
+            KeymasterUtils.addMinMacLengthAuthorizationIfNecessary(
+                    args,
+                    keymasterAlgorithm,
+                    keymasterBlockModes,
+                    keymasterDigests);
             args.addDateIfNotNull(KeymasterDefs.KM_TAG_ACTIVE_DATETIME,
                     params.getKeyValidityStart());
             args.addDateIfNotNull(KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME,
diff --git a/keystore/java/android/security/keystore/KeyGenParameterSpec.java b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
index 919dd48..faaa1a6 100644
--- a/keystore/java/android/security/keystore/KeyGenParameterSpec.java
+++ b/keystore/java/android/security/keystore/KeyGenParameterSpec.java
@@ -642,7 +642,8 @@
          * <p>This must be specified for signing/verification keys and RSA encryption/decryption
          * keys used with RSA OAEP padding scheme because these operations involve a digest. For
          * HMAC keys, the default is the digest associated with the key algorithm (e.g.,
-         * {@code SHA-256} for key algorithm {@code HmacSHA256}).
+         * {@code SHA-256} for key algorithm {@code HmacSHA256}). HMAC keys cannot be authorized
+         * for more than one digest.
          *
          * <p>For private keys used for TLS/SSL client or server authentication it is usually
          * necessary to authorize the use of no digest ({@link KeyProperties#DIGEST_NONE}). This is
diff --git a/keystore/java/android/security/keystore/KeyProtection.java b/keystore/java/android/security/keystore/KeyProtection.java
index 5b4b3e7..ec0ef24 100644
--- a/keystore/java/android/security/keystore/KeyProtection.java
+++ b/keystore/java/android/security/keystore/KeyProtection.java
@@ -423,7 +423,8 @@
          * <p>This must be specified for signing/verification keys and RSA encryption/decryption
          * keys used with RSA OAEP padding scheme because these operations involve a digest. For
          * HMAC keys, the default is the digest specified in {@link Key#getAlgorithm()} (e.g.,
-         * {@code SHA-256} for key algorithm {@code HmacSHA256}).
+         * {@code SHA-256} for key algorithm {@code HmacSHA256}). HMAC keys cannot be authorized
+         * for more than one digest.
          *
          * <p>For private keys used for TLS/SSL client or server authentication it is usually
          * necessary to authorize the use of no digest ({@link KeyProperties#DIGEST_NONE}). This is
diff --git a/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java b/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java
index ea0f4b9..dbb79bc 100644
--- a/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java
+++ b/keystore/java/android/security/keystore/KeyStoreCryptoOperationChunkedStreamer.java
@@ -19,12 +19,14 @@
 import android.os.IBinder;
 import android.security.KeyStore;
 import android.security.KeyStoreException;
+import android.security.keymaster.KeymasterDefs;
 import android.security.keymaster.OperationResult;
 
 import libcore.util.EmptyArray;
 
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.security.ProviderException;
 
 /**
  * Helper for streaming a crypto operation's input and output via {@link KeyStore} service's
@@ -135,14 +137,15 @@
                 mBuffered = EmptyArray.BYTE;
                 mBufferedOffset = 0;
                 mBufferedLength = 0;
-            } else if (opResult.inputConsumed == 0) {
+            } else if (opResult.inputConsumed <= 0) {
                 // Nothing was consumed. More input needed.
                 if (inputLength > 0) {
                     // More input is available, but it wasn't included into the previous chunk
                     // because the chunk reached its maximum permitted size.
                     // Shouldn't have happened.
-                    throw new IllegalStateException("Nothing consumed from max-sized chunk: "
-                            + chunk.length + " bytes");
+                    throw new KeyStoreException(KeymasterDefs.KM_ERROR_UNKNOWN_ERROR,
+                            "Keystore consumed nothing from max-sized chunk: " + chunk.length
+                                    + " bytes");
                 }
                 mBuffered = chunk;
                 mBufferedOffset = 0;
@@ -153,8 +156,9 @@
                 mBufferedOffset = opResult.inputConsumed;
                 mBufferedLength = chunk.length - opResult.inputConsumed;
             } else {
-                throw new IllegalStateException("Consumed more than provided: "
-                        + opResult.inputConsumed + ", provided: " + chunk.length);
+                throw new KeyStoreException(KeymasterDefs.KM_ERROR_UNKNOWN_ERROR,
+                        "Keystore consumed more input than provided. Provided: " + chunk.length
+                                + ", consumed: " + opResult.inputConsumed);
             }
 
             if ((opResult.output != null) && (opResult.output.length > 0)) {
@@ -165,7 +169,7 @@
                         try {
                             bufferedOutput.write(opResult.output);
                         } catch (IOException e) {
-                            throw new IllegalStateException("Failed to buffer output", e);
+                            throw new ProviderException("Failed to buffer output", e);
                         }
                     }
                 } else {
@@ -179,7 +183,7 @@
                         try {
                             bufferedOutput.write(opResult.output);
                         } catch (IOException e) {
-                            throw new IllegalStateException("Failed to buffer output", e);
+                            throw new ProviderException("Failed to buffer output", e);
                         }
                         result = bufferedOutput.toByteArray();
                     }
@@ -229,27 +233,71 @@
             return EmptyArray.BYTE;
         }
 
-        byte[] chunk = ArrayUtils.subarray(mBuffered, mBufferedOffset, mBufferedLength);
-        mBuffered = EmptyArray.BYTE;
-        mBufferedLength = 0;
-        mBufferedOffset = 0;
+        // Keep invoking the update operation with remaining buffered data until either all of the
+        // buffered data is consumed or until update fails to consume anything.
+        ByteArrayOutputStream bufferedOutput = null;
+        while (mBufferedLength > 0) {
+            byte[] chunk = ArrayUtils.subarray(mBuffered, mBufferedOffset, mBufferedLength);
+            OperationResult opResult = mKeyStoreStream.update(chunk);
+            if (opResult == null) {
+                throw new KeyStoreConnectException();
+            } else if (opResult.resultCode != KeyStore.NO_ERROR) {
+                throw KeyStore.getKeyStoreException(opResult.resultCode);
+            }
 
-        OperationResult opResult = mKeyStoreStream.update(chunk);
-        if (opResult == null) {
-            throw new KeyStoreConnectException();
-        } else if (opResult.resultCode != KeyStore.NO_ERROR) {
-            throw KeyStore.getKeyStoreException(opResult.resultCode);
+            if (opResult.inputConsumed <= 0) {
+                // Nothing was consumed. Break out of the loop to avoid an infinite loop.
+                break;
+            }
+
+            if (opResult.inputConsumed >= chunk.length) {
+                // All of the input was consumed
+                mBuffered = EmptyArray.BYTE;
+                mBufferedOffset = 0;
+                mBufferedLength = 0;
+            } else {
+                // Some of the input was not consumed
+                mBuffered = chunk;
+                mBufferedOffset = opResult.inputConsumed;
+                mBufferedLength = chunk.length - opResult.inputConsumed;
+            }
+
+            if (opResult.inputConsumed > chunk.length) {
+                throw new KeyStoreException(KeymasterDefs.KM_ERROR_UNKNOWN_ERROR,
+                        "Keystore consumed more input than provided. Provided: "
+                                + chunk.length + ", consumed: " + opResult.inputConsumed);
+            }
+
+            if ((opResult.output != null) && (opResult.output.length > 0)) {
+                // Some output was produced by this update operation
+                if (bufferedOutput == null) {
+                    // No output buffered yet.
+                    if (mBufferedLength == 0) {
+                        // No more output will be produced by this flush operation
+                        mProducedOutputSizeBytes += opResult.output.length;
+                        return opResult.output;
+                    } else {
+                        // More output might be produced by this flush operation -- buffer output.
+                        bufferedOutput = new ByteArrayOutputStream();
+                    }
+                }
+                // Buffer the output from this update operation
+                try {
+                    bufferedOutput.write(opResult.output);
+                } catch (IOException e) {
+                    throw new ProviderException("Failed to buffer output", e);
+                }
+            }
         }
 
-        if (opResult.inputConsumed < chunk.length) {
-            throw new IllegalStateException("Keystore failed to consume all input. Provided: "
-                    + chunk.length + ", consumed: " + opResult.inputConsumed);
-        } else if (opResult.inputConsumed > chunk.length) {
-            throw new IllegalStateException("Keystore consumed more input than provided"
-                    + " . Provided: " + chunk.length + ", consumed: " + opResult.inputConsumed);
+        if (mBufferedLength > 0) {
+            throw new KeyStoreException(KeymasterDefs.KM_ERROR_INVALID_INPUT_LENGTH,
+                    "Keystore failed to consume last "
+                            + ((mBufferedLength != 1) ? (mBufferedLength + " bytes") : "byte")
+                            + " of input");
         }
 
-        byte[] result = (opResult.output != null) ? opResult.output : EmptyArray.BYTE;
+        byte[] result = (bufferedOutput != null) ? bufferedOutput.toByteArray() : EmptyArray.BYTE;
         mProducedOutputSizeBytes += result.length;
         return result;
     }
diff --git a/keystore/java/android/security/keystore/KeymasterUtils.java b/keystore/java/android/security/keystore/KeymasterUtils.java
index 92d636c..feafbfa 100644
--- a/keystore/java/android/security/keystore/KeymasterUtils.java
+++ b/keystore/java/android/security/keystore/KeymasterUtils.java
@@ -22,6 +22,8 @@
 import android.security.keymaster.KeymasterArguments;
 import android.security.keymaster.KeymasterDefs;
 
+import java.security.ProviderException;
+
 /**
  * @hide
  */
@@ -133,4 +135,45 @@
                     userAuthenticationValidityDurationSeconds);
         }
     }
+
+    /**
+     * Adds {@code KM_TAG_MIN_MAC_LENGTH} tag, if necessary, to the keymaster arguments for
+     * generating or importing a key. This tag may only be needed for symmetric keys (e.g., HMAC,
+     * AES-GCM).
+     */
+    public static void addMinMacLengthAuthorizationIfNecessary(KeymasterArguments args,
+            int keymasterAlgorithm,
+            int[] keymasterBlockModes,
+            int[] keymasterDigests) {
+        switch (keymasterAlgorithm) {
+            case KeymasterDefs.KM_ALGORITHM_AES:
+                if (com.android.internal.util.ArrayUtils.contains(
+                        keymasterBlockModes, KeymasterDefs.KM_MODE_GCM)) {
+                    // AES GCM key needs the minimum length of AEAD tag specified.
+                    args.addUnsignedInt(KeymasterDefs.KM_TAG_MIN_MAC_LENGTH,
+                            AndroidKeyStoreAuthenticatedAESCipherSpi.GCM
+                                    .MIN_SUPPORTED_TAG_LENGTH_BITS);
+                }
+                break;
+            case KeymasterDefs.KM_ALGORITHM_HMAC:
+                // HMAC key needs the minimum length of MAC set to the output size of the associated
+                // digest. This is because we do not offer a way to generate shorter MACs and
+                // don't offer a way to verify MACs (other than by generating them).
+                if (keymasterDigests.length != 1) {
+                    throw new ProviderException(
+                            "Unsupported number of authorized digests for HMAC key: "
+                                    + keymasterDigests.length
+                                    + ". Exactly one digest must be authorized");
+                }
+                int keymasterDigest = keymasterDigests[0];
+                int digestOutputSizeBits = getDigestOutputSizeBits(keymasterDigest);
+                if (digestOutputSizeBits == -1) {
+                    throw new ProviderException(
+                            "HMAC key authorized for unsupported digest: "
+                                    + KeyProperties.Digest.fromKeymaster(keymasterDigest));
+                }
+                args.addUnsignedInt(KeymasterDefs.KM_TAG_MIN_MAC_LENGTH, digestOutputSizeBits);
+                break;
+        }
+    }
 }
diff --git a/libs/hwui/ClipArea.cpp b/libs/hwui/ClipArea.cpp
index eb520b4..b1a6844 100644
--- a/libs/hwui/ClipArea.cpp
+++ b/libs/hwui/ClipArea.cpp
@@ -263,10 +263,11 @@
 bool ClipArea::rectangleModeClipRectWithTransform(const Rect& r,
         const mat4* transform, SkRegion::Op op) {
 
-    // TODO: we should be able to handle kReplace_Op efficiently without
-    // going through RegionMode and later falling back into RectangleMode.
-
-    if (op != SkRegion::kIntersect_Op) {
+    if (op == SkRegion::kReplace_Op && transform->rectToRect()) {
+        mClipRect = r;
+        transform->mapRect(mClipRect);
+        return true;
+    } else if (op != SkRegion::kIntersect_Op) {
         enterRegionMode();
         return regionModeClipRectWithTransform(r, transform, op);
     }
diff --git a/libs/hwui/ClipArea.h b/libs/hwui/ClipArea.h
index e284af0..51ef27b 100644
--- a/libs/hwui/ClipArea.h
+++ b/libs/hwui/ClipArea.h
@@ -153,6 +153,8 @@
     }
 
     void regionFromPath(const SkPath& path, SkRegion& pathAsRegion) {
+        // TODO: this should not mask every path to the viewport - this makes it impossible to use
+        // paths to clip to larger areas (which is valid e.g. with SkRegion::kReplace_Op)
         pathAsRegion.setPath(path, createViewportRegion());
     }
 
diff --git a/libs/hwui/RenderNode.cpp b/libs/hwui/RenderNode.cpp
index 80f349a..0951fc1 100644
--- a/libs/hwui/RenderNode.cpp
+++ b/libs/hwui/RenderNode.cpp
@@ -214,10 +214,10 @@
         info.renderer->pushLayerUpdate(mLayer);
     }
 
-    if (CC_UNLIKELY(info.canvasContext)) {
-        // If canvasContext is not null that means there are prefetched layers
-        // that need to be accounted for. That might be us, so tell CanvasContext
-        // that this layer is in the tree and should not be destroyed.
+    if (info.canvasContext) {
+        // There might be prefetched layers that need to be accounted for.
+        // That might be us, so tell CanvasContext that this layer is in the
+        // tree and should not be destroyed.
         info.canvasContext->markLayerInUse(this);
     }
 }
@@ -339,7 +339,8 @@
         TextureCache& cache = Caches::getInstance().textureCache;
         info.out.hasFunctors |= subtree->functors.size();
         for (size_t i = 0; info.prepareTextures && i < subtree->bitmapResources.size(); i++) {
-            info.prepareTextures = cache.prefetchAndMarkInUse(subtree->bitmapResources[i]);
+            info.prepareTextures = cache.prefetchAndMarkInUse(
+                    info.canvasContext, subtree->bitmapResources[i]);
         }
         for (size_t i = 0; i < subtree->children().size(); i++) {
             DrawRenderNodeOp* op = subtree->children()[i];
diff --git a/libs/hwui/SkiaShader.cpp b/libs/hwui/SkiaShader.cpp
index a2aa2d1..81d8516 100644
--- a/libs/hwui/SkiaShader.cpp
+++ b/libs/hwui/SkiaShader.cpp
@@ -203,7 +203,13 @@
         return false;
     }
 
-    outData->bitmapTexture = caches.textureCache.get(&bitmap);
+    /*
+     * Bypass the AssetAtlas, since those textures:
+     * 1) require UV mapping, which isn't implemented in matrix computation below
+     * 2) can't handle REPEAT simply
+     * 3) are safe to upload here (outside of sync stage), since they're static
+     */
+    outData->bitmapTexture = caches.textureCache.getAndBypassAtlas(&bitmap);
     if (!outData->bitmapTexture) return false;
 
     outData->bitmapSampler = (*textureUnit)++;
diff --git a/libs/hwui/Texture.h b/libs/hwui/Texture.h
index 7227ce0..4bcd96d 100644
--- a/libs/hwui/Texture.h
+++ b/libs/hwui/Texture.h
@@ -97,7 +97,7 @@
      * Whether or not the Texture is marked in use and thus not evictable for
      * the current frame. This is reset at the start of a new frame.
      */
-    bool isInUse = false;
+    void* isInUse = nullptr;
 
 private:
     /**
diff --git a/libs/hwui/TextureCache.cpp b/libs/hwui/TextureCache.cpp
index fe1b7fd..fda0091 100644
--- a/libs/hwui/TextureCache.cpp
+++ b/libs/hwui/TextureCache.cpp
@@ -122,10 +122,12 @@
     mAssetAtlas = assetAtlas;
 }
 
-void TextureCache::resetMarkInUse() {
+void TextureCache::resetMarkInUse(void* ownerToken) {
     LruCache<uint32_t, Texture*>::Iterator iter(mCache);
     while (iter.next()) {
-        iter.value()->isInUse = false;
+        if (iter.value()->isInUse == ownerToken) {
+            iter.value()->isInUse = nullptr;
+        }
     }
 }
 
@@ -140,8 +142,8 @@
 
 // Returns a prepared Texture* that either is already in the cache or can fit
 // in the cache (and is thus added to the cache)
-Texture* TextureCache::getCachedTexture(const SkBitmap* bitmap) {
-    if (CC_LIKELY(mAssetAtlas)) {
+Texture* TextureCache::getCachedTexture(const SkBitmap* bitmap, AtlasUsageType atlasUsageType) {
+    if (CC_LIKELY(mAssetAtlas != nullptr) && atlasUsageType == AtlasUsageType::Use) {
         AssetAtlas::Entry* entry = mAssetAtlas->getEntry(bitmap);
         if (CC_UNLIKELY(entry)) {
             return entry->texture;
@@ -189,16 +191,16 @@
     return texture;
 }
 
-bool TextureCache::prefetchAndMarkInUse(const SkBitmap* bitmap) {
-    Texture* texture = getCachedTexture(bitmap);
+bool TextureCache::prefetchAndMarkInUse(void* ownerToken, const SkBitmap* bitmap) {
+    Texture* texture = getCachedTexture(bitmap, AtlasUsageType::Use);
     if (texture) {
-        texture->isInUse = true;
+        texture->isInUse = ownerToken;
     }
     return texture;
 }
 
-Texture* TextureCache::get(const SkBitmap* bitmap) {
-    Texture* texture = getCachedTexture(bitmap);
+Texture* TextureCache::get(const SkBitmap* bitmap, AtlasUsageType atlasUsageType) {
+    Texture* texture = getCachedTexture(bitmap, atlasUsageType);
 
     if (!texture) {
         if (!canMakeTextureFromBitmap(bitmap)) {
diff --git a/libs/hwui/TextureCache.h b/libs/hwui/TextureCache.h
index e7fc990..7a7ee5a 100644
--- a/libs/hwui/TextureCache.h
+++ b/libs/hwui/TextureCache.h
@@ -66,20 +66,30 @@
     /**
      * Resets all Textures to not be marked as in use
      */
-    void resetMarkInUse();
+    void resetMarkInUse(void* ownerToken);
 
     /**
      * Attempts to precache the SkBitmap. Returns true if a Texture was successfully
      * acquired for the bitmap, false otherwise. If a Texture was acquired it is
      * marked as in use.
      */
-    bool prefetchAndMarkInUse(const SkBitmap* bitmap);
+    bool prefetchAndMarkInUse(void* ownerToken, const SkBitmap* bitmap);
 
     /**
-     * Returns the texture associated with the specified bitmap. If the texture
-     * cannot be found in the cache, a new texture is generated.
+     * Returns the texture associated with the specified bitmap from either within the cache, or
+     * the AssetAtlas. If the texture cannot be found in the cache, a new texture is generated.
      */
-    Texture* get(const SkBitmap* bitmap);
+    Texture* get(const SkBitmap* bitmap) {
+        return get(bitmap, AtlasUsageType::Use);
+    }
+
+    /**
+     * Returns the texture associated with the specified bitmap. If the texture cannot be found in
+     * the cache, a new texture is generated, even if it resides in the AssetAtlas.
+     */
+    Texture* getAndBypassAtlas(const SkBitmap* bitmap) {
+        return get(bitmap, AtlasUsageType::Bypass);
+    }
 
     /**
      * Removes the texture associated with the specified pixelRef. This is meant
@@ -123,10 +133,15 @@
     void setAssetAtlas(AssetAtlas* assetAtlas);
 
 private:
+    enum class AtlasUsageType {
+        Use,
+        Bypass,
+    };
 
     bool canMakeTextureFromBitmap(const SkBitmap* bitmap);
 
-    Texture* getCachedTexture(const SkBitmap* bitmap);
+    Texture* get(const SkBitmap* bitmap, AtlasUsageType atlasUsageType);
+    Texture* getCachedTexture(const SkBitmap* bitmap, AtlasUsageType atlasUsageType);
 
     /**
      * Generates the texture from a bitmap into the specified texture structure.
diff --git a/libs/hwui/TreeInfo.h b/libs/hwui/TreeInfo.h
index 0799c6c..ed853f7 100644
--- a/libs/hwui/TreeInfo.h
+++ b/libs/hwui/TreeInfo.h
@@ -95,7 +95,7 @@
     // layer updates or similar. May be NULL.
     OpenGLRenderer* renderer;
     ErrorHandler* errorHandler;
-    // TODO: Remove this? May be NULL
+    // May be NULL (TODO: can it really?)
     renderthread::CanvasContext* canvasContext;
 
     struct Out {
diff --git a/libs/hwui/renderthread/CanvasContext.cpp b/libs/hwui/renderthread/CanvasContext.cpp
index 260fb6f..e472e93 100644
--- a/libs/hwui/renderthread/CanvasContext.cpp
+++ b/libs/hwui/renderthread/CanvasContext.cpp
@@ -145,7 +145,11 @@
 void CanvasContext::makeCurrent() {
     // TODO: Figure out why this workaround is needed, see b/13913604
     // In the meantime this matches the behavior of GLRenderer, so it is not a regression
-    mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface);
+    EGLint error = 0;
+    mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface, &error);
+    if (error) {
+        setSurface(nullptr);
+    }
 }
 
 void CanvasContext::processLayerUpdate(DeferredLayerUpdater* layerUpdater) {
@@ -174,16 +178,13 @@
 
     info.damageAccumulator = &mDamageAccumulator;
     info.renderer = mCanvas;
-    if (mPrefetechedLayers.size() && info.mode == TreeInfo::MODE_FULL) {
-        info.canvasContext = this;
-    }
+    info.canvasContext = this;
+
     mAnimationContext->startFrame(info.mode);
     mRootRenderNode->prepareTree(info);
     mAnimationContext->runRemainingAnimations(info);
 
-    if (info.canvasContext) {
-        freePrefetechedLayers();
-    }
+    freePrefetechedLayers();
 
     if (CC_UNLIKELY(!mNativeWindow.get())) {
         mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
@@ -365,7 +366,11 @@
     if (mEglManager.hasEglContext()) {
         freePrefetechedLayers();
         mRootRenderNode->destroyHardwareResources();
-        Caches::getInstance().flush(Caches::kFlushMode_Layers);
+        Caches& caches = Caches::getInstance();
+        // Make sure to release all the textures we were owning as there won't
+        // be another draw
+        caches.textureCache.resetMarkInUse(this);
+        caches.flush(Caches::kFlushMode_Layers);
     }
 }
 
diff --git a/libs/hwui/renderthread/DrawFrameTask.cpp b/libs/hwui/renderthread/DrawFrameTask.cpp
index 6507ce8..a4ac13b 100644
--- a/libs/hwui/renderthread/DrawFrameTask.cpp
+++ b/libs/hwui/renderthread/DrawFrameTask.cpp
@@ -114,7 +114,7 @@
     int64_t vsync = mFrameInfo[static_cast<int>(FrameInfoIndex::Vsync)];
     mRenderThread->timeLord().vsyncReceived(vsync);
     mContext->makeCurrent();
-    Caches::getInstance().textureCache.resetMarkInUse();
+    Caches::getInstance().textureCache.resetMarkInUse(mContext);
 
     for (size_t i = 0; i < mLayers.size(); i++) {
         mContext->processLayerUpdate(mLayers[i].get());
diff --git a/libs/hwui/renderthread/EglManager.cpp b/libs/hwui/renderthread/EglManager.cpp
index cb34e00..eb332d5 100644
--- a/libs/hwui/renderthread/EglManager.cpp
+++ b/libs/hwui/renderthread/EglManager.cpp
@@ -217,7 +217,7 @@
     mCurrentSurface = EGL_NO_SURFACE;
 }
 
-bool EglManager::makeCurrent(EGLSurface surface) {
+bool EglManager::makeCurrent(EGLSurface surface, EGLint* errOut) {
     if (isCurrent(surface)) return false;
 
     if (surface == EGL_NO_SURFACE) {
@@ -225,8 +225,14 @@
         surface = mPBufferSurface;
     }
     if (!eglMakeCurrent(mEglDisplay, surface, surface, mEglContext)) {
-        LOG_ALWAYS_FATAL("Failed to make current on surface %p, error=%s",
-                (void*)surface, egl_error_str());
+        if (errOut) {
+            *errOut = eglGetError();
+            ALOGW("Failed to make current on surface %p, error=%s",
+                    (void*)surface, egl_error_str(*errOut));
+        } else {
+            LOG_ALWAYS_FATAL("Failed to make current on surface %p, error=%s",
+                    (void*)surface, egl_error_str());
+        }
     }
     mCurrentSurface = surface;
     return true;
diff --git a/libs/hwui/renderthread/EglManager.h b/libs/hwui/renderthread/EglManager.h
index 8881de6..0a8cfd3 100644
--- a/libs/hwui/renderthread/EglManager.h
+++ b/libs/hwui/renderthread/EglManager.h
@@ -44,7 +44,7 @@
 
     bool isCurrent(EGLSurface surface) { return mCurrentSurface == surface; }
     // Returns true if the current surface changed, false if it was already current
-    bool makeCurrent(EGLSurface surface);
+    bool makeCurrent(EGLSurface surface, EGLint* errOut = nullptr);
     void beginFrame(EGLSurface surface, EGLint* width, EGLint* height);
     bool swapBuffers(EGLSurface surface, const SkRect& dirty, EGLint width, EGLint height);
 
diff --git a/libs/hwui/unit_tests/ClipAreaTests.cpp b/libs/hwui/unit_tests/ClipAreaTests.cpp
index 166d5b6..0c5e5e7 100644
--- a/libs/hwui/unit_tests/ClipAreaTests.cpp
+++ b/libs/hwui/unit_tests/ClipAreaTests.cpp
@@ -112,5 +112,16 @@
     regionBounds.set(skRect);
     EXPECT_EQ(expected, regionBounds);
 }
+
+TEST(ClipArea, replaceNegative) {
+    ClipArea area(createClipArea());
+    area.setClip(0, 0, 100, 100);
+
+    Matrix4 transform;
+    transform.loadIdentity();
+    Rect expected(-50, -50, 50, 50);
+    area.clipRectWithTransform(expected, &transform, SkRegion::kReplace_Op);
+    EXPECT_EQ(expected, area.getClipRect());
+}
 }
 }
diff --git a/media/java/android/media/IRingtonePlayer.aidl b/media/java/android/media/IRingtonePlayer.aidl
index aa5fde3..8091421 100644
--- a/media/java/android/media/IRingtonePlayer.aidl
+++ b/media/java/android/media/IRingtonePlayer.aidl
@@ -33,4 +33,7 @@
     /** Used for Notification sound playback. */
     void playAsync(in Uri uri, in UserHandle user, boolean looping, in AudioAttributes aa);
     void stopAsync();
+
+    /** Return the title of the media. */
+    String getTitle(in Uri uri);
 }
diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java
index 6dd855d..a4d3485 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -1017,16 +1017,14 @@
                 setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength());
             }
             return;
-        } catch (SecurityException ex) {
-        } catch (IOException ex) {
+        } catch (SecurityException | IOException ex) {
+            Log.w(TAG, "Couldn't open file on client side; trying server side: " + ex);
         } finally {
             if (fd != null) {
                 fd.close();
             }
         }
 
-        Log.d(TAG, "Couldn't open file on client side, trying server side");
-
         setDataSource(uri.toString(), headers);
     }
 
diff --git a/media/java/android/media/MediaSync.java b/media/java/android/media/MediaSync.java
index b07931d..b37e02c 100644
--- a/media/java/android/media/MediaSync.java
+++ b/media/java/android/media/MediaSync.java
@@ -24,6 +24,7 @@
 import android.os.Handler;
 import android.os.Looper;
 import android.os.Message;
+import android.util.Log;
 import android.view.Surface;
 
 import java.lang.annotation.Retention;
@@ -82,7 +83,7 @@
  *         codec.releaseOutputBuffer(bufferId, 1000 * info.presentationTime);
  *     } else {
  *         ByteBuffer audioByteBuffer = codec.getOutputBuffer(bufferId);
- *         sync.queueByteBuffer(audioByteBuffer, bufferId, info.size, info.presentationTime);
+ *         sync.queueAudio(audioByteBuffer, bufferId, info.presentationTime);
  *     }
  *     // ...
  * }
@@ -427,6 +428,11 @@
     /**
      * Flushes all buffers from the sync object.
      * <p>
+     * All pending unprocessed audio and video buffers are discarded. If an audio track was
+     * configured, it is flushed and stopped. If a video output surface was configured, the
+     * last frame queued to it is left on the frame. Queue a blank video frame to clear the
+     * surface,
+     * <p>
      * No callbacks are received for the flushed buffers.
      *
      * @throws IllegalStateException if the internal player engine has not been
@@ -437,10 +443,19 @@
             mAudioBuffers.clear();
             mCallbackHandler.removeCallbacksAndMessages(null);
         }
-        // TODO implement this for surface buffers.
+        if (mAudioTrack != null) {
+            mAudioTrack.pause();
+            mAudioTrack.flush();
+            // Call stop() to signal to the AudioSink to completely fill the
+            // internal buffer before resuming playback.
+            mAudioTrack.stop();
+        }
+        native_flush();
     }
 
-   /**
+    private native final void native_flush();
+
+    /**
      * Get current playback position.
      * <p>
      * The MediaTimestamp represents how the media time correlates to the system time in
@@ -478,6 +493,7 @@
 
     /**
      * Queues the audio data asynchronously for playback (AudioTrack must be in streaming mode).
+     * If the audio track was flushed as a result of {@link #flush}, it will be restarted.
      * @param audioData the buffer that holds the data to play. This buffer will be returned
      *     to the client via registered callback.
      * @param bufferId an integer used to identify audioData. It will be returned to
@@ -519,6 +535,14 @@
 
                     AudioBuffer audioBuffer = mAudioBuffers.get(0);
                     int size = audioBuffer.mByteBuffer.remaining();
+                    // restart audio track after flush
+                    if (size > 0 && mAudioTrack.getPlayState() != AudioTrack.PLAYSTATE_PLAYING) {
+                        try {
+                            mAudioTrack.play();
+                        } catch (IllegalStateException e) {
+                            Log.w(TAG, "could not start audio track");
+                        }
+                    }
                     int sizeWritten = mAudioTrack.write(
                             audioBuffer.mByteBuffer,
                             size,
@@ -558,17 +582,19 @@
                 final MediaSync sync = this;
                 mCallbackHandler.post(new Runnable() {
                     public void run() {
+                        Callback callback;
                         synchronized(mCallbackLock) {
+                            callback = mCallback;
                             if (mCallbackHandler == null
                                     || mCallbackHandler.getLooper().getThread()
                                             != Thread.currentThread()) {
                                 // callback handler has been changed.
                                 return;
                             }
-                            if (mCallback != null) {
-                                mCallback.onAudioBufferConsumed(sync, audioBuffer.mByteBuffer,
-                                        audioBuffer.mBufferIndex);
-                            }
+                        }
+                        if (callback != null) {
+                            callback.onAudioBufferConsumed(sync, audioBuffer.mByteBuffer,
+                                    audioBuffer.mBufferIndex);
                         }
                     }
                 });
diff --git a/media/java/android/media/Ringtone.java b/media/java/android/media/Ringtone.java
index faeebe6..9e9d602 100644
--- a/media/java/android/media/Ringtone.java
+++ b/media/java/android/media/Ringtone.java
@@ -27,6 +27,7 @@
 import android.os.RemoteException;
 import android.provider.MediaStore;
 import android.provider.Settings;
+import android.provider.MediaStore.MediaColumns;
 import android.util.Log;
 
 import java.io.IOException;
@@ -50,6 +51,8 @@
         MediaStore.Audio.Media.DATA,
         MediaStore.Audio.Media.TITLE
     };
+    /** Selection that limits query results to just audio files */
+    private static final String MEDIA_SELECTION = MediaColumns.MIME_TYPE + " LIKE 'audio/%'";
 
     // keep references on active Ringtones until stopped or completion listener called.
     private static final ArrayList<Ringtone> sActiveRingtones = new ArrayList<Ringtone>();
@@ -193,11 +196,14 @@
      */
     public String getTitle(Context context) {
         if (mTitle != null) return mTitle;
-        return mTitle = getTitle(context, mUri, true);
+        return mTitle = getTitle(context, mUri, true /*followSettingsUri*/, mAllowRemote);
     }
 
-    private static String getTitle(Context context, Uri uri, boolean followSettingsUri) {
-        Cursor cursor = null;
+    /**
+     * @hide
+     */
+    public static String getTitle(
+            Context context, Uri uri, boolean followSettingsUri, boolean allowRemote) {
         ContentResolver res = context.getContentResolver();
         
         String title = null;
@@ -209,31 +215,45 @@
                 if (followSettingsUri) {
                     Uri actualUri = RingtoneManager.getActualDefaultRingtoneUri(context,
                             RingtoneManager.getDefaultType(uri));
-                    String actualTitle = getTitle(context, actualUri, false);
+                    String actualTitle = getTitle(
+                            context, actualUri, false /*followSettingsUri*/, allowRemote);
                     title = context
                             .getString(com.android.internal.R.string.ringtone_default_with_actual,
                                     actualTitle);
                 }
             } else {
+                Cursor cursor = null;
                 try {
                     if (MediaStore.AUTHORITY.equals(authority)) {
-                        cursor = res.query(uri, MEDIA_COLUMNS, null, null, null);
+                        final String mediaSelection = allowRemote ? null : MEDIA_SELECTION;
+                        cursor = res.query(uri, MEDIA_COLUMNS, mediaSelection, null, null);
+                        if (cursor != null && cursor.getCount() == 1) {
+                            cursor.moveToFirst();
+                            return cursor.getString(2);
+                        }
+                        // missing cursor is handled below
                     }
                 } catch (SecurityException e) {
-                    // missing cursor is handled below
-                }
-
-                try {
-                    if (cursor != null && cursor.getCount() == 1) {
-                        cursor.moveToFirst();
-                        return cursor.getString(2);
-                    } else {
-                        title = uri.getLastPathSegment();
+                    IRingtonePlayer mRemotePlayer = null;
+                    if (allowRemote) {
+                        AudioManager audioManager =
+                                (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
+                        mRemotePlayer = audioManager.getRingtonePlayer();
+                    }
+                    if (mRemotePlayer != null) {
+                        try {
+                            title = mRemotePlayer.getTitle(uri);
+                        } catch (RemoteException re) {
+                        }
                     }
                 } finally {
                     if (cursor != null) {
                         cursor.close();
                     }
+                    cursor = null;
+                }
+                if (title == null) {
+                    title = uri.getLastPathSegment();
                 }
             }
         }
diff --git a/media/java/android/media/tv/TvInputInfo.java b/media/java/android/media/tv/TvInputInfo.java
index ce72c2f..a3d748e 100644
--- a/media/java/android/media/tv/TvInputInfo.java
+++ b/media/java/android/media/tv/TvInputInfo.java
@@ -49,6 +49,7 @@
 import java.io.InputStream;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
 
@@ -611,7 +612,7 @@
         String format = DELIMITER_INFO_IN_ID + PREFIX_HDMI_DEVICE
                 + "%0" + LENGTH_HDMI_PHYSICAL_ADDRESS + "X"
                 + "%0" + LENGTH_HDMI_DEVICE_ID + "X";
-        return name.flattenToShortString() + String.format(format,
+        return name.flattenToShortString() + String.format(Locale.ENGLISH, format,
                 deviceInfo.getPhysicalAddress(), deviceInfo.getId());
     }
 
diff --git a/media/java/android/media/tv/TvInputService.java b/media/java/android/media/tv/TvInputService.java
index 35037bb..86e8560 100644
--- a/media/java/android/media/tv/TvInputService.java
+++ b/media/java/android/media/tv/TvInputService.java
@@ -385,13 +385,14 @@
             trackIdSet.clear();
 
             // TODO: Validate the track list.
+            final List<TvTrackInfo> tracksCopy = new ArrayList<>(tracks);
             executeOrPostRunnable(new Runnable() {
                 @Override
                 public void run() {
                     try {
                         if (DEBUG) Log.d(TAG, "notifyTracksChanged");
                         if (mSessionCallback != null) {
-                            mSessionCallback.onTracksChanged(tracks);
+                            mSessionCallback.onTracksChanged(tracksCopy);
                         }
                     } catch (RemoteException e) {
                         Log.w(TAG, "error in notifyTracksChanged", e);
diff --git a/media/jni/android_media_MediaSync.cpp b/media/jni/android_media_MediaSync.cpp
index 8e0ed64..893c414 100644
--- a/media/jni/android_media_MediaSync.cpp
+++ b/media/jni/android_media_MediaSync.cpp
@@ -102,6 +102,10 @@
     return mSync->getVideoFrameRate();
 }
 
+void JMediaSync::flush() {
+    mSync->flush();
+}
+
 status_t JMediaSync::updateQueuedAudioData(
         int sizeInBytes, int64_t presentationTimeUs) {
     return mSync->updateQueuedAudioData(sizeInBytes, presentationTimeUs);
@@ -464,6 +468,16 @@
     return scs.asJobject(env, gSyncParamsFields);
 }
 
+static void android_media_MediaSync_native_flush(JNIEnv *env, jobject thiz) {
+    sp<JMediaSync> sync = getMediaSync(env, thiz);
+    if (sync == NULL) {
+        throwExceptionAsNecessary(env, INVALID_OPERATION);
+        return;
+    }
+
+    sync->flush();
+}
+
 static void android_media_MediaSync_native_init(JNIEnv *env) {
     ScopedLocalRef<jclass> clazz(env, env->FindClass("android/media/MediaSync"));
     CHECK(clazz.get() != NULL);
@@ -524,6 +538,8 @@
       "()J",
       (void *)android_media_MediaSync_native_getPlayTimeForPendingAudioFrames },
 
+    { "native_flush", "()V", (void *)android_media_MediaSync_native_flush },
+
     { "native_init", "()V", (void *)android_media_MediaSync_native_init },
 
     { "native_setup", "()V", (void *)android_media_MediaSync_native_setup },
diff --git a/media/jni/android_media_MediaSync.h b/media/jni/android_media_MediaSync.h
index 22c77c7..6f80885 100644
--- a/media/jni/android_media_MediaSync.h
+++ b/media/jni/android_media_MediaSync.h
@@ -49,6 +49,8 @@
     status_t setVideoFrameRateHint(float rate);
     float getVideoFrameRate();
 
+    void flush();
+
     sp<const MediaClock> getMediaClock();
 
 protected:
diff --git a/packages/BackupRestoreConfirmation/res/values-fa/strings.xml b/packages/BackupRestoreConfirmation/res/values-fa/strings.xml
index 4c16374..96ef731 100644
--- a/packages/BackupRestoreConfirmation/res/values-fa/strings.xml
+++ b/packages/BackupRestoreConfirmation/res/values-fa/strings.xml
@@ -19,7 +19,7 @@
     <string name="backup_confirm_title" msgid="827563724209303345">"پشتیبان‌گیری کامل"</string>
     <string name="restore_confirm_title" msgid="5469365809567486602">"بازیابی کامل"</string>
     <string name="backup_confirm_text" msgid="1878021282758896593">"درخواست پشتیبان گیری کامل از تمام داده‌ها به یک رایانه دسک‌تاپ متصل داده شده است. آیا می‌خواهید این عمل انجام شود؟\n\nاگر شما درخواست تهیهٔ نسخهٔ پشتیبان را نداده‌اید، اجازه‌ ادامه عملیات را ندهید."</string>
-    <string name="allow_backup_button_label" msgid="4217228747769644068">"از داده‌های من نسخهٔ پشتیبان تهیه شود"</string>
+    <string name="allow_backup_button_label" msgid="4217228747769644068">"پشتیبان‌گیری از داده‌های من"</string>
     <string name="deny_backup_button_label" msgid="6009119115581097708">"نسخهٔ پشتیبان تهیه نشود"</string>
     <string name="restore_confirm_text" msgid="7499866728030461776">"بازیابی کامل تمام داده‌ها از یک رایانه دسک تاپ متصل درخواست شده است. آیا می‌خواهید این اجازه را بدهید؟\n\nاگر خود شما درخواست بازیابی نداده‌اید، اجازه ادامه این عملیات را ندهید. با این کار همه داده‌هایی که اکنون روی دستگاه است جایگزین می‌شود!"</string>
     <string name="allow_restore_button_label" msgid="3081286752277127827">"بازیابی داده‌های من"</string>
diff --git a/packages/BackupRestoreConfirmation/res/values-hr/strings.xml b/packages/BackupRestoreConfirmation/res/values-hr/strings.xml
index 66037f3..cda36cb 100644
--- a/packages/BackupRestoreConfirmation/res/values-hr/strings.xml
+++ b/packages/BackupRestoreConfirmation/res/values-hr/strings.xml
@@ -19,7 +19,7 @@
     <string name="backup_confirm_title" msgid="827563724209303345">"Puna sigurnosna kopija"</string>
     <string name="restore_confirm_title" msgid="5469365809567486602">"Potpuno vraćanje"</string>
     <string name="backup_confirm_text" msgid="1878021282758896593">"Zatražena je potpuna sigurnosna kopija svih podataka na povezano stolno računalo. Želite li to dozvoliti?\n\nAko niste vi zatražili sigurnosnu kopiju, ne dozvolite nastavak te radnje."</string>
-    <string name="allow_backup_button_label" msgid="4217228747769644068">"Izradi sigurnosnu kopiju mojih podataka"</string>
+    <string name="allow_backup_button_label" msgid="4217228747769644068">"Sigurnosno kopiranje"</string>
     <string name="deny_backup_button_label" msgid="6009119115581097708">"Ne radi sigurnosnu kopiju"</string>
     <string name="restore_confirm_text" msgid="7499866728030461776">"Zatraženo je potpuno vraćanje svih podataka s povezanog stolnog računala. Želite li to dozvoliti?\n\nAko niste sami zatražili vraćanje, ne dozvolite nastavak radnje. To će zamijeniti sve podatke koji se trenutačno nalaze na uređaju!"</string>
     <string name="allow_restore_button_label" msgid="3081286752277127827">"Vrati moje podatke"</string>
@@ -28,8 +28,8 @@
     <string name="device_encryption_restore_text" msgid="1570864916855208992">"U nastavku unesite svoju zaporku za enkripciju uređaja."</string>
     <string name="device_encryption_backup_text" msgid="5866590762672844664">"U nastavku unesite svoju zaporku enkripcije za uređaj. Ona će se upotrijebiti i za enkripciju te za arhivu sigurnosnih kopija."</string>
     <string name="backup_enc_password_text" msgid="4981585714795233099">"Unesite zaporku koju ćete upotrebljavati za kriptiranje podataka potpune sigurnosne kopije. Ako je ostavite praznom, bit će upotrijebljena vaša trenutačna zaporka za sigurnosno kopiranje:"</string>
-    <string name="backup_enc_password_optional" msgid="1350137345907579306">"Ako želite kriptirati podatke potpune sigurnosne kopije, u nastavku unesite zaporku:"</string>
-    <string name="backup_enc_password_required" msgid="7889652203371654149">"Budući da vam je uređaj kriptiran, morate kriptirati sigurnosne kopije. Unesite zaporku u nastavku:"</string>
+    <string name="backup_enc_password_optional" msgid="1350137345907579306">"Ako želite šifrirati podatke potpune sigurnosne kopije, u nastavku unesite zaporku:"</string>
+    <string name="backup_enc_password_required" msgid="7889652203371654149">"Budući da vam je uređaj kriptiran, morate šifrirati sigurnosne kopije. Unesite zaporku u nastavku:"</string>
     <string name="restore_enc_password_text" msgid="6140898525580710823">"Ako su podaci za vraćanje kriptirani, unesite zaporku u nastavku:"</string>
     <string name="toast_backup_started" msgid="550354281452756121">"Započinje stvaranje sigurnosne kopije..."</string>
     <string name="toast_backup_ended" msgid="3818080769548726424">"Sigurnosna kopija dovršena"</string>
diff --git a/packages/BackupRestoreConfirmation/res/values-iw/strings.xml b/packages/BackupRestoreConfirmation/res/values-iw/strings.xml
index 8c2ffaf..4c13c73 100644
--- a/packages/BackupRestoreConfirmation/res/values-iw/strings.xml
+++ b/packages/BackupRestoreConfirmation/res/values-iw/strings.xml
@@ -19,7 +19,7 @@
     <string name="backup_confirm_title" msgid="827563724209303345">"גיבוי מלא"</string>
     <string name="restore_confirm_title" msgid="5469365809567486602">"שחזור מלא"</string>
     <string name="backup_confirm_text" msgid="1878021282758896593">"הוגשה בקשה לגיבוי מלא של כל הנתונים במחשב שולחני מחובר. האם אתה רוצה לאפשר פעולה זו? \n\nאם לא ביקשת את הגיבוי בעצמך, אל תאפשר לפעולה להמשיך."</string>
-    <string name="allow_backup_button_label" msgid="4217228747769644068">"גבה את הנתונים שלי"</string>
+    <string name="allow_backup_button_label" msgid="4217228747769644068">"גיבוי הנתונים שלי"</string>
     <string name="deny_backup_button_label" msgid="6009119115581097708">"אל תגבה"</string>
     <string name="restore_confirm_text" msgid="7499866728030461776">"הוגשה בקשה לשחזור מלא של כל הנתונים ממחשב שולחני מחובר. האם אתה רוצה לאפשר פעולה זו? \n \n אם לא ביקשת את השחזור בעצמך, אל תאפשר לפעולה להמשיך. פעולה זו תחליף את כל הנתונים שנמצאים כעת במכשיר!"</string>
     <string name="allow_restore_button_label" msgid="3081286752277127827">"שחזר את הנתונים שלי"</string>
diff --git a/packages/BackupRestoreConfirmation/res/values-ml-rIN/strings.xml b/packages/BackupRestoreConfirmation/res/values-ml-rIN/strings.xml
index b2b4bcb..5f97afa 100644
--- a/packages/BackupRestoreConfirmation/res/values-ml-rIN/strings.xml
+++ b/packages/BackupRestoreConfirmation/res/values-ml-rIN/strings.xml
@@ -19,7 +19,7 @@
     <string name="backup_confirm_title" msgid="827563724209303345">"പൂർണ്ണ ബാക്കപ്പ്"</string>
     <string name="restore_confirm_title" msgid="5469365809567486602">"പൂർണ്ണമായി പുനഃസ്ഥാപിക്കൽ"</string>
     <string name="backup_confirm_text" msgid="1878021282758896593">"കണക്റ്റുചെയ്‌ത ഡെസ്‌ക്‌ടോപ്പ് കമ്പ്യൂട്ടറിലേക്കുള്ള എല്ലാ ഡാറ്റയുടെയും പൂർണ്ണ ബാക്കപ്പ് ആവശ്യപ്പെട്ടു. ഇത് സംഭവിക്കാൻ അനുവദിക്കണോ?\n\nനിങ്ങൾ സ്വയം ബാക്കപ്പുചെയ്യാൻ ആവശ്യപ്പെട്ടില്ലെങ്കിൽ, ഈ പ്രവർത്തനം തുടരാൻ അനുവദിക്കരുത്."</string>
-    <string name="allow_backup_button_label" msgid="4217228747769644068">"എന്റെ ഡാറ്റ ബാക്കപ്പുചെയ്യുക"</string>
+    <string name="allow_backup_button_label" msgid="4217228747769644068">"ഡാറ്റ ബാക്കപ്പുചെയ്യൂ"</string>
     <string name="deny_backup_button_label" msgid="6009119115581097708">"ബാക്കപ്പ് ചെയ്യരുത്"</string>
     <string name="restore_confirm_text" msgid="7499866728030461776">"കണക്റ്റുചെയ്‌ത ഡെസ്‌ക്‌ടോപ്പ് കമ്പ്യൂട്ടറിലേക്കുള്ള എല്ലാ ഡാറ്റയുടെയും പൂർണ്ണ ബാക്കപ്പ് ആവശ്യപ്പെട്ടു. ഇത് സംഭവിക്കാൻ അനുവദിക്കണോ?\n\nനിങ്ങൾ സ്വയം ബാക്കപ്പുചെയ്യാൻ ആവശ്യപ്പെട്ടില്ലെങ്കിൽ, ഈ പ്രവർത്തനം തുടരാൻ അനുവദിക്കരുത്. ഇത് ഉപകരണത്തിൽ നിലവിലുള്ള എല്ലാ ഡാറ്റയേയും മാറ്റി പകരം വയ്ക്കും!"</string>
     <string name="allow_restore_button_label" msgid="3081286752277127827">"എന്റെ ഡാറ്റ പുനഃസ്ഥാപിക്കുക"</string>
diff --git a/packages/BackupRestoreConfirmation/res/values-sk/strings.xml b/packages/BackupRestoreConfirmation/res/values-sk/strings.xml
index a231d23..804f980 100644
--- a/packages/BackupRestoreConfirmation/res/values-sk/strings.xml
+++ b/packages/BackupRestoreConfirmation/res/values-sk/strings.xml
@@ -19,7 +19,7 @@
     <string name="backup_confirm_title" msgid="827563724209303345">"Úplná záloha"</string>
     <string name="restore_confirm_title" msgid="5469365809567486602">"Úplné obnovenie"</string>
     <string name="backup_confirm_text" msgid="1878021282758896593">"Bola vyžiadaná úplná záloha všetkých dát do pripojeného počítača. Chcete túto akciu povoliť?\n\nAk ste zálohu nevyžiadali vy, túto operáciu nepovoľujte."</string>
-    <string name="allow_backup_button_label" msgid="4217228747769644068">"Zálohovať údaje"</string>
+    <string name="allow_backup_button_label" msgid="4217228747769644068">"Zálohovať dáta"</string>
     <string name="deny_backup_button_label" msgid="6009119115581097708">"Nezálohovať"</string>
     <string name="restore_confirm_text" msgid="7499866728030461776">"Z pripojeného počítača bolo vyžiadané úplné obnovenie všetkých údajov. Chcete túto akciu povoliť?\n\nAk ste toto obnovenie nevyžiadali vy, túto operáciu nepovoľujte. Táto akcia nahradí všetky údaje v zariadení."</string>
     <string name="allow_restore_button_label" msgid="3081286752277127827">"Obnoviť údaje"</string>
diff --git a/packages/BackupRestoreConfirmation/res/values-sv/strings.xml b/packages/BackupRestoreConfirmation/res/values-sv/strings.xml
index 3ae37cf..dee8bc2 100644
--- a/packages/BackupRestoreConfirmation/res/values-sv/strings.xml
+++ b/packages/BackupRestoreConfirmation/res/values-sv/strings.xml
@@ -19,7 +19,7 @@
     <string name="backup_confirm_title" msgid="827563724209303345">"Fullständig säkerhetskopiering"</string>
     <string name="restore_confirm_title" msgid="5469365809567486602">"Fullständig återställning"</string>
     <string name="backup_confirm_text" msgid="1878021282758896593">"En fullständig säkerhetskopia av alla data till en ansluten dator har begärts. Vill du tillåta detta?\n\nOm du inte själv begärde säkerhetskopian ska du inte tillåta detta."</string>
-    <string name="allow_backup_button_label" msgid="4217228747769644068">"Säkerhetskopiera mina data"</string>
+    <string name="allow_backup_button_label" msgid="4217228747769644068">"Säkerhetskopiera data"</string>
     <string name="deny_backup_button_label" msgid="6009119115581097708">"Säkerhetskopiera inte"</string>
     <string name="restore_confirm_text" msgid="7499866728030461776">"En fullständig återställning av alla data från en ansluten dator har begärts. Vill du tillåta detta? \n \n Om du inte själv har begärt återställningen ska du inte tillåta den. Alla data som finns på enheten kommer då att ersättas!"</string>
     <string name="allow_restore_button_label" msgid="3081286752277127827">"Återställ mina data"</string>
diff --git a/packages/DefaultContainerService/res/values-fr/strings.xml b/packages/DefaultContainerService/res/values-fr/strings.xml
index 5c458bc..216d715 100644
--- a/packages/DefaultContainerService/res/values-fr/strings.xml
+++ b/packages/DefaultContainerService/res/values-fr/strings.xml
@@ -20,5 +20,5 @@
 
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="service_name" msgid="4841491635055379553">"Aide accès au package"</string>
+    <string name="service_name" msgid="4841491635055379553">"Package Access Helper"</string>
 </resources>
diff --git a/packages/DefaultContainerService/res/values-pt-rPT/strings.xml b/packages/DefaultContainerService/res/values-pt-rPT/strings.xml
index 5c03669..8ea6a3a 100644
--- a/packages/DefaultContainerService/res/values-pt-rPT/strings.xml
+++ b/packages/DefaultContainerService/res/values-pt-rPT/strings.xml
@@ -20,5 +20,5 @@
 
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="service_name" msgid="4841491635055379553">"Ajuda p/ aceder pacotes"</string>
+    <string name="service_name" msgid="4841491635055379553">"Ajuda p/ aceder a pacotes"</string>
 </resources>
diff --git a/packages/DocumentsUI/res/values-gu-rIN/strings.xml b/packages/DocumentsUI/res/values-gu-rIN/strings.xml
index a76c490..0281ba9 100644
--- a/packages/DocumentsUI/res/values-gu-rIN/strings.xml
+++ b/packages/DocumentsUI/res/values-gu-rIN/strings.xml
@@ -31,18 +31,18 @@
     <string name="menu_delete" msgid="8138799623850614177">"કાઢી નાખો"</string>
     <string name="menu_select_all" msgid="8323579667348729928">"બધા પસંદ કરો"</string>
     <string name="menu_copy" msgid="3612326052677229148">"આના પર કૉપિ કરો…"</string>
-    <string name="menu_advanced_show" product="nosdcard" msgid="4693652895715631401">"આંતરિક સ્ટોરેજ દર્શાવો"</string>
-    <string name="menu_advanced_show" product="default" msgid="5792182900084144261">"SD કાર્ડ દર્શાવો"</string>
+    <string name="menu_advanced_show" product="nosdcard" msgid="4693652895715631401">"આંતરિક સ્ટોરેજ બતાવો"</string>
+    <string name="menu_advanced_show" product="default" msgid="5792182900084144261">"SD કાર્ડ બતાવો"</string>
     <string name="menu_advanced_hide" product="nosdcard" msgid="4218809952721972589">"આંતરિક સંગ્રહ છુપાવો"</string>
     <string name="menu_advanced_hide" product="default" msgid="4845869969015718848">"SD કાર્ડ છુપાવો"</string>
-    <string name="menu_file_size_show" msgid="3240323619260823076">"ફાઇલ કદ દર્શાવો"</string>
+    <string name="menu_file_size_show" msgid="3240323619260823076">"ફાઇલ કદ બતાવો"</string>
     <string name="menu_file_size_hide" msgid="8881975928502581042">"ફાઇલ કદ છુપાવો"</string>
     <string name="button_select" msgid="527196987259139214">"પસંદ કરો"</string>
     <string name="button_copy" msgid="8706475544635021302">"કૉપિ કરો"</string>
     <string name="sort_name" msgid="9183560467917256779">"નામ દ્વારા"</string>
     <string name="sort_date" msgid="586080032956151448">"સંશોધન તારીખ દ્વારા"</string>
     <string name="sort_size" msgid="3350681319735474741">"કદ દ્વારા"</string>
-    <string name="drawer_open" msgid="4545466532430226949">"રૂટ્સ દર્શાવો"</string>
+    <string name="drawer_open" msgid="4545466532430226949">"રૂટ્સ બતાવો"</string>
     <string name="drawer_close" msgid="7602734368552123318">"રૂટ્સ છુપાવો"</string>
     <string name="save_error" msgid="6167009778003223664">"દસ્તાવેજ સાચવવામાં નિષ્ફળ થયાં."</string>
     <string name="create_error" msgid="3735649141335444215">"ફોલ્ડર બનાવવામાં નિષ્ફળ થયા"</string>
@@ -52,7 +52,7 @@
     <string name="root_type_service" msgid="2178854894416775409">"સંગ્રહ સેવાઓ"</string>
     <string name="root_type_shortcut" msgid="3318760609471618093">"શોર્ટકટ્સ"</string>
     <string name="root_type_device" msgid="7121342474653483538">"ઉપકરણો"</string>
-    <string name="root_type_apps" msgid="8838065367985945189">"વધુ એપ્લિકેશન્સ"</string>
+    <string name="root_type_apps" msgid="8838065367985945189">"વધુ એપ્લિકેશનો"</string>
     <string name="empty" msgid="7858882803708117596">"કોઈ આઇટમ્સ નથી"</string>
     <string name="toast_no_application" msgid="1339885974067891667">"ફાઇલ ખોલી શકાતી નથી"</string>
     <string name="toast_failed_delete" msgid="2180678019407244069">"કેટલાક દસ્તાવેજો કાઢી નાખવામાં અસમર્થ"</string>
diff --git a/packages/DocumentsUI/res/values-ml-rIN/strings.xml b/packages/DocumentsUI/res/values-ml-rIN/strings.xml
index 56b22b1..4c4b481 100644
--- a/packages/DocumentsUI/res/values-ml-rIN/strings.xml
+++ b/packages/DocumentsUI/res/values-ml-rIN/strings.xml
@@ -31,9 +31,9 @@
     <string name="menu_delete" msgid="8138799623850614177">"ഇല്ലാതാക്കുക"</string>
     <string name="menu_select_all" msgid="8323579667348729928">"എല്ലാം തിരഞ്ഞെടുക്കുക"</string>
     <string name="menu_copy" msgid="3612326052677229148">"ഇതിൽ പകർത്തുക…"</string>
-    <string name="menu_advanced_show" product="nosdcard" msgid="4693652895715631401">"ആന്തരിക സംഭരണം കാണിക്കുക"</string>
+    <string name="menu_advanced_show" product="nosdcard" msgid="4693652895715631401">"ആന്തരിക സ്റ്റോറേജ്  കാണിക്കുക"</string>
     <string name="menu_advanced_show" product="default" msgid="5792182900084144261">"SD കാർഡ് കാണിക്കുക"</string>
-    <string name="menu_advanced_hide" product="nosdcard" msgid="4218809952721972589">"ആന്തരിക സംഭരണം മറയ്‌ക്കുക"</string>
+    <string name="menu_advanced_hide" product="nosdcard" msgid="4218809952721972589">"ആന്തരിക സ്റ്റോറേജ്  മറയ്‌ക്കുക"</string>
     <string name="menu_advanced_hide" product="default" msgid="4845869969015718848">"SD കാർഡ് മറയ്‌ക്കുക"</string>
     <string name="menu_file_size_show" msgid="3240323619260823076">"ഫയൽ വലുപ്പം കാണിക്കുക"</string>
     <string name="menu_file_size_hide" msgid="8881975928502581042">"ഫയൽ വലുപ്പം മറയ്‌ക്കുക"</string>
diff --git a/packages/ExternalStorageProvider/res/values-da/strings.xml b/packages/ExternalStorageProvider/res/values-da/strings.xml
index a9ecb69..dc565ae 100644
--- a/packages/ExternalStorageProvider/res/values-da/strings.xml
+++ b/packages/ExternalStorageProvider/res/values-da/strings.xml
@@ -16,7 +16,7 @@
 
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="app_label" msgid="7123375275748530234">"Ekstern lagring"</string>
-    <string name="root_internal_storage" msgid="827844243068584127">"Intern lagring"</string>
+    <string name="app_label" msgid="7123375275748530234">"Ekstern lagerplads"</string>
+    <string name="root_internal_storage" msgid="827844243068584127">"Intern lagerplads"</string>
     <string name="root_documents" msgid="4051252304075469250">"Dokumenter"</string>
 </resources>
diff --git a/packages/ExternalStorageProvider/res/values-ml-rIN/strings.xml b/packages/ExternalStorageProvider/res/values-ml-rIN/strings.xml
index 204b336..08e6dae 100644
--- a/packages/ExternalStorageProvider/res/values-ml-rIN/strings.xml
+++ b/packages/ExternalStorageProvider/res/values-ml-rIN/strings.xml
@@ -16,7 +16,7 @@
 
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
-    <string name="app_label" msgid="7123375275748530234">"ബാഹ്യ സംഭരണം"</string>
-    <string name="root_internal_storage" msgid="827844243068584127">"ആന്തരിക സംഭരണം"</string>
+    <string name="app_label" msgid="7123375275748530234">"ബാഹ്യ സ്റ്റോറേജ്"</string>
+    <string name="root_internal_storage" msgid="827844243068584127">"ആന്തരിക സ്റ്റോറേജ്"</string>
     <string name="root_documents" msgid="4051252304075469250">"പ്രമാണങ്ങൾ"</string>
 </resources>
diff --git a/packages/ExternalStorageProvider/res/values-ru/strings.xml b/packages/ExternalStorageProvider/res/values-ru/strings.xml
index b6c10951..740272f 100644
--- a/packages/ExternalStorageProvider/res/values-ru/strings.xml
+++ b/packages/ExternalStorageProvider/res/values-ru/strings.xml
@@ -17,6 +17,6 @@
 <resources xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
     <string name="app_label" msgid="7123375275748530234">"Внешний накопитель"</string>
-    <string name="root_internal_storage" msgid="827844243068584127">"Внутренняя память"</string>
+    <string name="root_internal_storage" msgid="827844243068584127">"Внутренний накопитель"</string>
     <string name="root_documents" msgid="4051252304075469250">"Документы"</string>
 </resources>
diff --git a/packages/InputDevices/res/values-uk/strings.xml b/packages/InputDevices/res/values-uk/strings.xml
index d8152d4..43a3fe6 100644
--- a/packages/InputDevices/res/values-uk/strings.xml
+++ b/packages/InputDevices/res/values-uk/strings.xml
@@ -3,7 +3,7 @@
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
     <string name="app_label" msgid="8016145283189546017">"Пристрої вводу"</string>
     <string name="keyboard_layouts_label" msgid="6688773268302087545">"Клавіатура Android"</string>
-    <string name="keyboard_layout_english_uk_label" msgid="6664258463319999632">"англійська (Великобританія)"</string>
+    <string name="keyboard_layout_english_uk_label" msgid="6664258463319999632">"англійська (Велика Британія)"</string>
     <string name="keyboard_layout_english_us_label" msgid="8994890249649106291">"англійська (США)"</string>
     <string name="keyboard_layout_english_us_intl" msgid="3705168594034233583">"англійська (США), міжнародна"</string>
     <string name="keyboard_layout_english_us_colemak_label" msgid="4194969610343455380">"англійська (США), розкладка Colemak"</string>
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardConstants.java b/packages/Keyguard/src/com/android/keyguard/KeyguardConstants.java
index e5f3dc9..3927122 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardConstants.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardConstants.java
@@ -27,4 +27,5 @@
      */
     public static final boolean DEBUG = false;
     public static final boolean DEBUG_SIM_STATES = false;
+    public static final boolean DEBUG_FP_WAKELOCK = true;
 }
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityContainer.java b/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityContainer.java
index 23bd238..85da298 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityContainer.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardSecurityContainer.java
@@ -308,7 +308,8 @@
     boolean showNextSecurityScreenOrFinish(boolean authenticated) {
         if (DEBUG) Log.d(TAG, "showNextSecurityScreenOrFinish(" + authenticated + ")");
         boolean finish = false;
-        if (mUpdateMonitor.getUserHasTrust(KeyguardUpdateMonitor.getCurrentUser())) {
+        if (mUpdateMonitor.getUserCanSkipBouncer(
+                KeyguardUpdateMonitor.getCurrentUser())) {
             finish = true;
         } else if (SecurityMode.None == mCurrentSecuritySelection) {
             SecurityMode securityMode = mSecurityModel.getSecurityMode();
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitor.java
index 6574e4e..b098258 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitor.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitor.java
@@ -44,7 +44,9 @@
 import android.os.Handler;
 import android.os.IRemoteCallback;
 import android.os.Message;
+import android.os.PowerManager;
 import android.os.RemoteException;
+import android.os.SystemClock;
 import android.os.UserHandle;
 import android.provider.Settings;
 
@@ -90,12 +92,15 @@
     private static final String TAG = "KeyguardUpdateMonitor";
     private static final boolean DEBUG = KeyguardConstants.DEBUG;
     private static final boolean DEBUG_SIM_STATES = KeyguardConstants.DEBUG_SIM_STATES;
+    private static final boolean DEBUG_FP_WAKELOCK = KeyguardConstants.DEBUG_FP_WAKELOCK;
     private static final int LOW_BATTERY_THRESHOLD = 20;
+    private static final long FINGERPRINT_WAKELOCK_TIMEOUT_MS = 15 * 1000;
 
     private static final String ACTION_FACE_UNLOCK_STARTED
             = "com.android.facelock.FACE_UNLOCK_STARTED";
     private static final String ACTION_FACE_UNLOCK_STOPPED
             = "com.android.facelock.FACE_UNLOCK_STOPPED";
+    private static final String FINGERPRINT_WAKE_LOCK_NAME = "wake-and-unlock wakelock";
 
     // Callback messages
     private static final int MSG_TIME_UPDATE = 301;
@@ -114,10 +119,6 @@
     private static final int MSG_SCREEN_TURNED_ON = 319;
     private static final int MSG_SCREEN_TURNED_OFF = 320;
     private static final int MSG_KEYGUARD_BOUNCER_CHANGED = 322;
-    private static final int MSG_FINGERPRINT_AUTHENTICATED = 323;
-    private static final int MSG_FINGERPRINT_ERROR = 324;
-    private static final int MSG_FINGERPRINT_HELP = 325;
-    private static final int MSG_FINGERPRINT_AUTH_FAILED = 326;
     private static final int MSG_FACE_UNLOCK_STATE_CHANGED = 327;
     private static final int MSG_SIM_SUBSCRIPTION_INFO_CHANGED = 328;
     private static final int MSG_AIRPLANE_MODE_CHANGED = 329;
@@ -157,6 +158,7 @@
     private List<SubscriptionInfo> mSubscriptionInfo;
     private boolean mFingerprintDetectionRunning;
     private TrustManager mTrustManager;
+    private PowerManager mPowerManager;
 
     private final Handler mHandler = new Handler() {
         @Override
@@ -210,18 +212,6 @@
                 case MSG_SCREEN_TURNED_ON:
                     handleScreenTurnedOn();
                     break;
-                case MSG_FINGERPRINT_AUTHENTICATED:
-                    handleFingerprintAuthenticated();
-                    break;
-                case MSG_FINGERPRINT_HELP:
-                    handleFingerprintHelp(msg.arg1 /* msgId */, (String) msg.obj /* errString */);
-                    break;
-                case MSG_FINGERPRINT_ERROR:
-                    handleFingerprintError(msg.arg1 /* msgId */, (String) msg.obj /* errString */);
-                    break;
-                case MSG_FINGERPRINT_AUTH_FAILED:
-                    handleFingerprintAuthFailed();
-                    break;
                 case MSG_FACE_UNLOCK_STATE_CHANGED:
                     handleFaceUnlockStateChanged(msg.arg1 != 0, msg.arg2);
                     break;
@@ -253,6 +243,8 @@
 
     private static int sCurrentUser;
 
+    private boolean mWakeAndUnlocking;
+
     public synchronized static void setCurrentUser(int currentUser) {
         sCurrentUser = currentUser;
     }
@@ -353,23 +345,72 @@
         }
     }
 
-    private void onFingerprintAuthenticated(int userId) {
+    private void onFingerprintAuthenticated(int userId, boolean wakeAndUnlocking) {
         mUserFingerprintAuthenticated.put(userId, true);
         for (int i = 0; i < mCallbacks.size(); i++) {
             KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
             if (cb != null) {
-                cb.onFingerprintAuthenticated(userId);
+                cb.onFingerprintAuthenticated(userId, wakeAndUnlocking);
             }
         }
     }
 
     private void handleFingerprintAuthFailed() {
+        releaseFingerprintWakeLock();
         stopListeningForFingerprint();
         handleFingerprintHelp(-1, mContext.getString(R.string.fingerprint_not_recognized));
         updateFingerprintListeningState();
     }
 
+    private void handleFingerprintAcquired(int acquireInfo) {
+        if (acquireInfo != FingerprintManager.FINGERPRINT_ACQUIRED_GOOD) {
+            return;
+        }
+        if (!mScreenOn) {
+            releaseFingerprintWakeLock();
+            mWakeLock = mPowerManager.newWakeLock(
+                    PowerManager.PARTIAL_WAKE_LOCK, FINGERPRINT_WAKE_LOCK_NAME);
+            mWakeLock.acquire();
+            mWakeAndUnlocking = true;
+            if (DEBUG_FP_WAKELOCK) {
+                Log.i(TAG, "fingerprint acquired, grabbing fp wakelock");
+            }
+            mHandler.postDelayed(mReleaseFingerprintWakeLockRunnable,
+                    FINGERPRINT_WAKELOCK_TIMEOUT_MS);
+        } else {
+            mWakeAndUnlocking = false;
+        }
+    }
+
+    private final Runnable mReleaseFingerprintWakeLockRunnable = new Runnable() {
+        @Override
+        public void run() {
+            if (DEBUG_FP_WAKELOCK) {
+                Log.i(TAG, "fp wakelock: TIMEOUT!!");
+            }
+            releaseFingerprintWakeLock();
+        }
+    };
+
+    private void releaseFingerprintWakeLock() {
+        if (mWakeLock != null) {
+            mHandler.removeCallbacks(mReleaseFingerprintWakeLockRunnable);
+            if (DEBUG_FP_WAKELOCK) {
+                Log.i(TAG, "releasing fp wakelock");
+            }
+            mWakeLock.release();
+            mWakeLock = null;
+        }
+    }
+
     private void handleFingerprintAuthenticated() {
+        if (mWakeAndUnlocking) {
+            if (DEBUG_FP_WAKELOCK) {
+                Log.i(TAG, "fp wakelock: Authenticated, waking up...");
+            }
+            mPowerManager.wakeUp(SystemClock.uptimeMillis());
+        }
+        releaseFingerprintWakeLock();
         try {
             final int userId;
             try {
@@ -382,7 +423,7 @@
                 Log.d(TAG, "Fingerprint disabled by DPM for userId: " + userId);
                 return;
             }
-            onFingerprintAuthenticated(userId);
+            onFingerprintAuthenticated(userId, mWakeAndUnlocking);
         } finally {
             setFingerprintRunningDetectionRunning(false);
         }
@@ -455,9 +496,12 @@
                     & DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT) != 0;
     }
 
+    public boolean getUserCanSkipBouncer(int userId) {
+        return getUserHasTrust(userId) || mUserFingerprintAuthenticated.get(userId);
+    }
+
     public boolean getUserHasTrust(int userId) {
-        return !isTrustDisabled(userId) && mUserHasTrust.get(userId)
-                || mUserFingerprintAuthenticated.get(userId);
+        return !isTrustDisabled(userId) && mUserHasTrust.get(userId);
     }
 
     public boolean getUserTrustIsManaged(int userId) {
@@ -552,26 +596,32 @@
 
         @Override
         public void onAuthenticationFailed() {
-            mHandler.obtainMessage(MSG_FINGERPRINT_AUTH_FAILED).sendToTarget();
+            handleFingerprintAuthFailed();
         };
 
         @Override
         public void onAuthenticationSucceeded(AuthenticationResult result) {
-            mHandler.obtainMessage(MSG_FINGERPRINT_AUTHENTICATED).sendToTarget();
+            handleFingerprintAuthenticated();
         }
 
         @Override
         public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
-            mHandler.obtainMessage(MSG_FINGERPRINT_HELP, helpMsgId, 0, helpString).sendToTarget();
+            handleFingerprintHelp(helpMsgId, helpString.toString());
         }
 
         @Override
         public void onAuthenticationError(int errMsgId, CharSequence errString) {
-            mHandler.obtainMessage(MSG_FINGERPRINT_ERROR, errMsgId, 0, errString).sendToTarget();
+            handleFingerprintError(errMsgId, errString.toString());
+        }
+
+        @Override
+        public void onAuthenticationAcquired(int acquireInfo) {
+            handleFingerprintAcquired(acquireInfo);
         }
     };
     private CancellationSignal mFingerprintCancelSignal;
     private FingerprintManager mFpm;
+    private PowerManager.WakeLock mWakeLock;
 
     /**
      * When we receive a
@@ -738,6 +788,7 @@
     private KeyguardUpdateMonitor(Context context) {
         mContext = context;
         mSubscriptionManager = SubscriptionManager.from(context);
+        mPowerManager = context.getSystemService(PowerManager.class);
         mDeviceProvisioned = isDeviceProvisionedInSettingsDb();
         // Since device can't be un-provisioned, we only need to register a content observer
         // to update mDeviceProvisioned when we are...
@@ -816,7 +867,7 @@
     }
 
     private boolean shouldListenForFingerprint() {
-        return mScreenOn && mKeyguardIsVisible && !mSwitchingUser
+        return mKeyguardIsVisible && !mSwitchingUser
                 && mTrustManager.hasUserAuthenticatedSinceBoot(ActivityManager.getCurrentUser());
     }
 
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java b/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
index 26e6973..9fd8d30 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitorCallback.java
@@ -178,8 +178,10 @@
     /**
      * Called when a fingerprint is recognized.
      * @param userId the user id for which the fingerprint was authenticated
+     * @param wakeAndUnlocking whether the authentication woke the device up and thus we'd like to
+     *                         dismiss the lockscreen before turning on the screen
      */
-    public void onFingerprintAuthenticated(int userId) { }
+    public void onFingerprintAuthenticated(int userId, boolean wakeAndUnlocking) { }
 
     /**
      * Called when fingerprint provides help string (e.g. "Try again")
diff --git a/packages/PrintSpooler/res/values-fr/strings.xml b/packages/PrintSpooler/res/values-fr/strings.xml
index 5f3d5b6..1f5c716 100644
--- a/packages/PrintSpooler/res/values-fr/strings.xml
+++ b/packages/PrintSpooler/res/values-fr/strings.xml
@@ -34,7 +34,7 @@
     <string name="install_for_print_preview" msgid="6366303997385509332">"Installer un lecteur PDF pour afficher l\'aperçu"</string>
     <string name="printing_app_crashed" msgid="854477616686566398">"L\'application à l\'origine de l\'impression a planté"</string>
     <string name="generating_print_job" msgid="3119608742651698916">"Génération tâche impression…"</string>
-    <string name="save_as_pdf" msgid="5718454119847596853">"Enregistrer au format .PDF"</string>
+    <string name="save_as_pdf" msgid="5718454119847596853">"Enregistrer au format PDF"</string>
     <string name="all_printers" msgid="5018829726861876202">"Toutes les imprim."</string>
     <string name="print_dialog" msgid="32628687461331979">"Boîte de dialogue d\'impression"</string>
     <string name="current_page_template" msgid="1386638343571771292">"<xliff:g id="CURRENT_PAGE">%1$d</xliff:g>/<xliff:g id="PAGE_COUNT">%2$d</xliff:g>"</string>
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index 9832b45..c00fdf3 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -76,7 +76,9 @@
     <uses-permission android:name="android.permission.FORCE_STOP_PACKAGES" />
     <uses-permission android:name="android.permission.STOP_APP_SWITCHES" />
     <uses-permission android:name="android.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY" />
-    <uses-permission android:name="android.permission.GRANT_REVOKE_PERMISSIONS" />
+    <uses-permission android:name="android.permission.GRANT_RUNTIME_PERMISSIONS" />
+    <uses-permission android:name="android.permission.REVOKE_RUNTIME_PERMISSIONS" />
+    <uses-permission android:name="android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS" />
     <uses-permission android:name="android.permission.SET_KEYBOARD_LAYOUT" />
     <uses-permission android:name="android.permission.GET_DETAILED_TASKS" />
     <uses-permission android:name="android.permission.SET_SCREEN_COMPATIBILITY" />
diff --git a/packages/Shell/res/values-bg/strings.xml b/packages/Shell/res/values-bg/strings.xml
index 2d779b6..381d5d8 100644
--- a/packages/Shell/res/values-bg/strings.xml
+++ b/packages/Shell/res/values-bg/strings.xml
@@ -22,5 +22,5 @@
     <string name="bugreport_finished_text" product="default" msgid="3559904746859400732">"Докоснете, за да споделите отчета си за програмни грешки"</string>
     <string name="bugreport_confirm" msgid="5130698467795669780">"Отчетите за програмни грешки съдържат данни от различни регистрационни файлове на системата, включително лична и поверителна информация. Споделяйте ги само с приложения и хора, на които имате доверие."</string>
     <string name="bugreport_confirm_repeat" msgid="4926842460688645058">"Това съобщение да се показва следващия път"</string>
-    <string name="bugreport_storage_title" msgid="5332488144740527109">"Отчети за програмни грешки"</string>
+    <string name="bugreport_storage_title" msgid="5332488144740527109">"Отчети за прогр. грешки"</string>
 </resources>
diff --git a/packages/Shell/res/values-ca/strings.xml b/packages/Shell/res/values-ca/strings.xml
index 327fdc2..b07bafd 100644
--- a/packages/Shell/res/values-ca/strings.xml
+++ b/packages/Shell/res/values-ca/strings.xml
@@ -18,7 +18,7 @@
     xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
     <string name="app_label" msgid="3701846017049540910">"Protecció"</string>
     <string name="bugreport_finished_title" msgid="2293711546892863898">"S\'ha registrat l\'informe d\'error"</string>
-    <string name="bugreport_finished_text" product="watch" msgid="8389172248433597683">"Fes lliscar el dit cap a l\'esquerra per compartir l\'informe d\'errors."</string>
+    <string name="bugreport_finished_text" product="watch" msgid="8389172248433597683">"Llisca cap a l\'esquerra per compartir l\'informe d\'errors."</string>
     <string name="bugreport_finished_text" product="default" msgid="3559904746859400732">"Toca aquí per compartir el teu informe d\'error."</string>
     <string name="bugreport_confirm" msgid="5130698467795669780">"Els informes d\'error contenen dades dels diferents fitxers de registre del sistema, inclosa informació privada i personal. Comparteix els informes d\'error només amb les aplicacions i amb les persones en qui confies."</string>
     <string name="bugreport_confirm_repeat" msgid="4926842460688645058">"Mostra aquest missatge la propera vegada"</string>
diff --git a/packages/Shell/res/values-gu-rIN/strings.xml b/packages/Shell/res/values-gu-rIN/strings.xml
index 53e3852..e9fdfdb 100644
--- a/packages/Shell/res/values-gu-rIN/strings.xml
+++ b/packages/Shell/res/values-gu-rIN/strings.xml
@@ -20,7 +20,7 @@
     <string name="bugreport_finished_title" msgid="2293711546892863898">"બગ રિપોર્ટ કેપ્ચર કરી"</string>
     <string name="bugreport_finished_text" product="watch" msgid="8389172248433597683">"તમારી બગ રિપોર્ટ શેર કરવા માટે ડાબે સ્વાઇપ કરો"</string>
     <string name="bugreport_finished_text" product="default" msgid="3559904746859400732">"તમારી બગ રિપોર્ટ શેર કરવા માટે ટચ કરો"</string>
-    <string name="bugreport_confirm" msgid="5130698467795669780">"બગ રિપોર્ટ્સ વ્યક્તિગત અને ખાનગી માહિતી સહિત, સિસ્ટમની વિભિન્ન લૉગ ફાઇલોનો ડેટા ધરાવે છે. બગ રિપોર્ટ્સ ફક્ત તમે વિશ્વાસ કરતા હો તે એપ્લિકેશન્સ અને લોકો સાથે જ શેર કરો."</string>
-    <string name="bugreport_confirm_repeat" msgid="4926842460688645058">"આગલી વખતે આ સંદેશ દર્શાવો"</string>
+    <string name="bugreport_confirm" msgid="5130698467795669780">"બગ રિપોર્ટ્સ વ્યક્તિગત અને ખાનગી માહિતી સહિત, સિસ્ટમની વિભિન્ન લૉગ ફાઇલોનો ડેટા ધરાવે છે. બગ રિપોર્ટ્સ ફક્ત તમે વિશ્વાસ કરતા હો તે એપ્લિકેશનો અને લોકો સાથે જ શેર કરો."</string>
+    <string name="bugreport_confirm_repeat" msgid="4926842460688645058">"આગલી વખતે આ સંદેશ બતાવો"</string>
     <string name="bugreport_storage_title" msgid="5332488144740527109">"બગ રિપોર્ટ્સ"</string>
 </resources>
diff --git a/packages/Shell/res/values-hr/strings.xml b/packages/Shell/res/values-hr/strings.xml
index cf122ab..a2cb3b0 100644
--- a/packages/Shell/res/values-hr/strings.xml
+++ b/packages/Shell/res/values-hr/strings.xml
@@ -22,5 +22,5 @@
     <string name="bugreport_finished_text" product="default" msgid="3559904746859400732">"Dodirnite za dijeljenje prijave programske pogreške"</string>
     <string name="bugreport_confirm" msgid="5130698467795669780">"Prijave programskih pogrešaka sadržavaju podatke iz različitih datoteka zapisnika sustava, uključujući osobne i privatne informacije. Prijave programskih pogrešaka dijelite samo s aplikacijama i osobama koje smatrate pouzdanima."</string>
     <string name="bugreport_confirm_repeat" msgid="4926842460688645058">"Prikaži tu poruku sljedeći put"</string>
-    <string name="bugreport_storage_title" msgid="5332488144740527109">"Izvješća o programskim pogreškama"</string>
+    <string name="bugreport_storage_title" msgid="5332488144740527109">"Izvj. o prog. pogreš."</string>
 </resources>
diff --git a/packages/Shell/res/values-pl/strings.xml b/packages/Shell/res/values-pl/strings.xml
index 266f070..96b8f2a 100644
--- a/packages/Shell/res/values-pl/strings.xml
+++ b/packages/Shell/res/values-pl/strings.xml
@@ -22,5 +22,5 @@
     <string name="bugreport_finished_text" product="default" msgid="3559904746859400732">"Kliknij, by udostępnić raport o błędach"</string>
     <string name="bugreport_confirm" msgid="5130698467795669780">"Raporty o błędach zawierają dane z różnych plików dzienników systemu, w tym dane osobowe i prywatne. Udostępniaj je tylko aplikacjom i osobom, którym ufasz."</string>
     <string name="bugreport_confirm_repeat" msgid="4926842460688645058">"Pokaż ten komunikat następnym razem"</string>
-    <string name="bugreport_storage_title" msgid="5332488144740527109">"Zgłoszenia błędów"</string>
+    <string name="bugreport_storage_title" msgid="5332488144740527109">"Raporty o błędach"</string>
 </resources>
diff --git a/packages/Shell/res/values-sk/strings.xml b/packages/Shell/res/values-sk/strings.xml
index a79059d..4228dd3 100644
--- a/packages/Shell/res/values-sk/strings.xml
+++ b/packages/Shell/res/values-sk/strings.xml
@@ -22,5 +22,5 @@
     <string name="bugreport_finished_text" product="default" msgid="3559904746859400732">"Hlásenie o chybách môžete zdielať klepnutím"</string>
     <string name="bugreport_confirm" msgid="5130698467795669780">"Správy o chybách obsahujú údaje z rôznych súborov denníkov systému vrátane osobných a súkromných informácií. Zdieľajte ich iba s dôveryhodnými aplikáciami a ľuďmi."</string>
     <string name="bugreport_confirm_repeat" msgid="4926842460688645058">"Zobraziť túto správu nabudúce"</string>
-    <string name="bugreport_storage_title" msgid="5332488144740527109">"Hlásenia o chybe"</string>
+    <string name="bugreport_storage_title" msgid="5332488144740527109">"Hlásenia chýb"</string>
 </resources>
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index 6e5dc3f..fea7f94 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -405,5 +405,13 @@
             android:exported="true"
             android:singleUser="true"
             android:permission="android.permission.BIND_DREAM_SERVICE" />
+
+        <receiver
+            android:name=".tuner.TunerService$ClearReceiver"
+            android:exported="false">
+            <intent-filter>
+                <action android:name="com.android.systemui.action.CLEAR_TUNER" />
+            </intent-filter>
+        </receiver>
     </application>
 </manifest>
diff --git a/packages/SystemUI/res/drawable-nodpi/tuner.xml b/packages/SystemUI/res/drawable-nodpi/tuner.xml
index e27423f..0596aa4 100644
--- a/packages/SystemUI/res/drawable-nodpi/tuner.xml
+++ b/packages/SystemUI/res/drawable-nodpi/tuner.xml
@@ -1,7 +1,7 @@
 <!--
-   Copyright (C) 2015 The Android Open Source Project
+    Copyright (C) 2015 The Android Open Source Project
 
-   Licensed under the Apache License, Version 2.0 (the "License");
+    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
 
@@ -14,14 +14,11 @@
     limitations under the License.
 -->
 <vector xmlns:android="http://schemas.android.com/apk/res/android"
-        android:width="48.0dp"
-        android:height="48.0dp"
-        android:viewportWidth="48.0"
-        android:viewportHeight="48.0">
+        android:width="24.0dp"
+        android:height="24.0dp"
+        android:viewportWidth="24.0"
+        android:viewportHeight="24.0">
     <path
-        android:fillColor="#FF000000"
-        android:pathData="M29.9,24.8c0.0,-0.3 0.1,-0.5 0.1,-0.8s0.0,-0.5 -0.1,-0.8l1.7,-1.3c0.2,-0.1 0.2,-0.3 0.1,-0.5l-1.6,-2.8c-0.1,-0.2 -0.3,-0.2 -0.5,-0.2l-2.0,0.8c-0.4,-0.3 -0.9,-0.6 -1.4,-0.8L26.0,16.3c0.0,-0.2 -0.2,-0.3 -0.4,-0.3l-3.2,0.0c-0.2,0.0 -0.4,0.1 -0.4,0.3l-0.3,2.1c-0.5,0.2 -0.9,0.5 -1.4,0.8l-2.0,-0.8c-0.2,-0.1 -0.4,0.0 -0.5,0.2l-1.6,2.8c-0.1,0.2 -0.1,0.4 0.1,0.5l1.7,1.3c0.0,0.3 -0.1,0.5 -0.1,0.8s0.0,0.5 0.1,0.8l-1.7,1.3c-0.2,0.1 -0.2,0.3 -0.1,0.5l1.6,2.8c0.1,0.2 0.3,0.2 0.5,0.2l2.0,-0.8c0.4,0.3 0.9,0.6 1.4,0.8l0.3,2.1c0.0,0.2 0.2,0.3 0.4,0.3l3.2,0.0c0.2,0.0 0.4,-0.1 0.4,-0.3l0.3,-2.1c0.5,-0.2 0.9,-0.5 1.4,-0.8l2.0,0.8c0.2,0.1 0.4,0.0 0.5,-0.2l1.6,-2.8c0.1,-0.2 0.1,-0.4 -0.1,-0.5L29.9,24.8zM24.0,26.8c-1.5,0.0 -2.8,-1.3 -2.8,-2.8s1.3,-2.8 2.8,-2.8s2.8,1.3 2.8,2.8S25.5,26.8 24.0,26.8z"/>
-    <path
-        android:fillColor="#FF000000"
-        android:pathData="M18.0,38.0c-0.6,0.0 -1.0,-0.4 -1.0,-1.0s0.4,-1.0 1.0,-1.0s1.0,0.4 1.0,1.0S18.6,38.0 18.0,38.0zM24.0,38.0c-0.6,0.0 -1.0,-0.4 -1.0,-1.0s0.4,-1.0 1.0,-1.0s1.0,0.4 1.0,1.0S24.6,38.0 24.0,38.0zM30.0,38.0c-0.6,0.0 -1.0,-0.4 -1.0,-1.0s0.4,-1.0 1.0,-1.0s1.0,0.4 1.0,1.0S30.6,38.0 30.0,38.0zM42.0,6.0L6.0,6.0c-2.2,0.0 -4.0,1.8 -4.0,4.0l0.0,28.0c0.0,2.2 1.8,4.0 4.0,4.0l36.0,0.0c2.2,0.0 4.0,-1.8 4.0,-4.0L46.0,10.0C46.0,7.8 44.2,6.0 42.0,6.0zM42.0,34.0L6.0,34.0L6.0,14.0l36.0,0.0L42.0,34.0zM9.0,12.0L7.0,12.0l0.0,-2.0l2.0,0.0L9.0,12.0zM13.0,12.0l-2.0,0.0l0.0,-2.0l2.0,0.0L13.0,12.0zM17.0,12.0l-2.0,0.0l0.0,-2.0l2.0,0.0L17.0,12.0z"/>
+        android:fillColor="#FFFFFFFF"
+        android:pathData="M22.7,19.0l-9.1,-9.1c0.9,-2.0 0.4,-5.0 -1.5,-6.9 -2.0,-2.0 -5.0,-2.4 -7.4,-1.3L9.0,6.0 6.0,9.0 1.6,4.7C0.4,7.0 0.9,10.1 2.9,12.1c1.9,1.9 4.6,2.4 6.9,1.5l9.1,9.1c0.4,0.4 1.0,0.4 1.4,0.0l2.3,-2.3c0.5,-0.4 0.5,-1.0 0.1,-1.4z"/>
 </vector>
diff --git a/packages/SystemUI/res/layout/qs_detail_item.xml b/packages/SystemUI/res/layout/qs_detail_item.xml
index a519d3f..6facb71 100644
--- a/packages/SystemUI/res/layout/qs_detail_item.xml
+++ b/packages/SystemUI/res/layout/qs_detail_item.xml
@@ -20,6 +20,7 @@
     android:minHeight="@dimen/qs_detail_item_height"
     android:background="@drawable/btn_borderless_rect"
     android:clickable="true"
+    android:focusable="true"
     android:gravity="center_vertical"
     android:orientation="horizontal" >
 
@@ -57,6 +58,7 @@
         android:layout_width="48dp"
         android:layout_height="48dp"
         android:clickable="true"
+        android:focusable="true"
         android:scaleType="center"
         android:src="@drawable/ic_qs_cancel" />
 
diff --git a/packages/SystemUI/res/layout/status_bar.xml b/packages/SystemUI/res/layout/status_bar.xml
index 3118d08..a5b3a83 100644
--- a/packages/SystemUI/res/layout/status_bar.xml
+++ b/packages/SystemUI/res/layout/status_bar.xml
@@ -25,7 +25,7 @@
     android:id="@+id/status_bar"
     android:background="@drawable/system_bar_background"
     android:orientation="vertical"
-    android:focusable="true"
+    android:focusable="false"
     android:descendantFocusability="afterDescendants"
     >
 
diff --git a/packages/SystemUI/res/layout/status_bar_expanded_header.xml b/packages/SystemUI/res/layout/status_bar_expanded_header.xml
index 7262ed2..8c8a3dd 100644
--- a/packages/SystemUI/res/layout/status_bar_expanded_header.xml
+++ b/packages/SystemUI/res/layout/status_bar_expanded_header.xml
@@ -44,14 +44,31 @@
             android:scaleType="centerInside"/>
     </com.android.systemui.statusbar.phone.MultiUserSwitch>
 
-    <com.android.keyguard.AlphaOptimizedImageButton android:id="@+id/settings_button"
-        style="@android:style/Widget.Material.Button.Borderless"
-        android:layout_toStartOf="@id/multi_user_switch"
+    <com.android.keyguard.AlphaOptimizedLinearLayout
+        android:id="@+id/settings_button_container"
         android:layout_width="48dp"
         android:layout_height="@dimen/status_bar_header_height"
-        android:background="@drawable/ripple_drawable"
-        android:src="@drawable/ic_settings"
-        android:contentDescription="@string/accessibility_desc_settings" />
+        android:paddingStart="12dp"
+        android:clipChildren="false"
+        android:clipToPadding="false"
+        android:layout_toStartOf="@id/multi_user_switch">
+
+        <com.android.systemui.statusbar.phone.SettingsButton android:id="@+id/settings_button"
+            style="@android:style/Widget.Material.Button.Borderless"
+            android:layout_width="24dp"
+            android:layout_height="@dimen/status_bar_header_height"
+            android:background="@drawable/ripple_drawable"
+            android:src="@drawable/ic_settings"
+            android:contentDescription="@string/accessibility_desc_settings" />
+        <com.android.systemui.statusbar.AlphaOptimizedImageView android:id="@+id/tuner_icon"
+            android:layout_width="12dp"
+            android:layout_height="@dimen/status_bar_header_height"
+            android:tint="#4DFFFFFF"
+            android:tintMode="src_in"
+            android:visibility="invisible"
+            android:src="@drawable/tuner" />
+
+    </com.android.keyguard.AlphaOptimizedLinearLayout>
 
     <LinearLayout android:id="@+id/system_icons_super_container"
         android:layout_width="wrap_content"
diff --git a/packages/SystemUI/res/layout/status_bar_notification_dismiss_all.xml b/packages/SystemUI/res/layout/status_bar_notification_dismiss_all.xml
index 6a000fd..dc7577a 100644
--- a/packages/SystemUI/res/layout/status_bar_notification_dismiss_all.xml
+++ b/packages/SystemUI/res/layout/status_bar_notification_dismiss_all.xml
@@ -27,6 +27,7 @@
             android:layout_width="48dp"
             android:layout_height="48dp"
             android:layout_gravity="end"
+            android:focusable="true"
             android:background="@drawable/ripple_drawable"
             android:contentDescription="@string/accessibility_clear_all"/>
 </com.android.systemui.statusbar.DismissView>
diff --git a/packages/SystemUI/res/layout/status_bar_notification_keyguard_overflow.xml b/packages/SystemUI/res/layout/status_bar_notification_keyguard_overflow.xml
index 4526af5..f699fce 100644
--- a/packages/SystemUI/res/layout/status_bar_notification_keyguard_overflow.xml
+++ b/packages/SystemUI/res/layout/status_bar_notification_keyguard_overflow.xml
@@ -31,7 +31,7 @@
         android:layout_height="match_parent"
         />
 
-    <LinearLayout
+    <com.android.keyguard.AlphaOptimizedLinearLayout
         android:id="@+id/content"
         android:layout_width="match_parent"
         android:layout_height="match_parent">
@@ -63,6 +63,6 @@
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             />
-    </LinearLayout>
+    </com.android.keyguard.AlphaOptimizedLinearLayout>
 
 </com.android.systemui.statusbar.NotificationOverflowContainer>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 155f5ea..03ea73c 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -562,7 +562,7 @@
 
     <!-- Padding to be used on the bottom of the fingerprint icon on Keyguard so it better aligns
          with the other icons. -->
-    <dimen name="fingerprint_icon_additional_padding">12dp</dimen>
+    <dimen name="fingerprint_icon_additional_padding">4dp</dimen>
 
     <!-- Minimum margin of the notification panel on the side, when being positioned dynamically -->
     <dimen name="notification_panel_min_side_margin">48dp</dimen>
@@ -583,7 +583,7 @@
     <dimen name="managed_profile_toast_padding">4dp</dimen>
 
     <!-- Thickness of the assist disclosure beams -->
-    <dimen name="assist_disclosure_thickness">3dp</dimen>
+    <dimen name="assist_disclosure_thickness">2.5dp</dimen>
 
     <!-- Thickness of the shadows of the assist disclosure beams -->
     <dimen name="assist_disclosure_shadow_thickness">1.5dp</dimen>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index fcf7e3e..3eac84f 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -1032,7 +1032,7 @@
     <string name="volume_stream_vibrate_dnd" translatable="false">%s vibrate — Priority only</string>
 
     <!-- Name of special SystemUI debug settings -->
-    <string name="system_ui_tuner">System UI tuner</string>
+    <string name="system_ui_tuner">System UI Tuner</string>
 
     <!-- Preference to show/hide embedded battery percentage [CHAR LIMIT=50] -->
     <string name="show_battery_percentage">Show embedded battery percentage</string>
@@ -1099,4 +1099,25 @@
     <!-- Accessibility label for managed profile icon (not shown on screen) [CHAR LIMIT=NONE] -->
     <string name="accessibility_managed_profile">Work profile</string>
 
+    <!-- Title of warning when entering System UI tuner for first time [CHAR LIMIT=NONE] -->
+    <string name="tuner_warning_title">Fun for some but not for all</string>
+
+    <!-- Warning for users entering the System UI tuner for the first time [CHAR LIMIT=NONE]-->
+    <string name="tuner_warning">System UI Tuner gives you extra ways to tweak and customize the Android user interface. These experimental features may change, break, or disappear in future releases. Proceed with caution.</string>
+
+    <!-- Warning for users entering the System UI tuner [CHAR LIMIT=NONE]-->
+    <string name="tuner_persistent_warning">These experimental features may change, break, or disappear in future releases. Proceed with caution.</string>
+
+    <!-- Generic "got it" acceptance of dialog or cling [CHAR LIMIT=NONE] -->
+    <string name="got_it">Got it</string>
+
+    <!-- Toast describing tuner has been enabled [CHAR LIMIT=NONE] -->
+    <string name="tuner_toast">Congrats! System UI Tuner has been added to Settings</string>
+
+    <!-- Option to remove the tuner from settings [CHAR LIMIT=NONE] -->
+    <string name="remove_from_settings">Remove from Settings</string>
+
+    <!-- Dialog asking if the tuner should really be removed from settings [CHAR LIMIT=NONE]-->
+    <string name="remove_from_settings_prompt">Remove System UI Tuner from Settings and stop using all of its features?"</string>
+
 </resources>
diff --git a/packages/SystemUI/res/xml/tuner_prefs.xml b/packages/SystemUI/res/xml/tuner_prefs.xml
index 8c1acc3..3a41c3c 100644
--- a/packages/SystemUI/res/xml/tuner_prefs.xml
+++ b/packages/SystemUI/res/xml/tuner_prefs.xml
@@ -76,4 +76,8 @@
         android:key="demo_mode"
         android:title="@string/demo_mode" />
 
+    <Preference
+        android:summary="@string/tuner_persistent_warning"
+        android:selectable="false" />
+
 </PreferenceScreen>
diff --git a/packages/SystemUI/src/com/android/systemui/DejankUtils.java b/packages/SystemUI/src/com/android/systemui/DejankUtils.java
new file mode 100644
index 0000000..fc98ec4
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/DejankUtils.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.systemui;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.os.StrictMode;
+import android.view.Choreographer;
+
+import java.util.ArrayList;
+
+/**
+ * Utility class for methods used to dejank the UI.
+ */
+public class DejankUtils {
+
+    private static final Choreographer sChoreographer = Choreographer.getInstance();
+    private static final Handler sHandler = new Handler();
+
+    private static final ArrayList<Runnable> sPendingRunnables = new ArrayList<>();
+
+    private static final Runnable sAnimationCallbackRunnable = new Runnable() {
+        @Override
+        public void run() {
+            for (int i = 0; i < sPendingRunnables.size(); i++) {
+                sHandler.post(sPendingRunnables.get(i));
+            }
+            sPendingRunnables.clear();
+        }
+    };
+
+    /**
+     * Executes {@code r} after performTraversals. Use this do to CPU heavy work for which the
+     * timing is not critical for animation. The work is then scheduled at the same time
+     * RenderThread is doing its thing, leading to better parallelization.
+     *
+     * <p>Needs to be called from the main thread.
+     */
+    public static void postAfterTraversal(Runnable r) {
+        throwIfNotCalledOnMainThread();
+        sPendingRunnables.add(r);
+        postAnimationCallback();
+    }
+
+    /**
+     * Removes a previously scheduled runnable.
+     *
+     * <p>Needs to be called from the main thread.
+     */
+    public static void removeCallbacks(Runnable r) {
+        throwIfNotCalledOnMainThread();
+        sPendingRunnables.remove(r);
+        sHandler.removeCallbacks(r);
+    }
+
+    private static void postAnimationCallback() {
+        sChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION, sAnimationCallbackRunnable,
+                null);
+    }
+
+    private static void throwIfNotCalledOnMainThread() {
+        if (!Looper.getMainLooper().isCurrentThread()) {
+            throw new IllegalStateException("should be called from the main thread.");
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/DemoMode.java b/packages/SystemUI/src/com/android/systemui/DemoMode.java
index d406f5b..11996d0 100644
--- a/packages/SystemUI/src/com/android/systemui/DemoMode.java
+++ b/packages/SystemUI/src/com/android/systemui/DemoMode.java
@@ -20,6 +20,8 @@
 
 public interface DemoMode {
 
+    public static final String DEMO_MODE_ALLOWED = "sysui_demo_allowed";
+
     void dispatchDemoCommand(String command, Bundle args);
 
     public static final String ACTION_DEMO = "com.android.systemui.demo";
diff --git a/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java b/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
index 9f6d8df..8556afc 100644
--- a/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
+++ b/packages/SystemUI/src/com/android/systemui/ImageWallpaper.java
@@ -116,7 +116,6 @@
         private final DisplayInfo mTmpDisplayInfo = new DisplayInfo();
 
         boolean mVisible = true;
-        boolean mRedrawNeeded;
         boolean mOffsetsChanged;
         int mLastXTranslation;
         int mLastYTranslation;
@@ -153,6 +152,9 @@
         private int mDisplayWidthAtLastSurfaceSizeUpdate = -1;
         private int mDisplayHeightAtLastSurfaceSizeUpdate = -1;
 
+        private int mLastRequestedWidth = -1;
+        private int mLastRequestedHeight = -1;
+
         public DrawableEngine() {
             super();
             setFixedSizeAllowed(true);
@@ -211,21 +213,13 @@
             int surfaceWidth = Math.max(displayInfo.logicalWidth, mBackgroundWidth);
             int surfaceHeight = Math.max(displayInfo.logicalHeight, mBackgroundHeight);
 
-            // If the surface dimensions haven't changed, then just return
-            final Rect frame = surfaceHolder.getSurfaceFrame();
-            if (frame != null) {
-                final int dw = frame.width();
-                final int dh = frame.height();
-                if (surfaceWidth == dw && surfaceHeight == dh) {
-                    return;
-                }
-            }
-
             if (FIXED_SIZED_SURFACE) {
                 // Used a fixed size surface, because we are special.  We can do
                 // this because we know the current design of window animations doesn't
                 // cause this to break.
                 surfaceHolder.setFixedSize(surfaceWidth, surfaceHeight);
+                mLastRequestedWidth = surfaceWidth;
+                mLastRequestedHeight = surfaceHeight;
             } else {
                 surfaceHolder.setSizeFromLayout();
             }
@@ -387,7 +381,6 @@
                     yPixels += (int) (availhUnscaled * (mYOffset - .5f) + .5f);
 
                 mOffsetsChanged = false;
-                mRedrawNeeded = false;
                 if (surfaceDimensionsChanged) {
                     mLastSurfaceWidth = dw;
                     mLastSurfaceHeight = dh;
@@ -475,13 +468,15 @@
             out.print(" mYOffset="); out.println(mYOffset);
 
             out.print(prefix); out.print(" mVisible="); out.print(mVisible);
-            out.print(" mRedrawNeeded="); out.print(mRedrawNeeded);
             out.print(" mOffsetsChanged="); out.println(mOffsetsChanged);
 
             out.print(prefix); out.print(" mLastXTranslation="); out.print(mLastXTranslation);
             out.print(" mLastYTranslation="); out.print(mLastYTranslation);
             out.print(" mScale="); out.println(mScale);
 
+            out.print(prefix); out.print(" mLastRequestedWidth="); out.print(mLastRequestedWidth);
+            out.print(" mLastRequestedHeight="); out.println(mLastRequestedHeight);
+
             out.print(prefix); out.println(" DisplayInfo at last updateSurfaceSize:");
             out.print(prefix);
             out.print("  rotation="); out.print(mRotationAtLastSurfaceSizeUpdate);
diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java b/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
index 0daa5c9..9265b63 100644
--- a/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
+++ b/packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
@@ -18,6 +18,7 @@
 import android.os.RemoteException;
 import android.os.UserHandle;
 import android.provider.Settings;
+import android.service.voice.VoiceInteractionSession;
 import android.util.Log;
 import android.view.Gravity;
 import android.view.HapticFeedbackConstants;
@@ -218,7 +219,8 @@
     }
 
     private void startVoiceInteractor(Bundle args) {
-        mAssistUtils.showSessionForActiveService(args, mShowCallback);
+        mAssistUtils.showSessionForActiveService(args,
+                VoiceInteractionSession.SHOW_SOURCE_ASSIST_GESTURE, mShowCallback, null);
     }
 
     public void launchVoiceAssistFromKeyguard() {
@@ -302,4 +304,8 @@
     public void onUserSwitched(int newUserId) {
         updateAssistInfo();
     }
+
+    public void onLockscreenShown() {
+        mAssistUtils.onLockscreenShown();
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeService.java b/packages/SystemUI/src/com/android/systemui/doze/DozeService.java
index 5d46712..887391c 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeService.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeService.java
@@ -136,7 +136,7 @@
                 mDozeParameters.getPulseOnPickup(), mDozeParameters.getVibrateOnPickup(),
                 DozeLog.PULSE_REASON_SENSOR_PICKUP);
         mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
-        mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, mTag);
+        mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
         mWakeLock.setReferenceCounted(true);
         mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
         mDisplayStateSupported = mDozeParameters.getDisplayStateSupported();
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
index 98558b4..9f21dbe 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardService.java
@@ -25,9 +25,9 @@
 import android.os.Process;
 import android.util.Log;
 
+import com.android.internal.policy.IKeyguardDrawnCallback;
 import com.android.internal.policy.IKeyguardExitCallback;
 import com.android.internal.policy.IKeyguardService;
-import com.android.internal.policy.IKeyguardShowCallback;
 import com.android.internal.policy.IKeyguardStateCallback;
 import com.android.systemui.SystemUIApplication;
 
@@ -120,9 +120,15 @@
         }
 
         @Override // Binder interface
-        public void onStartedWakingUp(IKeyguardShowCallback callback) {
+        public void onStartedWakingUp() {
             checkPermission();
-            mKeyguardViewMediator.onStartedWakingUp(callback);
+            mKeyguardViewMediator.onStartedWakingUp();
+        }
+
+        @Override // Binder interface
+        public void onScreenTurningOn(IKeyguardDrawnCallback callback) {
+            checkPermission();
+            mKeyguardViewMediator.onScreenTurningOn(callback);
         }
 
         @Override // Binder interface
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index 009a0d6..c01a485 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -41,6 +41,7 @@
 import android.os.RemoteException;
 import android.os.SystemClock;
 import android.os.SystemProperties;
+import android.os.Trace;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.provider.Settings;
@@ -55,8 +56,9 @@
 import android.view.WindowManagerPolicy;
 import android.view.animation.Animation;
 import android.view.animation.AnimationUtils;
+
+import com.android.internal.policy.IKeyguardDrawnCallback;
 import com.android.internal.policy.IKeyguardExitCallback;
-import com.android.internal.policy.IKeyguardShowCallback;
 import com.android.internal.policy.IKeyguardStateCallback;
 import com.android.internal.telephony.IccCardConstants;
 import com.android.internal.widget.LockPatternUtils;
@@ -77,7 +79,6 @@
 
 import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
 
-
 /**
  * Mediates requests related to the keyguard.  This includes queries about the
  * state of the keyguard, power management events that effect whether the keyguard
@@ -138,7 +139,7 @@
     private static final int RESET = 4;
     private static final int VERIFY_UNLOCK = 5;
     private static final int NOTIFY_SCREEN_OFF = 6;
-    private static final int NOTIFY_SCREEN_ON = 7;
+    private static final int NOTIFY_SCREEN_TURNING_ON = 7;
     private static final int KEYGUARD_DONE = 9;
     private static final int KEYGUARD_DONE_DRAWING = 10;
     private static final int KEYGUARD_DONE_AUTHENTICATING = 11;
@@ -148,6 +149,7 @@
     private static final int START_KEYGUARD_EXIT_ANIM = 18;
     private static final int ON_ACTIVITY_DRAWN = 19;
     private static final int KEYGUARD_DONE_PENDING_TIMEOUT = 20;
+    private static final int NOTIFY_STARTED_WAKING_UP = 21;
 
     /**
      * The default amount of time we stay awake (used for all key input)
@@ -311,11 +313,14 @@
     private boolean mPendingReset;
 
     /**
-     * When starting goign to sleep, we figured out that we need to lock Keyguard and this should be
+     * When starting going to sleep, we figured out that we need to lock Keyguard and this should be
      * committed when finished going to sleep.
      */
     private boolean mPendingLock;
 
+    private boolean mWakeAndUnlocking;
+    private IKeyguardDrawnCallback mDrawnCallback;
+
     KeyguardUpdateMonitorCallback mUpdateCallback = new KeyguardUpdateMonitorCallback() {
 
         @Override
@@ -454,12 +459,17 @@
         }
 
         @Override
-        public void onFingerprintAuthenticated(int userId) {
+        public void onFingerprintAuthenticated(int userId, boolean wakeAndUnlocking) {
             if (mStatusBarKeyguardViewManager.isBouncerShowing()) {
                 mStatusBarKeyguardViewManager.notifyKeyguardAuthenticated();
             } else {
-                mStatusBarKeyguardViewManager.animateCollapsePanels(
-                        FINGERPRINT_COLLAPSE_SPEEDUP_FACTOR);
+                if (wakeAndUnlocking) {
+                    mWakeAndUnlocking = true;
+                    keyguardDone(true, true);
+                } else {
+                    mStatusBarKeyguardViewManager.animateCollapsePanels(
+                            FINGERPRINT_COLLAPSE_SPEEDUP_FACTOR);
+                }
             }
         };
 
@@ -752,21 +762,23 @@
     /**
      * Let's us know when the device is waking up.
      */
-    public void onStartedWakingUp(IKeyguardShowCallback callback) {
+    public void onStartedWakingUp() {
 
         // TODO: Rename all screen off/on references to interactive/sleeping
         synchronized (this) {
             mDeviceInteractive = true;
             cancelDoKeyguardLaterLocked();
             if (DEBUG) Log.d(TAG, "onStartedWakingUp, seq = " + mDelayedShowingSequence);
-            if (callback != null) {
-                notifyScreenOnLocked(callback);
-            }
+            notifyStartedWakingUp();
         }
         KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurnedOn();
         maybeSendUserPresentBroadcast();
     }
 
+    public void onScreenTurningOn(IKeyguardDrawnCallback callback) {
+        notifyScreenOnLocked(callback);
+    }
+
     private void maybeSendUserPresentBroadcast() {
         if (mSystemReady && mLockPatternUtils.isLockScreenDisabled(
                 KeyguardUpdateMonitor.getCurrentUser())) {
@@ -1093,14 +1105,14 @@
         mHandler.sendEmptyMessage(NOTIFY_SCREEN_OFF);
     }
 
-    /**
-     * Send a message to keyguard telling it the screen just turned on.
-     * @see #onScreenTurnedOn
-     * @see #handleNotifyScreenOn
-     */
-    private void notifyScreenOnLocked(IKeyguardShowCallback result) {
+    private void notifyStartedWakingUp() {
+        if (DEBUG) Log.d(TAG, "notifyStartedWakingUp");
+        mHandler.sendEmptyMessage(NOTIFY_STARTED_WAKING_UP);
+    }
+
+    private void notifyScreenOnLocked(IKeyguardDrawnCallback callback) {
         if (DEBUG) Log.d(TAG, "notifyScreenOnLocked");
-        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_ON, result);
+        Message msg = mHandler.obtainMessage(NOTIFY_SCREEN_TURNING_ON, callback);
         mHandler.sendMessage(msg);
     }
 
@@ -1190,8 +1202,11 @@
                 case NOTIFY_SCREEN_OFF:
                     handleNotifyScreenOff();
                     break;
-                case NOTIFY_SCREEN_ON:
-                    handleNotifyScreenOn((IKeyguardShowCallback) msg.obj);
+                case NOTIFY_SCREEN_TURNING_ON:
+                    handleNotifyScreenTurningOn((IKeyguardDrawnCallback) msg.obj);
+                    break;
+                case NOTIFY_STARTED_WAKING_UP:
+                    handleNotifyStartedWakingUp();
                     break;
                 case KEYGUARD_DONE:
                     handleKeyguardDone(msg.arg1 != 0, msg.arg2 != 0);
@@ -1354,6 +1369,7 @@
             setShowingLocked(true);
             mStatusBarKeyguardViewManager.show(options);
             mHiding = false;
+            mWakeAndUnlocking = false;
             resetKeyguardDonePendingLocked();
             mHideAnimationRun = false;
             updateActivityLockScreenState();
@@ -1375,7 +1391,8 @@
                 // manager until it tells us it's safe to do so with
                 // startKeyguardExitAnimation.
                 ActivityManagerNative.getDefault().keyguardGoingAway(
-                        mStatusBarKeyguardViewManager.shouldDisableWindowAnimationsForUnlock(),
+                        mStatusBarKeyguardViewManager.shouldDisableWindowAnimationsForUnlock()
+                                || mWakeAndUnlocking,
                         mStatusBarKeyguardViewManager.isGoingToNotificationShade());
             } catch (RemoteException e) {
                 Log.e(TAG, "Error while calling WindowManager", e);
@@ -1437,6 +1454,9 @@
             updateActivityLockScreenState();
             adjustStatusBarLocked();
             sendUserPresentBroadcast();
+            if (mWakeAndUnlocking && mDrawnCallback != null) {
+                notifyDrawn(mDrawnCallback);
+            }
         }
     }
 
@@ -1508,14 +1528,31 @@
         }
     }
 
-    /**
-     * Handle message sent by {@link #notifyScreenOnLocked}
-     * @see #NOTIFY_SCREEN_ON
-     */
-    private void handleNotifyScreenOn(IKeyguardShowCallback callback) {
+    private void handleNotifyStartedWakingUp() {
         synchronized (KeyguardViewMediator.this) {
-            if (DEBUG) Log.d(TAG, "handleNotifyScreenOn");
-            mStatusBarKeyguardViewManager.onScreenTurnedOn(callback);
+            if (DEBUG) Log.d(TAG, "handleNotifyWakingUp");
+            mStatusBarKeyguardViewManager.onScreenTurnedOn();
+        }
+    }
+
+    private void handleNotifyScreenTurningOn(IKeyguardDrawnCallback callback) {
+        synchronized (KeyguardViewMediator.this) {
+            if (DEBUG) Log.d(TAG, "handleNotifyScreenTurningOn");
+            if (callback != null) {
+                if (mWakeAndUnlocking) {
+                    mDrawnCallback = callback;
+                } else {
+                    notifyDrawn(callback);
+                }
+            }
+        }
+    }
+
+    private void notifyDrawn(final IKeyguardDrawnCallback callback) {
+        try {
+            callback.onDrawn();
+        } catch (RemoteException e) {
+            Slog.w(TAG, "Exception calling onDrawn():", e);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java b/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
index e9a256c..fe876d7 100644
--- a/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
+++ b/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
@@ -171,6 +171,13 @@
             }
             mAsyncPlayer.stop();
         }
+
+        @Override
+        public String getTitle(Uri uri) {
+            final UserHandle user = Binder.getCallingUserHandle();
+            return Ringtone.getTitle(getContextForUser(user), uri,
+                    false /*followSettingsUri*/, false /*allowRemote*/);
+        }
     };
 
     private Context getContextForUser(UserHandle user) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
index 937615a..61695b2 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/CastTile.java
@@ -92,7 +92,8 @@
 
     @Override
     protected void handleUpdateState(BooleanState state, Object arg) {
-        state.visible = !(mKeyguard.isSecure() && mKeyguard.isShowing() && !mKeyguard.isTrusted());
+        state.visible = !mKeyguard.isSecure() || !mKeyguard.isShowing()
+                || mKeyguard.canSkipBouncer();
         state.label = mContext.getString(R.string.quick_settings_cast_title);
         state.value = false;
         state.autoMirrorDrawable = false;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
index 07406b9..f3ad9d8 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/CellularTile.java
@@ -45,6 +45,8 @@
     private final MobileDataController mDataController;
     private final CellularDetailAdapter mDetailAdapter;
 
+    private final CellSignalCallback mSignalCallback = new CellSignalCallback();
+
     public CellularTile(Host host) {
         super(host);
         mController = host.getNetworkController();
@@ -90,8 +92,10 @@
     protected void handleUpdateState(SignalState state, Object arg) {
         state.visible = mController.hasMobileDataFeature();
         if (!state.visible) return;
-        final CallbackInfo cb = (CallbackInfo) arg;
-        if (cb == null) return;
+        CallbackInfo cb = (CallbackInfo) arg;
+        if (cb == null) {
+            cb = mSignalCallback.mInfo;
+        }
 
         final Resources r = mContext.getResources();
         final int iconId = cb.noSim ? R.drawable.ic_qs_no_sim
@@ -152,7 +156,7 @@
         boolean isDataTypeIconWide;
     }
 
-    private final SignalCallback mSignalCallback = new SignalCallbackAdapter() {
+    private final class CellSignalCallback extends SignalCallbackAdapter {
         private final CallbackInfo mInfo = new CallbackInfo();
         @Override
         public void setWifiIndicators(boolean enabled, IconState statusIcon, IconState qsIcon,
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
index ddde106..7b83e6a 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/HotspotTile.java
@@ -23,10 +23,9 @@
 import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.Prefs;
 import com.android.systemui.R;
-import com.android.systemui.qs.UsageTracker;
 import com.android.systemui.qs.QSTile;
+import com.android.systemui.qs.UsageTracker;
 import com.android.systemui.statusbar.policy.HotspotController;
-import com.android.systemui.statusbar.policy.KeyguardMonitor;
 
 /** Quick settings tile: Hotspot **/
 public class HotspotTile extends QSTile<QSTile.BooleanState> {
@@ -37,14 +36,12 @@
     private final HotspotController mController;
     private final Callback mCallback = new Callback();
     private final UsageTracker mUsageTracker;
-    private final KeyguardMonitor mKeyguard;
 
     public HotspotTile(Host host) {
         super(host);
         mController = host.getHotspotController();
         mUsageTracker = newUsageTracker(host.getContext());
         mUsageTracker.setListening(true);
-        mKeyguard = host.getKeyguardMonitor();
     }
 
     @Override
@@ -97,7 +94,7 @@
         if (arg instanceof Boolean) {
             state.value = (boolean) arg;
         } else {
-            mController.isHotspotEnabled();
+            state.value = mController.isHotspotEnabled();
         }
         state.icon = state.visible && state.value ? mEnable : mDisable;
     }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/IntentTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/IntentTile.java
index f7f7acb..3d0dc7b 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/IntentTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/IntentTile.java
@@ -45,6 +45,8 @@
     private int mCurrentUserId;
     private String mIntentPackage;
 
+    private Intent mLastIntent;
+
     private IntentTile(Host host, String action) {
         super(host);
         mContext.registerReceiver(mReceiver, new IntentFilter(action));
@@ -112,8 +114,16 @@
 
     @Override
     protected void handleUpdateState(State state, Object arg) {
-        if (!(arg instanceof Intent)) return;
-        final Intent intent = (Intent) arg;
+        Intent intent = (Intent) arg;
+        if (intent == null) {
+            if (mLastIntent == null) {
+                return;
+            }
+            // No intent but need to refresh state, just use the last one.
+            intent = mLastIntent;
+        }
+        // Save the last one in case we need it later.
+        mLastIntent = intent;
         state.visible = intent.getBooleanExtra("visible", true);
         state.contentDescription = intent.getStringExtra("contentDescription");
         state.label = intent.getStringExtra("label");
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/RotationLockTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/RotationLockTile.java
index 6d2c8c0..1a26a4d 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/RotationLockTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/RotationLockTile.java
@@ -78,8 +78,7 @@
             return;
         }
         state.value = rotationLocked;
-        final boolean portrait = mContext.getResources().getConfiguration().orientation
-                != Configuration.ORIENTATION_LANDSCAPE;
+        final boolean portrait = isCurrentOrientationLockPortrait();
         final AnimationIcon icon;
         if (rotationLocked) {
             final int label = portrait ? R.string.quick_settings_rotation_locked_portrait_label
@@ -98,6 +97,17 @@
                 R.string.accessibility_rotation_lock_off);
     }
 
+    private boolean isCurrentOrientationLockPortrait() {
+        int lockOrientation = mController.getRotationLockOrientation();
+        if (lockOrientation == Configuration.ORIENTATION_UNDEFINED) {
+            // Freely rotating device; use current rotation
+            return mContext.getResources().getConfiguration().orientation
+                    != Configuration.ORIENTATION_LANDSCAPE;
+        } else {
+            return lockOrientation != Configuration.ORIENTATION_LANDSCAPE;
+        }
+    }
+
     @Override
     public int getMetricsCategory() {
         return MetricsLogger.QS_ROTATIONLOCK;
@@ -116,9 +126,7 @@
             int idWhenOff) {
         int stringID;
         if (locked) {
-            final boolean portrait = mContext.getResources().getConfiguration().orientation
-                    != Configuration.ORIENTATION_LANDSCAPE;
-            stringID = portrait ? idWhenPortrait: idWhenLandscape;
+            stringID = isCurrentOrientationLockPortrait() ? idWhenPortrait: idWhenLandscape;
         } else {
             stringID = idWhenOff;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java
index 3bfff2f..e654efd 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/WifiTile.java
@@ -35,7 +35,6 @@
 import com.android.systemui.statusbar.policy.NetworkController;
 import com.android.systemui.statusbar.policy.NetworkController.AccessPointController;
 import com.android.systemui.statusbar.policy.NetworkController.IconState;
-import com.android.systemui.statusbar.policy.NetworkController.SignalCallback;
 import com.android.systemui.statusbar.policy.SignalCallbackAdapter;
 
 import java.util.List;
@@ -49,6 +48,8 @@
     private final WifiDetailAdapter mDetailAdapter;
     private final QSTile.SignalState mStateBeforeClick = newTileState();
 
+    private final WifiSignalCallback mSignalCallback = new WifiSignalCallback();
+
     public WifiTile(Host host) {
         super(host);
         mController = host.getNetworkController();
@@ -118,8 +119,10 @@
     protected void handleUpdateState(SignalState state, Object arg) {
         state.visible = true;
         if (DEBUG) Log.d(TAG, "handleUpdateState arg=" + arg);
-        if (arg == null) return;
         CallbackInfo cb = (CallbackInfo) arg;
+        if (cb == null) {
+            cb = mSignalCallback.mInfo;
+        }
 
         boolean wifiConnected = cb.enabled && (cb.wifiSignalIconId > 0) && (cb.enabledDesc != null);
         boolean wifiNotConnected = (cb.wifiSignalIconId > 0) && (cb.enabledDesc == null);
@@ -213,20 +216,21 @@
         }
     }
 
-    private final SignalCallback mSignalCallback = new SignalCallbackAdapter() {
+    private final class WifiSignalCallback extends SignalCallbackAdapter {
+        final CallbackInfo mInfo = new CallbackInfo();
+
         @Override
         public void setWifiIndicators(boolean enabled, IconState statusIcon, IconState qsIcon,
                 boolean activityIn, boolean activityOut, String description) {
             if (DEBUG) Log.d(TAG, "onWifiSignalChanged enabled=" + enabled);
-            final CallbackInfo info = new CallbackInfo();
-            info.enabled = enabled;
-            info.connected = qsIcon.visible;
-            info.wifiSignalIconId = qsIcon.icon;
-            info.enabledDesc = description;
-            info.activityIn = activityIn;
-            info.activityOut = activityOut;
-            info.wifiSignalContentDescription = qsIcon.contentDescription;
-            refreshState(info);
+            mInfo.enabled = enabled;
+            mInfo.connected = qsIcon.visible;
+            mInfo.wifiSignalIconId = qsIcon.icon;
+            mInfo.enabledDesc = description;
+            mInfo.activityIn = activityIn;
+            mInfo.activityOut = activityOut;
+            mInfo.wifiSignalContentDescription = qsIcon.contentDescription;
+            refreshState(mInfo);
         }
     };
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/ActivatableNotificationView.java b/packages/SystemUI/src/com/android/systemui/statusbar/ActivatableNotificationView.java
index 7cde44c..403af70 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/ActivatableNotificationView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/ActivatableNotificationView.java
@@ -656,12 +656,14 @@
     }
 
     private void setContentAlpha(float contentAlpha) {
-        int layerType = contentAlpha == 0.0f || contentAlpha == 1.0f ? LAYER_TYPE_NONE
-                : LAYER_TYPE_HARDWARE;
         View contentView = getContentView();
-        int currentLayerType = contentView.getLayerType();
-        if (currentLayerType != layerType) {
-            contentView.setLayerType(layerType, null);
+        if (contentView.hasOverlappingRendering()) {
+            int layerType = contentAlpha == 0.0f || contentAlpha == 1.0f ? LAYER_TYPE_NONE
+                    : LAYER_TYPE_HARDWARE;
+            int currentLayerType = contentView.getLayerType();
+            if (currentLayerType != layerType) {
+                contentView.setLayerType(layerType, null);
+            }
         }
         contentView.setAlpha(contentAlpha);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
index f62dc59..a2e6632 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
@@ -729,11 +729,15 @@
     }
 
     protected void setNotificationShown(StatusBarNotification n) {
-        mNotificationListener.setNotificationsShown(new String[] { n.getKey() });
+        setNotificationsShown(new String[]{n.getKey()});
     }
 
     protected void setNotificationsShown(String[] keys) {
-        mNotificationListener.setNotificationsShown(keys);
+        try {
+            mNotificationListener.setNotificationsShown(keys);
+        } catch (RuntimeException e) {
+            Log.d(TAG, "failed setNotificationsShown: ", e);
+        }
     }
 
     protected boolean isCurrentProfile(int userId) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/SignalClusterView.java b/packages/SystemUI/src/com/android/systemui/statusbar/SignalClusterView.java
index da1f03e..f7c3c67 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/SignalClusterView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/SignalClusterView.java
@@ -478,7 +478,6 @@
     }
 
     private void setTint(ImageView v, int tint) {
-        v.setImageTintMode(PorterDuff.Mode.SRC_ATOP);
         v.setImageTintList(ColorStateList.valueOf(tint));
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
index 815e123..a5310a5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
@@ -18,7 +18,6 @@
 
 import android.app.ActivityManager;
 import android.app.ActivityManagerNative;
-import android.app.Application;
 import android.app.admin.DevicePolicyManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
@@ -30,8 +29,6 @@
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.content.res.Configuration;
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.InsetDrawable;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.IBinder;
@@ -255,10 +252,10 @@
 
     private Intent getCameraIntent() {
         KeyguardUpdateMonitor updateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
-        boolean currentUserHasTrust = updateMonitor.getUserHasTrust(
+        boolean canSkipBouncer = updateMonitor.getUserCanSkipBouncer(
                 KeyguardUpdateMonitor.getCurrentUser());
         boolean secure = mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser());
-        return (secure && !currentUserHasTrust) ? SECURE_CAMERA_INTENT : INSECURE_CAMERA_INTENT;
+        return (secure && !canSkipBouncer) ? SECURE_CAMERA_INTENT : INSECURE_CAMERA_INTENT;
     }
 
     private void updateCameraVisibility() {
@@ -644,7 +641,7 @@
         }
 
         @Override
-        public void onFingerprintAuthenticated(int userId) {
+        public void onFingerprintAuthenticated(int userId, boolean wakeAndUnlocking) {
         }
 
         @Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
index a7afec4..e9b2c61 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBouncer.java
@@ -29,6 +29,7 @@
 import com.android.keyguard.KeyguardSecurityView;
 import com.android.keyguard.R;
 import com.android.keyguard.ViewMediatorCallback;
+import com.android.systemui.DejankUtils;
 
 import static com.android.keyguard.KeyguardHostView.OnDismissAction;
 import static com.android.keyguard.KeyguardSecurityModel.SecurityMode;
@@ -46,7 +47,6 @@
     private KeyguardHostView mKeyguardView;
     private ViewGroup mRoot;
     private boolean mShowingSoon;
-    private Choreographer mChoreographer = Choreographer.getInstance();
     private int mBouncerPromptReason;
 
     public KeyguardBouncer(Context context, ViewMediatorCallback callback,
@@ -70,16 +70,13 @@
             return;
         }
 
-        mBouncerPromptReason = mCallback.getBouncerPromptReason();
-
         // Try to dismiss the Keyguard. If no security pattern is set, this will dismiss the whole
         // Keyguard. If we need to authenticate, show the bouncer.
         if (!mKeyguardView.dismiss()) {
             mShowingSoon = true;
 
             // Split up the work over multiple frames.
-            mChoreographer.postCallbackDelayed(Choreographer.CALLBACK_ANIMATION, mShowRunnable,
-                    null, 16);
+            DejankUtils.postAfterTraversal(mShowRunnable);
         }
     }
 
@@ -107,7 +104,7 @@
     }
 
     private void cancelShowRunnable() {
-        mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION, mShowRunnable, null);
+        DejankUtils.removeCallbacks(mShowRunnable);
         mShowingSoon = false;
     }
 
@@ -165,6 +162,7 @@
         if (wasInitialized) {
             mKeyguardView.showPrimarySecurityScreen();
         }
+        mBouncerPromptReason = mCallback.getBouncerPromptReason();
     }
 
     private void ensureView() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
index 6bcb766..9e2ce15 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/LockIcon.java
@@ -214,7 +214,7 @@
         } else if (oldState == STATE_FINGERPRINT_ERROR && newState == STATE_FINGERPRINT) {
             return R.drawable.lockscreen_fingerprint_error_state_to_fp_animation;
         } else if (oldState == STATE_FINGERPRINT && newState == STATE_LOCK_OPEN
-                && !mUnlockMethodCache.isCurrentlyInsecure()) {
+                && !mUnlockMethodCache.isTrusted()) {
             return R.drawable.lockscreen_fingerprint_draw_off_animation;
         } else if (newState == STATE_FINGERPRINT && !oldScreenOn && screenOn) {
             return R.drawable.lockscreen_fingerprint_draw_on_animation;
@@ -226,7 +226,7 @@
     private int getState() {
         boolean fingerprintRunning =
                 KeyguardUpdateMonitor.getInstance(mContext).isFingerprintDetectionRunning();
-        if (mUnlockMethodCache.isCurrentlyInsecure()) {
+        if (mUnlockMethodCache.canSkipBouncer()) {
             return STATE_LOCK_OPEN;
         } else if (mTransientFpError) {
             return STATE_FINGERPRINT_ERROR;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
index f40f5016..416fb36 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
@@ -40,6 +40,7 @@
 import android.view.Surface;
 import android.view.View;
 import android.view.ViewGroup;
+import android.view.ViewRootImpl;
 import android.view.WindowManager;
 import android.view.inputmethod.InputMethodManager;
 import android.widget.FrameLayout;
@@ -184,6 +185,15 @@
         mBarTransitions = new NavigationBarTransitions(this);
     }
 
+    @Override
+    protected void onAttachedToWindow() {
+        super.onAttachedToWindow();
+        ViewRootImpl root = getViewRootImpl();
+        if (root != null) {
+            root.setDrawDuringWindowsAnimating(true);
+        }
+    }
+
     public BarTransitions getBarTransitions() {
         return mBarTransitions;
     }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
index 094b9b5..10191ed 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
@@ -773,14 +773,7 @@
                 && mQsExpansionEnabled) {
             mTwoFingerQsExpandPossible = true;
         }
-        final int pointerCount = event.getPointerCount();
-        final boolean twoFingerDrag = action == MotionEvent.ACTION_POINTER_DOWN
-                && pointerCount == 2;
-        final boolean stylusClickDrag = action == MotionEvent.ACTION_DOWN
-                && pointerCount == 1 && event.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS
-                && (event.isButtonPressed(MotionEvent.BUTTON_SECONDARY)
-                        || event.isButtonPressed(MotionEvent.BUTTON_TERTIARY));
-        if (mTwoFingerQsExpandPossible && (twoFingerDrag || stylusClickDrag)
+        if (mTwoFingerQsExpandPossible && isOpenQsEvent(event)
                 && event.getY(event.getActionIndex()) < mStatusBarMinHeight) {
             MetricsLogger.count(mContext, COUNTER_PANEL_OPEN_QS, 1);
             mQsExpandImmediate = true;
@@ -799,6 +792,24 @@
                 || y <= mQsContainer.getY() + mQsContainer.getHeight());
     }
 
+    private boolean isOpenQsEvent(MotionEvent event) {
+        final int pointerCount = event.getPointerCount();
+        final int action = event.getActionMasked();
+
+        final boolean twoFingerDrag = action == MotionEvent.ACTION_POINTER_DOWN
+                && pointerCount == 2;
+
+        final boolean stylusButtonClickDrag = action == MotionEvent.ACTION_DOWN
+                && (event.isButtonPressed(MotionEvent.BUTTON_STYLUS_PRIMARY)
+                        || event.isButtonPressed(MotionEvent.BUTTON_STYLUS_SECONDARY));
+
+        final boolean mouseButtonClickDrag = action == MotionEvent.ACTION_DOWN
+                && (event.isButtonPressed(MotionEvent.BUTTON_SECONDARY)
+                        || event.isButtonPressed(MotionEvent.BUTTON_TERTIARY));
+
+        return twoFingerDrag || stylusButtonClickDrag || mouseButtonClickDrag;
+    }
+
     private void handleQsDown(MotionEvent event) {
         if (event.getActionMasked() == MotionEvent.ACTION_DOWN
                 && shouldQuickSettingsIntercept(event.getX(), event.getY(), -1)) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
index 1e78f66..42e35a9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -1730,7 +1730,7 @@
     }
 
     private int adjustDisableFlags(int state) {
-        if (!mLaunchTransitionFadingAway
+        if (!mLaunchTransitionFadingAway && !mKeyguardFadingAway
                 && (mExpandedVisible || mBouncerShowing || mWaitingForKeyguardExit)) {
             state |= StatusBarManager.DISABLE_NOTIFICATION_ICONS;
             state |= StatusBarManager.DISABLE_SYSTEM_INFO;
@@ -2001,7 +2001,7 @@
     }
 
     public boolean isKeyguardCurrentlySecure() {
-        return !mUnlockMethodCache.isCurrentlyInsecure();
+        return !mUnlockMethodCache.canSkipBouncer();
     }
 
     public void setPanelExpanded(boolean isExpanded) {
@@ -2070,7 +2070,6 @@
         // Expand the window to encompass the full screen in anticipation of the drag.
         // This is only possible to do atomically because the status bar is at the top of the screen!
         mStatusBarWindowManager.setPanelVisible(true);
-        mStatusBarView.setFocusable(false);
 
         visibilityChanged(true);
         mWaitingForKeyguardExit = false;
@@ -2202,7 +2201,6 @@
         // Shrink the window to the size of the status bar only
         mStatusBarWindowManager.setPanelVisible(false);
         mStatusBarWindowManager.setForceStatusBarVisible(false);
-        mStatusBarView.setFocusable(true);
 
         // Close any "App info" popups that might have snuck on-screen
         dismissPopups();
@@ -2679,6 +2677,9 @@
         if (mBluetoothController != null) {
             mBluetoothController.dump(fd, pw, args);
         }
+        if (mHotspotController != null) {
+            mHotspotController.dump(fd, pw, args);
+        }
         if (mCastController != null) {
             mCastController.dump(fd, pw, args);
         }
@@ -2912,7 +2913,7 @@
         updateRowStates();
         mIconController.updateResources();
         mScreenPinningRequest.onConfigurationChanged();
-        mNetworkController.handleConfigurationChanged();
+        mNetworkController.onConfigurationChanged();
     }
 
     @Override
@@ -3051,20 +3052,20 @@
         boolean isOccluded = mStatusBarKeyguardViewManager.isOccluded();
         boolean isBouncerShowing = mStatusBarKeyguardViewManager.isBouncerShowing();
         boolean isSecure = mUnlockMethodCache.isMethodSecure();
-        boolean isCurrentlyInsecure = mUnlockMethodCache.isCurrentlyInsecure();
+        boolean canSkipBouncer = mUnlockMethodCache.canSkipBouncer();
         int stateFingerprint = getLoggingFingerprint(mState,
                 isShowing,
                 isOccluded,
                 isBouncerShowing,
                 isSecure,
-                isCurrentlyInsecure);
+                canSkipBouncer);
         if (stateFingerprint != mLastLoggedStateFingerprint) {
             EventLogTags.writeSysuiStatusBarState(mState,
                     isShowing ? 1 : 0,
                     isOccluded ? 1 : 0,
                     isBouncerShowing ? 1 : 0,
                     isSecure ? 1 : 0,
-                    isCurrentlyInsecure ? 1 : 0);
+                    canSkipBouncer ? 1 : 0);
             mLastLoggedStateFingerprint = stateFingerprint;
         }
     }
@@ -3210,7 +3211,7 @@
     public void dispatchDemoCommand(String command, Bundle args) {
         if (!mDemoModeAllowed) {
             mDemoModeAllowed = Settings.Global.getInt(mContext.getContentResolver(),
-                    "sysui_demo_allowed", 0) != 0;
+                    DEMO_MODE_ALLOWED, 0) != 0;
         }
         if (!mDemoModeAllowed) return;
         if (command.equals(COMMAND_ENTER)) {
@@ -3310,6 +3311,7 @@
             mDraggedDownRow.notifyHeightChanged(false  /* needsAnimation */);
             mDraggedDownRow = null;
         }
+        mAssistManager.onLockscreenShown();
     }
 
     private void onLaunchTransitionFadingEnded() {
@@ -3459,7 +3461,7 @@
                 startTime + fadeoutDuration
                         - StatusBarIconController.DEFAULT_TINT_ANIMATION_DURATION,
                 StatusBarIconController.DEFAULT_TINT_ANIMATION_DURATION);
-        disable(mDisabledUnmodified1, mDisabledUnmodified2, true /* animate */);
+        disable(mDisabledUnmodified1, mDisabledUnmodified2, fadeoutDuration > 0 /* animate */);
     }
 
     public boolean isKeyguardFadingAway() {
@@ -3668,7 +3670,7 @@
 
     public void onTrackingStopped(boolean expand) {
         if (mState == StatusBarState.KEYGUARD || mState == StatusBarState.SHADE_LOCKED) {
-            if (!expand && !mUnlockMethodCache.isCurrentlyInsecure()) {
+            if (!expand && !mUnlockMethodCache.canSkipBouncer()) {
                 showBouncer();
             }
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
index 6d04b28..c0887ca 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarView.java
@@ -24,6 +24,7 @@
 import android.view.View;
 import android.view.accessibility.AccessibilityEvent;
 
+import com.android.systemui.DejankUtils;
 import com.android.systemui.EventLogTags;
 import com.android.systemui.R;
 
@@ -117,12 +118,12 @@
     public void onAllPanelsCollapsed() {
         super.onAllPanelsCollapsed();
         // Close the status bar in the next frame so we can show the end of the animation.
-        postOnAnimation(mHideExpandedRunnable);
+        DejankUtils.postAfterTraversal(mHideExpandedRunnable);
         mLastFullyOpenedPanel = null;
     }
 
     public void removePendingHideExpandedRunnables() {
-        removeCallbacks(mHideExpandedRunnable);
+        DejankUtils.removeCallbacks(mHideExpandedRunnable);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
index bacf890..6816399 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
@@ -105,7 +105,7 @@
 
     public void onTrackingStarted() {
         mExpanding = true;
-        mDarkenWhileDragging = !mUnlockMethodCache.isCurrentlyInsecure();
+        mDarkenWhileDragging = !mUnlockMethodCache.canSkipBouncer();
     }
 
     public void onExpandingFinished() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/SettingsButton.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/SettingsButton.java
new file mode 100644
index 0000000..a1e9ece
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/SettingsButton.java
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.systemui.statusbar.phone;
+
+import android.animation.Animator;
+import android.animation.Animator.AnimatorListener;
+import android.animation.ObjectAnimator;
+import android.content.Context;
+import android.os.Handler;
+import android.os.Message;
+import android.util.AttributeSet;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.ViewConfiguration;
+import android.view.animation.Animation;
+import android.view.animation.AnimationUtils;
+
+import com.android.keyguard.AlphaOptimizedImageButton;
+
+public class SettingsButton extends AlphaOptimizedImageButton {
+
+    private static final long LONG_PRESS_LENGTH = 1000;
+    private static final long ACCEL_LENGTH = 750;
+    private static final long FULL_SPEED_LENGTH = 375;
+    private static final long RUN_DURATION = 350;
+
+    private boolean mUpToSpeed;
+    private ObjectAnimator mAnimator;
+
+    private float mSlop;
+
+    public SettingsButton(Context context, AttributeSet attrs) {
+        super(context, attrs);
+        mSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
+    }
+
+    public boolean isAnimating() {
+        return mAnimator != null && mAnimator.isRunning();
+    }
+
+    public boolean isTunerClick() {
+        return mUpToSpeed;
+    }
+
+    @Override
+    public boolean onTouchEvent(MotionEvent event) {
+        switch (event.getActionMasked()) {
+            case MotionEvent.ACTION_DOWN:
+                postDelayed(mLongPressCallback, LONG_PRESS_LENGTH);
+                break;
+            case MotionEvent.ACTION_UP:
+                if (mUpToSpeed) {
+                    startExitAnimation();
+                } else {
+                    cancelLongClick();
+                }
+                break;
+            case MotionEvent.ACTION_CANCEL:
+                cancelLongClick();
+                break;
+            case MotionEvent.ACTION_MOVE:
+                float x = event.getX();
+                float y = event.getY();
+                if ((x < -mSlop) || (y < -mSlop) || (x > getWidth() + mSlop)
+                        || (y > getHeight() + mSlop)) {
+                    cancelLongClick();
+                }
+                break;
+        }
+        return super.onTouchEvent(event);
+    }
+
+    private void cancelLongClick() {
+        cancelAnimation();
+        mUpToSpeed = false;
+        removeCallbacks(mLongPressCallback);
+    }
+
+    private void cancelAnimation() {
+        if (mAnimator != null) {
+            mAnimator.removeAllListeners();
+            mAnimator.cancel();
+            mAnimator = null;
+        }
+    }
+
+    private void startExitAnimation() {
+        animate()
+                .translationX(((View) getParent().getParent()).getWidth() - getX())
+                .alpha(0)
+                .setDuration(RUN_DURATION)
+                .setInterpolator(AnimationUtils.loadInterpolator(mContext,
+                        android.R.interpolator.accelerate_cubic))
+                .setListener(new AnimatorListener() {
+                    @Override
+                    public void onAnimationStart(Animator animation) {
+                    }
+
+                    @Override
+                    public void onAnimationRepeat(Animator animation) {
+                    }
+
+                    @Override
+                    public void onAnimationEnd(Animator animation) {
+                        setAlpha(1f);
+                        setTranslationX(0);
+                        cancelLongClick();
+                    }
+
+                    @Override
+                    public void onAnimationCancel(Animator animation) {
+                    }
+                })
+                .start();
+    }
+
+    protected void startAccelSpin() {
+        cancelAnimation();
+        mAnimator = ObjectAnimator.ofFloat(this, View.ROTATION, 0, 360);
+        mAnimator.setInterpolator(AnimationUtils.loadInterpolator(mContext,
+                android.R.interpolator.accelerate_quad));
+        mAnimator.setDuration(ACCEL_LENGTH);
+        mAnimator.addListener(new AnimatorListener() {
+            @Override
+            public void onAnimationStart(Animator animation) {
+            }
+
+            @Override
+            public void onAnimationRepeat(Animator animation) {
+            }
+
+            @Override
+            public void onAnimationEnd(Animator animation) {
+                startContinuousSpin();
+            }
+
+            @Override
+            public void onAnimationCancel(Animator animation) {
+            }
+        });
+        mAnimator.start();
+    }
+
+    protected void startContinuousSpin() {
+        cancelAnimation();
+        mUpToSpeed = true;
+        mAnimator = ObjectAnimator.ofFloat(this, View.ROTATION, 0, 360);
+        mAnimator.setInterpolator(AnimationUtils.loadInterpolator(mContext,
+                android.R.interpolator.linear));
+        mAnimator.setDuration(FULL_SPEED_LENGTH);
+        mAnimator.setRepeatCount(Animation.INFINITE);
+        mAnimator.start();
+    }
+
+    private final Runnable mLongPressCallback = new Runnable() {
+        @Override
+        public void run() {
+            startAccelSpin();
+        }
+    };
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeaderView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeaderView.java
index a81f06e2..5d58cd0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeaderView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarHeaderView.java
@@ -37,6 +37,7 @@
 import android.widget.RelativeLayout;
 import android.widget.Switch;
 import android.widget.TextView;
+import android.widget.Toast;
 
 import com.android.keyguard.KeyguardStatusView;
 import com.android.systemui.BatteryMeterView;
@@ -48,6 +49,7 @@
 import com.android.systemui.statusbar.policy.NetworkControllerImpl.EmergencyListener;
 import com.android.systemui.statusbar.policy.NextAlarmController;
 import com.android.systemui.statusbar.policy.UserInfoController;
+import com.android.systemui.tuner.TunerService;
 
 import java.text.NumberFormat;
 
@@ -73,7 +75,8 @@
     private TextView mDateExpanded;
     private LinearLayout mSystemIcons;
     private View mSignalCluster;
-    private View mSettingsButton;
+    private SettingsButton mSettingsButton;
+    private View mSettingsContainer;
     private View mQsDetailHeader;
     private TextView mQsDetailHeaderTitle;
     private Switch mQsDetailHeaderSwitch;
@@ -142,7 +145,8 @@
         mMultiUserAvatar = (ImageView) findViewById(R.id.multi_user_avatar);
         mDateCollapsed = (TextView) findViewById(R.id.date_collapsed);
         mDateExpanded = (TextView) findViewById(R.id.date_expanded);
-        mSettingsButton = findViewById(R.id.settings_button);
+        mSettingsButton = (SettingsButton) findViewById(R.id.settings_button);
+        mSettingsContainer = findViewById(R.id.settings_button_container);
         mSettingsButton.setOnClickListener(this);
         mQsDetailHeader = findViewById(R.id.qs_detail_header);
         mQsDetailHeader.setAlpha(0);
@@ -323,13 +327,15 @@
         mDateCollapsed.setVisibility(mExpanded && mAlarmShowing ? View.VISIBLE : View.INVISIBLE);
         mDateExpanded.setVisibility(mExpanded && mAlarmShowing ? View.INVISIBLE : View.VISIBLE);
         mAlarmStatus.setVisibility(mExpanded && mAlarmShowing ? View.VISIBLE : View.INVISIBLE);
-        mSettingsButton.setVisibility(mExpanded ? View.VISIBLE : View.INVISIBLE);
+        mSettingsContainer.setVisibility(mExpanded ? View.VISIBLE : View.INVISIBLE);
         mQsDetailHeader.setVisibility(mExpanded && mShowingDetail? View.VISIBLE : View.INVISIBLE);
         if (mSignalCluster != null) {
             updateSignalClusterDetachment();
         }
         mEmergencyCallsOnly.setVisibility(mExpanded && mShowEmergencyCallsOnly ? VISIBLE : GONE);
         mBatteryLevel.setVisibility(mExpanded ? View.VISIBLE : View.GONE);
+        mSettingsContainer.findViewById(R.id.tuner_icon).setVisibility(
+                TunerService.isTunerEnabled(mContext) ? View.VISIBLE : View.INVISIBLE);
     }
 
     private void updateSignalClusterDetachment() {
@@ -352,7 +358,7 @@
     private void updateSystemIconsLayoutParams() {
         RelativeLayout.LayoutParams lp = (LayoutParams) mSystemIconsSuperContainer.getLayoutParams();
         int rule = mExpanded
-                ? mSettingsButton.getId()
+                ? mSettingsContainer.getId()
                 : mMultiUserSwitch.getId();
         if (rule != lp.getRules()[RelativeLayout.START_OF]) {
             lp.addRule(RelativeLayout.START_OF, rule);
@@ -495,6 +501,20 @@
     @Override
     public void onClick(View v) {
         if (v == mSettingsButton) {
+            if (mSettingsButton.isTunerClick()) {
+                if (TunerService.isTunerEnabled(mContext)) {
+                    TunerService.showResetRequest(mContext, new Runnable() {
+                        @Override
+                        public void run() {
+                            // Relaunch settings so that the tuner disappears.
+                            startSettingsActivity();
+                        }
+                    });
+                } else {
+                    Toast.makeText(getContext(), R.string.tuner_toast, Toast.LENGTH_LONG).show();
+                    TunerService.setTunerEnabled(mContext, true);
+                }
+            }
             startSettingsActivity();
         } else if (v == mSystemIconsSuperContainer) {
             startBatteryActivity();
@@ -567,10 +587,10 @@
         }
         target.batteryY = mSystemIconsSuperContainer.getTop() + mSystemIconsContainer.getTop();
         target.batteryLevelAlpha = getAlphaForVisibility(mBatteryLevel);
-        target.settingsAlpha = getAlphaForVisibility(mSettingsButton);
+        target.settingsAlpha = getAlphaForVisibility(mSettingsContainer);
         target.settingsTranslation = mExpanded
                 ? 0
-                : mMultiUserSwitch.getLeft() - mSettingsButton.getLeft();
+                : mMultiUserSwitch.getLeft() - mSettingsContainer.getLeft();
         target.signalClusterAlpha = mSignalClusterDetached ? 0f : 1f;
         target.settingsRotation = !mExpanded ? 90f : 0f;
     }
@@ -622,9 +642,11 @@
             mSignalCluster.setTranslationX(0f);
             mSignalCluster.setTranslationY(0f);
         }
-        mSettingsButton.setTranslationY(mSystemIconsSuperContainer.getTranslationY());
-        mSettingsButton.setTranslationX(values.settingsTranslation);
-        mSettingsButton.setRotation(values.settingsRotation);
+        if (!mSettingsButton.isAnimating()) {
+            mSettingsContainer.setTranslationY(mSystemIconsSuperContainer.getTranslationY());
+            mSettingsContainer.setTranslationX(values.settingsTranslation);
+            mSettingsButton.setRotation(values.settingsRotation);
+        }
         applyAlpha(mEmergencyCallsOnly, values.emergencyCallsOnlyAlpha);
         if (!mShowingDetail && !mDetailTransitioning) {
             // Otherwise it needs to stay invisible
@@ -633,7 +655,7 @@
         applyAlpha(mDateCollapsed, values.dateCollapsedAlpha);
         applyAlpha(mDateExpanded, values.dateExpandedAlpha);
         applyAlpha(mBatteryLevel, values.batteryLevelAlpha);
-        applyAlpha(mSettingsButton, values.settingsAlpha);
+        applyAlpha(mSettingsContainer, values.settingsAlpha);
         applyAlpha(mSignalCluster, values.signalClusterAlpha);
         if (!mExpanded) {
             mTime.setScaleX(1f);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
index a69416a..e622144 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarKeyguardViewManager.java
@@ -19,15 +19,12 @@
 import android.content.ComponentCallbacks2;
 import android.content.Context;
 import android.os.Bundle;
-import android.os.RemoteException;
 import android.os.SystemClock;
-import android.util.Slog;
 import android.view.KeyEvent;
 import android.view.View;
 import android.view.ViewGroup;
 import android.view.WindowManagerGlobal;
 
-import com.android.internal.policy.IKeyguardShowCallback;
 import com.android.internal.widget.LockPatternUtils;
 import com.android.keyguard.KeyguardUpdateMonitor;
 import com.android.keyguard.ViewMediatorCallback;
@@ -163,26 +160,10 @@
         mBouncer.onScreenTurnedOff();
     }
 
-    public void onScreenTurnedOn(final IKeyguardShowCallback callback) {
+    public void onScreenTurnedOn() {
         mScreenOn = true;
         mScreenWillWakeUp = false;
         mPhoneStatusBar.onScreenTurnedOn();
-        if (callback != null) {
-            callbackAfterDraw(callback);
-        }
-    }
-
-    private void callbackAfterDraw(final IKeyguardShowCallback callback) {
-        mContainer.post(new Runnable() {
-            @Override
-            public void run() {
-                try {
-                    callback.onShown(mContainer.getWindowToken());
-                } catch (RemoteException e) {
-                    Slog.w(TAG, "Exception calling onShown():", e);
-                }
-            }
-        });
     }
 
     public void notifyScreenWakeUpRequested() {
@@ -270,16 +251,22 @@
             mPhoneStatusBar.setKeyguardFadingAway(startTime, delay, fadeoutDuration);
             boolean staying = mPhoneStatusBar.hideKeyguard();
             if (!staying) {
-                mStatusBarWindowManager.setKeyguardFadingAway(true);
-                mScrimController.animateKeyguardFadingOut(delay, fadeoutDuration, new Runnable() {
-                    @Override
-                    public void run() {
-                        mStatusBarWindowManager.setKeyguardFadingAway(false);
-                        mPhoneStatusBar.finishKeyguardFadingAway();
-                        WindowManagerGlobal.getInstance().trimMemory(
-                                ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
-                    }
-                });
+                if (fadeoutDuration == 0) {
+                    mPhoneStatusBar.finishKeyguardFadingAway();
+                    WindowManagerGlobal.getInstance().trimMemory(
+                            ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
+                } else {
+                    mStatusBarWindowManager.setKeyguardFadingAway(true);
+                    mScrimController.animateKeyguardFadingOut(delay, fadeoutDuration, new Runnable() {
+                        @Override
+                        public void run() {
+                            mStatusBarWindowManager.setKeyguardFadingAway(false);
+                            mPhoneStatusBar.finishKeyguardFadingAway();
+                            WindowManagerGlobal.getInstance().trimMemory(
+                                    ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
+                        }
+                    });
+                }
             } else {
                 mScrimController.animateGoingToFullShade(delay, fadeoutDuration);
                 mPhoneStatusBar.finishKeyguardFadingAway();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java
index 66d71f6..f31311d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java
@@ -39,9 +39,10 @@
     /** Whether the user configured a secure unlock method (PIN, password, etc.) */
     private boolean mSecure;
     /** Whether the unlock method is currently insecure (insecure method or trusted environment) */
-    private boolean mCurrentlyInsecure;
+    private boolean mCanSkipBouncer;
     private boolean mTrustManaged;
     private boolean mFaceUnlockRunning;
+    private boolean mTrusted;
 
     private UnlockMethodCache(Context ctx) {
         mLockPatternUtils = new LockPatternUtils(ctx);
@@ -64,11 +65,15 @@
         return mSecure;
     }
 
+    public boolean isTrusted() {
+        return mTrusted;
+    }
+
     /**
-     * @return whether the lockscreen is currently insecure, i. e. the bouncer won't be shown
+     * @return whether the lockscreen is currently insecure, and the bouncer won't be shown
      */
-    public boolean isCurrentlyInsecure() {
-        return mCurrentlyInsecure;
+    public boolean canSkipBouncer() {
+        return mCanSkipBouncer;
     }
 
     public void addListener(OnUnlockMethodChangedListener listener) {
@@ -82,15 +87,17 @@
     private void update(boolean updateAlways) {
         int user = KeyguardUpdateMonitor.getCurrentUser();
         boolean secure = mLockPatternUtils.isSecure(user);
-        boolean currentlyInsecure = !secure ||  mKeyguardUpdateMonitor.getUserHasTrust(user);
+        boolean canSkipBouncer = !secure ||  mKeyguardUpdateMonitor.getUserCanSkipBouncer(user);
         boolean trustManaged = mKeyguardUpdateMonitor.getUserTrustIsManaged(user);
+        boolean trusted = mKeyguardUpdateMonitor.getUserHasTrust(user);
         boolean faceUnlockRunning = mKeyguardUpdateMonitor.isFaceUnlockRunning(user)
                 && trustManaged;
-        boolean changed = secure != mSecure || currentlyInsecure != mCurrentlyInsecure ||
+        boolean changed = secure != mSecure || canSkipBouncer != mCanSkipBouncer ||
                 trustManaged != mTrustManaged  || faceUnlockRunning != mFaceUnlockRunning;
         if (changed || updateAlways) {
             mSecure = secure;
-            mCurrentlyInsecure = currentlyInsecure;
+            mCanSkipBouncer = canSkipBouncer;
+            mTrusted = trusted;
             mTrustManaged = trustManaged;
             mFaceUnlockRunning = faceUnlockRunning;
             notifyListeners();
@@ -125,7 +132,7 @@
         }
 
         @Override
-        public void onFingerprintAuthenticated(int userId) {
+        public void onFingerprintAuthenticated(int userId, boolean wakeAndUnlocking) {
             update(false /* updateAlways */);
         }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
index 04c626b..61986ad 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/Clock.java
@@ -232,7 +232,13 @@
             } else if (hhmm != null && hhmm.length() == 4) {
                 int hh = Integer.parseInt(hhmm.substring(0, 2));
                 int mm = Integer.parseInt(hhmm.substring(2));
-                mCalendar.set(Calendar.HOUR, hh);
+                boolean is24 = DateFormat.is24HourFormat(
+                        getContext(), ActivityManager.getCurrentUser());
+                if (is24) {
+                    mCalendar.set(Calendar.HOUR_OF_DAY, hh);
+                } else {
+                    mCalendar.set(Calendar.HOUR, hh);
+                }
                 mCalendar.set(Calendar.MINUTE, mm);
             }
             setText(getSmallTime());
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/HotspotControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/HotspotControllerImpl.java
index 1e3bc4d..41aeac9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/HotspotControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/HotspotControllerImpl.java
@@ -17,7 +17,6 @@
 package com.android.systemui.statusbar.policy;
 
 import android.content.BroadcastReceiver;
-import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
@@ -27,6 +26,8 @@
 
 import com.android.settingslib.TetherUtil;
 
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
 import java.util.ArrayList;
 
 public class HotspotControllerImpl implements HotspotController {
@@ -43,11 +44,32 @@
     private final ArrayList<Callback> mCallbacks = new ArrayList<Callback>();
     private final Receiver mReceiver = new Receiver();
     private final Context mContext;
-    private final WifiManager mWifiManager;
+
+    private int mHotspotState;
 
     public HotspotControllerImpl(Context context) {
         mContext = context;
-        mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
+    }
+
+    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        pw.println("HotspotController state:");
+        pw.print("  mHotspotEnabled="); pw.println(stateToString(mHotspotState));
+    }
+
+    private static String stateToString(int hotspotState) {
+        switch (hotspotState) {
+            case WifiManager.WIFI_AP_STATE_DISABLED:
+                return "DISABLED";
+            case WifiManager.WIFI_AP_STATE_DISABLING:
+                return "DISABLING";
+            case WifiManager.WIFI_AP_STATE_ENABLED:
+                return "ENABLED";
+            case WifiManager.WIFI_AP_STATE_ENABLING:
+                return "ENABLING";
+            case WifiManager.WIFI_AP_STATE_FAILED:
+                return "FAILED";
+        }
+        return null;
     }
 
     public void addCallback(Callback callback) {
@@ -66,7 +88,7 @@
 
     @Override
     public boolean isHotspotEnabled() {
-        return mWifiManager.getWifiApState() == WifiManager.WIFI_AP_STATE_ENABLED;
+        return mHotspotState == WifiManager.WIFI_AP_STATE_ENABLED;
     }
 
     @Override
@@ -76,7 +98,6 @@
 
     @Override
     public void setHotspotEnabled(boolean enabled) {
-        final ContentResolver cr = mContext.getContentResolver();
         // Call provisioning app which is called when enabling Tethering from Settings
         if (enabled && TetherUtil.isProvisioningNeeded(mContext)) {
             mContext.startServiceAsUser(TETHER_SERVICE_INTENT, UserHandle.CURRENT);
@@ -113,7 +134,8 @@
             if (DEBUG) Log.d(TAG, "onReceive " + intent.getAction());
             int state = intent.getIntExtra(
                     WifiManager.EXTRA_WIFI_AP_STATE, WifiManager.WIFI_AP_STATE_FAILED);
-            fireCallback(WifiManager.WIFI_AP_STATE_ENABLED == state);
+            mHotspotState = state;
+            fireCallback(mHotspotState == WifiManager.WIFI_AP_STATE_ENABLED);
         }
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardMonitor.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardMonitor.java
index d4eb553..d907b00 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardMonitor.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyguardMonitor.java
@@ -36,7 +36,7 @@
     private int mCurrentUser;
     private boolean mShowing;
     private boolean mSecure;
-    private boolean mTrusted;
+    private boolean mCanSkipBouncer;
 
     private boolean mListening;
 
@@ -47,7 +47,7 @@
             @Override
             public void onUserSwitched(int newUserId) {
                 mCurrentUser = newUserId;
-                updateTrustedState();
+                updateCanSkipBouncerState();
             }
         };
     }
@@ -57,7 +57,7 @@
         if (mCallbacks.size() != 0 && !mListening) {
             mListening = true;
             mCurrentUser = ActivityManager.getCurrentUser();
-            updateTrustedState();
+            updateCanSkipBouncerState();
             mKeyguardUpdateMonitor.registerCallback(this);
             mUserTracker.startTracking();
         }
@@ -79,8 +79,8 @@
         return mSecure;
     }
 
-    public boolean isTrusted() {
-        return mTrusted;
+    public boolean canSkipBouncer() {
+        return mCanSkipBouncer;
     }
 
     public void notifyKeyguardState(boolean showing, boolean secure) {
@@ -92,12 +92,12 @@
 
     @Override
     public void onTrustChanged(int userId) {
-        updateTrustedState();
+        updateCanSkipBouncerState();
         notifyKeyguardChanged();
     }
 
-    private void updateTrustedState() {
-        mTrusted = mKeyguardUpdateMonitor.getUserHasTrust(mCurrentUser);
+    private void updateCanSkipBouncerState() {
+        mCanSkipBouncer = mKeyguardUpdateMonitor.getUserCanSkipBouncer(mCurrentUser);
     }
 
     private void notifyKeyguardChanged() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
index 81f2d53..7cd94d7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
@@ -197,7 +197,6 @@
         filter.addAction(TelephonyIntents.SPN_STRINGS_UPDATED_ACTION);
         filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
         filter.addAction(ConnectivityManager.INET_CONDITION_ACTION);
-        filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
         filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
         mContext.registerReceiver(this, filter, null, mReceiverHandler);
         mListening = true;
@@ -339,8 +338,6 @@
         if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION) ||
                 action.equals(ConnectivityManager.INET_CONDITION_ACTION)) {
             updateConnectivity();
-        } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
-            handleConfigurationChanged();
         } else if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
             refreshLocale();
             updateAirplaneMode(false);
@@ -373,8 +370,18 @@
         }
     }
 
-    public void handleConfigurationChanged() {
+    public void onConfigurationChanged() {
         mConfig = Config.readConfig(mContext);
+        mReceiverHandler.post(new Runnable() {
+            @Override
+            public void run() {
+                handleConfigurationChanged();
+            }
+        });
+    }
+
+    @VisibleForTesting
+    void handleConfigurationChanged() {
         for (MobileSignalController mobileSignalController : mMobileSignalControllers.values()) {
             mobileSignalController.setConfiguration(mConfig);
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
index 41fc967..6fabe9b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
@@ -412,7 +412,7 @@
         public int getCount() {
             boolean secureKeyguardShowing = mController.mKeyguardMonitor.isShowing()
                     && mController.mKeyguardMonitor.isSecure()
-                    && !mController.mKeyguardMonitor.isTrusted();
+                    && !mController.mKeyguardMonitor.canSkipBouncer();
             if (!secureKeyguardShowing) {
                 return mController.mUsers.size();
             }
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/DemoModeFragment.java b/packages/SystemUI/src/com/android/systemui/tuner/DemoModeFragment.java
index 3f5ca58..a2b062c 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/DemoModeFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/DemoModeFragment.java
@@ -28,13 +28,14 @@
 import android.preference.PreferenceScreen;
 import android.preference.SwitchPreference;
 import android.provider.Settings;
+import android.view.MenuItem;
 
+import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.DemoMode;
 import com.android.systemui.R;
 
 public class DemoModeFragment extends PreferenceFragment implements OnPreferenceChangeListener {
 
-    private static final String DEMO_MODE_ALLOWED = "sysui_demo_allowed";
     private static final String DEMO_MODE_ON = "sysui_tuner_demo_on";
 
     private static final String[] STATUS_ICONS = {
@@ -75,10 +76,33 @@
         updateDemoModeEnabled();
         updateDemoModeOn();
         ContentResolver contentResolver = getContext().getContentResolver();
-        contentResolver.registerContentObserver(Settings.Global.getUriFor(DEMO_MODE_ALLOWED), false,
-                mDemoModeObserver);
+        contentResolver.registerContentObserver(Settings.Global.getUriFor(
+                DemoMode.DEMO_MODE_ALLOWED), false, mDemoModeObserver);
         contentResolver.registerContentObserver(Settings.Global.getUriFor(DEMO_MODE_ON), false,
                 mDemoModeObserver);
+        setHasOptionsMenu(true);
+    }
+
+    @Override
+    public boolean onOptionsItemSelected(MenuItem item) {
+        switch (item.getItemId()) {
+            case android.R.id.home:
+                getFragmentManager().popBackStack();
+                break;
+        }
+        return super.onOptionsItemSelected(item);
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+        MetricsLogger.visibility(getContext(), MetricsLogger.TUNER_DEMO_MODE, true);
+    }
+
+    @Override
+    public void onPause() {
+        super.onPause();
+        MetricsLogger.visibility(getContext(), MetricsLogger.TUNER_DEMO_MODE, false);
     }
 
     @Override
@@ -89,7 +113,7 @@
 
     private void updateDemoModeEnabled() {
         boolean enabled = Settings.Global.getInt(getContext().getContentResolver(),
-                DEMO_MODE_ALLOWED, 0) != 0;
+                DemoMode.DEMO_MODE_ALLOWED, 0) != 0;
         mEnabledSwitch.setChecked(enabled);
         mOnSwitch.setEnabled(enabled);
     }
@@ -102,15 +126,18 @@
 
     @Override
     public boolean onPreferenceChange(Preference preference, Object newValue) {
+        boolean enabled = newValue == Boolean.TRUE;
         if (preference == mEnabledSwitch) {
-            if (newValue != Boolean.TRUE) {
+            if (!enabled) {
                 // Make sure we aren't in demo mode when disabling it.
                 mOnSwitch.setChecked(false);
                 stopDemoMode();
             }
-            setGlobal(DEMO_MODE_ALLOWED, newValue == Boolean.TRUE ? 1 : 0);
+            MetricsLogger.action(getContext(), MetricsLogger.TUNER_DEMO_MODE_ENABLED, enabled);
+            setGlobal(DemoMode.DEMO_MODE_ALLOWED, enabled ? 1 : 0);
         } else if (preference == mOnSwitch) {
-            if (newValue == Boolean.TRUE) {
+            MetricsLogger.action(getContext(), MetricsLogger.TUNER_DEMO_MODE_ON, enabled);
+            if (enabled) {
                 startDemoMode();
             } else {
                 stopDemoMode();
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/QsTuner.java b/packages/SystemUI/src/com/android/systemui/tuner/QsTuner.java
index a5b244e..37ac098 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/QsTuner.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/QsTuner.java
@@ -40,6 +40,7 @@
 import android.widget.FrameLayout;
 import android.widget.ScrollView;
 
+import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.R;
 import com.android.systemui.qs.QSPanel;
 import com.android.systemui.qs.QSTile;
@@ -79,12 +80,25 @@
         menu.add(0, MENU_RESET, 0, com.android.internal.R.string.reset);
     }
 
+    public void onResume() {
+        super.onResume();
+        MetricsLogger.visibility(getContext(), MetricsLogger.TUNER_QS, true);
+    }
+
+    public void onPause() {
+        super.onPause();
+        MetricsLogger.visibility(getContext(), MetricsLogger.TUNER_QS, false);
+    }
+
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
             case MENU_RESET:
                 mTileHost.reset();
                 break;
+            case android.R.id.home:
+                getFragmentManager().popBackStack();
+                break;
         }
         return super.onOptionsItemSelected(item);
     }
@@ -205,6 +219,8 @@
             if (oldTile.equals(newTile)) {
                 return;
             }
+            MetricsLogger.action(getContext(), MetricsLogger.TUNER_QS_REORDER, oldTile + ","
+                    + newTile);
             List<String> order = new ArrayList<>(mTileSpecs);
             int index = order.indexOf(oldTile);
             if (index < 0) {
@@ -217,12 +233,14 @@
         }
 
         public void remove(String tile) {
+            MetricsLogger.action(getContext(), MetricsLogger.TUNER_QS_REMOVE, tile);
             List<String> tiles = new ArrayList<>(mTileSpecs);
             tiles.remove(tile);
             setTiles(tiles);
         }
 
         public void add(String tile) {
+            MetricsLogger.action(getContext(), MetricsLogger.TUNER_QS_ADD, tile);
             List<String> tiles = new ArrayList<>(mTileSpecs);
             tiles.add(tile);
             setTiles(tiles);
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/StatusBarSwitch.java b/packages/SystemUI/src/com/android/systemui/tuner/StatusBarSwitch.java
index d4cc56d..e5b550e 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/StatusBarSwitch.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/StatusBarSwitch.java
@@ -23,6 +23,7 @@
 import android.text.TextUtils;
 import android.util.AttributeSet;
 
+import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.statusbar.phone.StatusBarIconController;
 import com.android.systemui.tuner.TunerService.Tunable;
 
@@ -50,11 +51,14 @@
         if (!value) {
             // If not enabled add to blacklist.
             if (!mBlacklist.contains(getKey())) {
+                MetricsLogger.action(getContext(), MetricsLogger.TUNER_STATUS_BAR_DISABLE,
+                        getKey());
                 mBlacklist.add(getKey());
                 setList(mBlacklist);
             }
         } else {
             if (mBlacklist.remove(getKey())) {
+                MetricsLogger.action(getContext(), MetricsLogger.TUNER_STATUS_BAR_ENABLE, getKey());
                 setList(mBlacklist);
             }
         }
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java b/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java
index 4a8c2e4..71b5de5 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/TunerFragment.java
@@ -17,7 +17,10 @@
 
 import static com.android.systemui.BatteryMeterView.SHOW_PERCENT_SETTING;
 
+import android.app.AlertDialog;
 import android.app.FragmentTransaction;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
 import android.database.ContentObserver;
 import android.net.Uri;
 import android.os.Bundle;
@@ -28,19 +31,29 @@
 import android.preference.PreferenceFragment;
 import android.preference.PreferenceGroup;
 import android.preference.SwitchPreference;
+import android.provider.Settings;
 import android.provider.Settings.System;
+import android.view.Menu;
+import android.view.MenuInflater;
 import android.view.MenuItem;
 
+import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.R;
 import com.android.systemui.statusbar.phone.StatusBarIconController;
 import com.android.systemui.tuner.TunerService.Tunable;
 
 public class TunerFragment extends PreferenceFragment {
 
+    private static final String TAG = "TunerFragment";
+
     private static final String KEY_QS_TUNER = "qs_tuner";
     private static final String KEY_DEMO_MODE = "demo_mode";
     private static final String KEY_BATTERY_PCT = "battery_pct";
 
+    public static final String SETTING_SEEN_TUNER_WARNING = "seen_tuner_warning";
+
+    private static final int MENU_REMOVE = Menu.FIRST + 1;
+
     private final SettingObserver mSettingObserver = new SettingObserver();
 
     private SwitchPreference mBatteryPct;
@@ -73,6 +86,19 @@
             }
         });
         mBatteryPct = (SwitchPreference) findPreference(KEY_BATTERY_PCT);
+        if (Settings.Secure.getInt(getContext().getContentResolver(), SETTING_SEEN_TUNER_WARNING,
+                0) == 0) {
+            new AlertDialog.Builder(getContext())
+                    .setTitle(R.string.tuner_warning_title)
+                    .setMessage(R.string.tuner_warning)
+                    .setPositiveButton(R.string.got_it, new OnClickListener() {
+                        @Override
+                        public void onClick(DialogInterface dialog, int which) {
+                            Settings.Secure.putInt(getContext().getContentResolver(),
+                                    SETTING_SEEN_TUNER_WARNING, 1);
+                        }
+                    }).show();
+        }
     }
 
     @Override
@@ -83,6 +109,7 @@
                 System.getUriFor(SHOW_PERCENT_SETTING), false, mSettingObserver);
 
         registerPrefs(getPreferenceScreen());
+        MetricsLogger.visibility(getContext(), MetricsLogger.TUNER, true);
     }
 
     @Override
@@ -91,6 +118,7 @@
         getContext().getContentResolver().unregisterContentObserver(mSettingObserver);
 
         unregisterPrefs(getPreferenceScreen());
+        MetricsLogger.visibility(getContext(), MetricsLogger.TUNER, false);
     }
 
     private void registerPrefs(PreferenceGroup group) {
@@ -120,11 +148,24 @@
     }
 
     @Override
+    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+        menu.add(Menu.NONE, MENU_REMOVE, Menu.NONE, R.string.remove_from_settings);
+    }
+
+    @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
             case android.R.id.home:
                 getActivity().finish();
                 return true;
+            case MENU_REMOVE:
+                TunerService.showResetRequest(getContext(), new Runnable() {
+                    @Override
+                    public void run() {
+                        getActivity().finish();
+                    }
+                });
+                return true;
         }
         return super.onOptionsItemSelected(item);
     }
@@ -152,6 +193,7 @@
         @Override
         public boolean onPreferenceChange(Preference preference, Object newValue) {
             final boolean v = (Boolean) newValue;
+            MetricsLogger.action(getContext(), MetricsLogger.TUNER_BATTERY_PERCENTAGE, v);
             System.putInt(getContext().getContentResolver(), SHOW_PERCENT_SETTING, v ? 1 : 0);
             return true;
         }
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/TunerService.java b/packages/SystemUI/src/com/android/systemui/tuner/TunerService.java
index de5aaf6..d3f33ab 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/TunerService.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/TunerService.java
@@ -16,8 +16,15 @@
 package com.android.systemui.tuner;
 
 import android.app.ActivityManager;
+import android.app.AlertDialog;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
 import android.content.ContentResolver;
 import android.content.Context;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
+import android.content.Intent;
+import android.content.pm.PackageManager;
 import android.database.ContentObserver;
 import android.net.Uri;
 import android.os.Handler;
@@ -25,9 +32,13 @@
 import android.provider.Settings;
 import android.util.ArrayMap;
 
+import com.android.systemui.BatteryMeterView;
+import com.android.systemui.DemoMode;
+import com.android.systemui.R;
 import com.android.systemui.SystemUI;
 import com.android.systemui.SystemUIApplication;
 import com.android.systemui.settings.CurrentUserTracker;
+import com.android.systemui.statusbar.phone.SystemUIDialog;
 
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -36,6 +47,8 @@
 
 public class TunerService extends SystemUI {
 
+    public static final String ACTION_CLEAR = "com.android.systemui.action.CLEAR_TUNER";
+
     private final Observer mObserver = new Observer();
     // Map of Uris we listen on to their settings keys.
     private final ArrayMap<Uri, String> mListeningUris = new ArrayMap<>();
@@ -118,6 +131,19 @@
         }
     }
 
+    public void clearAll() {
+        // A couple special cases.
+        Settings.Global.putString(mContentResolver, DemoMode.DEMO_MODE_ALLOWED, null);
+        Settings.System.putString(mContentResolver, BatteryMeterView.SHOW_PERCENT_SETTING, null);
+        Intent intent = new Intent(DemoMode.ACTION_DEMO);
+        intent.putExtra(DemoMode.EXTRA_COMMAND, DemoMode.COMMAND_EXIT);
+        mContext.sendBroadcast(intent);
+
+        for (String key : mTunableLookup.keySet()) {
+            Settings.Secure.putString(mContentResolver, key, null);
+        }
+    }
+
     // Only used in other processes, such as the tuner.
     private static TunerService sInstance;
 
@@ -141,6 +167,44 @@
         return sInstance;
     }
 
+    public static final void showResetRequest(final Context context, final Runnable onDisabled) {
+        SystemUIDialog dialog = new SystemUIDialog(context);
+        dialog.setMessage(R.string.remove_from_settings_prompt);
+        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(R.string.cancel),
+                (OnClickListener) null);
+        dialog.setButton(DialogInterface.BUTTON_POSITIVE,
+                context.getString(R.string.guest_exit_guest_dialog_remove), new OnClickListener() {
+            @Override
+            public void onClick(DialogInterface dialog, int which) {
+                // Tell the tuner (in main SysUI process) to clear all its settings.
+                context.sendBroadcast(new Intent(TunerService.ACTION_CLEAR));
+                // Disable access to tuner.
+                TunerService.setTunerEnabled(context, false);
+                // Make them sit through the warning dialog again.
+                Settings.Secure.putInt(context.getContentResolver(),
+                        TunerFragment.SETTING_SEEN_TUNER_WARNING, 0);
+                if (onDisabled != null) {
+                    onDisabled.run();
+                }
+            }
+        });
+        dialog.show();
+    }
+
+    public static final void setTunerEnabled(Context context, boolean enabled) {
+        context.getPackageManager().setComponentEnabledSetting(
+                new ComponentName(context, TunerActivity.class),
+                enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
+                        : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
+                        PackageManager.DONT_KILL_APP);
+    }
+
+    public static final boolean isTunerEnabled(Context context) {
+        return context.getPackageManager().getComponentEnabledSetting(
+                new ComponentName(context, TunerActivity.class))
+                == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
+    }
+
     private class Observer extends ContentObserver {
         public Observer() {
             super(new Handler(Looper.getMainLooper()));
@@ -157,4 +221,13 @@
     public interface Tunable {
         void onTuningChanged(String key, String newValue);
     }
+
+    public static class ClearReceiver extends BroadcastReceiver {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            if (ACTION_CLEAR.equals(intent.getAction())) {
+                get(context).clearAll();
+            }
+        }
+    }
 }
diff --git a/rs/java/android/renderscript/ScriptIntrinsicBLAS.java b/rs/java/android/renderscript/ScriptIntrinsicBLAS.java
index 06134e5..c04191b 100644
--- a/rs/java/android/renderscript/ScriptIntrinsicBLAS.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicBLAS.java
@@ -3272,7 +3272,7 @@
 
 
     /**
-     * 8-bit GEMM-like operation for neural networks: C = B.transposed() * A
+     * 8-bit GEMM-like operation for neural networks: C = A * Transpose(B)
      * Calculations are done in 1.10.21 fixed-point format for the final output,
      * just before there's a shift down to drop the fractional parts. The output
      * values are gated to 0 to 255 to fit in a byte, but the 10-bit format
diff --git a/rs/java/android/renderscript/ScriptIntrinsicBlend.java b/rs/java/android/renderscript/ScriptIntrinsicBlend.java
index 906e0f6..6b09bb7 100644
--- a/rs/java/android/renderscript/ScriptIntrinsicBlend.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicBlend.java
@@ -360,6 +360,8 @@
     /**
      * dst = dst.rgb * src.a + (1.0 - dst.a) * src.rgb
      * dst.a = src.a
+     * Note: Before API 23, the alpha channel was not correctly set.
+     *       Please use with caution when targeting older APIs.
      *
      * @param ain The source buffer
      * @param aout The destination buffer
@@ -371,6 +373,8 @@
     /**
      * dst = dst.rgb * src.a + (1.0 - dst.a) * src.rgb
      * dst.a = src.a
+     * Note: Before API 23, the alpha channel was not correctly set.
+     *       Please use with caution when targeting older APIs.
      *
      * @param ain The source buffer
      * @param aout The destination buffer
diff --git a/services/core/java/com/android/server/DeviceIdleController.java b/services/core/java/com/android/server/DeviceIdleController.java
index c7c9d29..7561c7d 100644
--- a/services/core/java/com/android/server/DeviceIdleController.java
+++ b/services/core/java/com/android/server/DeviceIdleController.java
@@ -253,6 +253,8 @@
                 "max_temp_app_whitelist_duration";
         private static final String KEY_MMS_TEMP_APP_WHITELIST_DURATION =
                 "mms_temp_app_whitelist_duration";
+        private static final String KEY_SMS_TEMP_APP_WHITELIST_DURATION =
+                "sms_temp_app_whitelist_duration";
 
         /**
          * This is the time, after becoming inactive, at which we start looking at the
@@ -357,6 +359,13 @@
          */
         public long MMS_TEMP_APP_WHITELIST_DURATION;
 
+        /**
+         * Amount of time we would like to whitelist an app that is receiving an SMS.
+         * @see Settings.Global#DEVICE_IDLE_CONSTANTS
+         * @see #KEY_SMS_TEMP_APP_WHITELIST_DURATION
+         */
+        public long SMS_TEMP_APP_WHITELIST_DURATION;
+
         private final ContentResolver mResolver;
         private final KeyValueListParser mParser = new KeyValueListParser(',');
 
@@ -410,6 +419,8 @@
                         KEY_MAX_TEMP_APP_WHITELIST_DURATION, 5 * 60 * 1000L);
                 MMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
                         KEY_MMS_TEMP_APP_WHITELIST_DURATION, 60 * 1000L);
+                SMS_TEMP_APP_WHITELIST_DURATION = mParser.getLong(
+                        KEY_SMS_TEMP_APP_WHITELIST_DURATION, 20 * 1000L);
             }
         }
 
@@ -465,6 +476,10 @@
             pw.print("    "); pw.print(KEY_MMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
             TimeUtils.formatDuration(MMS_TEMP_APP_WHITELIST_DURATION, pw);
             pw.println();
+
+            pw.print("    "); pw.print(KEY_SMS_TEMP_APP_WHITELIST_DURATION); pw.print("=");
+            TimeUtils.formatDuration(SMS_TEMP_APP_WHITELIST_DURATION, pw);
+            pw.println();
         }
     }
 
@@ -617,6 +632,13 @@
             return duration;
         }
 
+        @Override public long addPowerSaveTempWhitelistAppForSms(String packageName,
+                int userId, String reason) throws RemoteException {
+            long duration = mConstants.SMS_TEMP_APP_WHITELIST_DURATION;
+            addPowerSaveTempWhitelistApp(packageName, duration, userId, reason);
+            return duration;
+        }
+
         @Override public void exitIdle(String reason) {
             getContext().enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER,
                     null);
diff --git a/services/core/java/com/android/server/MountService.java b/services/core/java/com/android/server/MountService.java
index 0e158a2..92b98a7 100644
--- a/services/core/java/com/android/server/MountService.java
+++ b/services/core/java/com/android/server/MountService.java
@@ -740,15 +740,20 @@
      */
     @Deprecated
     private void killMediaProvider() {
-        final ProviderInfo provider = mPms.resolveContentProvider(MediaStore.AUTHORITY, 0,
-                UserHandle.USER_OWNER);
-        if (provider != null) {
-            final IActivityManager am = ActivityManagerNative.getDefault();
-            try {
-                am.killApplicationWithAppId(provider.applicationInfo.packageName,
-                        UserHandle.getAppId(provider.applicationInfo.uid), "vold reset");
-            } catch (RemoteException e) {
+        final long token = Binder.clearCallingIdentity();
+        try {
+            final ProviderInfo provider = mPms.resolveContentProvider(MediaStore.AUTHORITY, 0,
+                    UserHandle.USER_OWNER);
+            if (provider != null) {
+                final IActivityManager am = ActivityManagerNative.getDefault();
+                try {
+                    am.killApplicationWithAppId(provider.applicationInfo.packageName,
+                            UserHandle.getAppId(provider.applicationInfo.uid), "vold reset");
+                } catch (RemoteException e) {
+                }
             }
+        } finally {
+            Binder.restoreCallingIdentity(token);
         }
     }
 
diff --git a/services/core/java/com/android/server/accounts/AccountManagerService.java b/services/core/java/com/android/server/accounts/AccountManagerService.java
index a270974..cb294fd 100644
--- a/services/core/java/com/android/server/accounts/AccountManagerService.java
+++ b/services/core/java/com/android/server/accounts/AccountManagerService.java
@@ -534,9 +534,10 @@
                     account.type);
             throw new SecurityException(msg);
         }
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             return readPasswordInternal(accounts, account);
         } finally {
             restoreCallingIdentity(identityToken);
@@ -572,9 +573,10 @@
                     + ", pid " + Binder.getCallingPid());
         }
         if (account == null) throw new IllegalArgumentException("account is null");
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             return readPreviousNameInternal(accounts, account);
         } finally {
             restoreCallingIdentity(identityToken);
@@ -632,9 +634,10 @@
                     account.type);
             throw new SecurityException(msg);
         }
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             return readUserDataInternal(accounts, account, key);
         } finally {
             restoreCallingIdentity(identityToken);
@@ -709,11 +712,12 @@
          *     a limited user.
          */
 
-        UserAccounts accounts = getUserAccountsForCaller();
         // fails if the account already exists
         int uid = getCallingUid();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             return addAccountInternal(accounts, account, password, extras, false, uid);
         } finally {
             restoreCallingIdentity(identityToken);
@@ -801,6 +805,13 @@
         if (!canUserModifyAccounts(userId) || !canUserModifyAccountsForType(userId, account.type)) {
             return false;
         }
+        int user = UserHandle.getCallingUserId();
+        long identityToken = clearCallingIdentity();
+        try {
+            UserAccounts accounts = getUserAccounts(user);
+        } finally {
+            restoreCallingIdentity(identityToken);
+        }
         return updateLastAuthenticatedTime(account);
     }
 
@@ -975,9 +986,10 @@
         if (account == null) throw new IllegalArgumentException("account is null");
         if (features == null) throw new IllegalArgumentException("features is null");
         checkReadAccountsPermitted(callingUid, account.type);
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             new TestFeaturesSession(accounts, response, account, features).bind();
         } finally {
             restoreCallingIdentity(identityToken);
@@ -1057,9 +1069,10 @@
                     accountToRename.type);
             throw new SecurityException(msg);
         }
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             Account resultingAccount = renameAccountInternal(accounts, accountToRename, newName);
             Bundle result = new Bundle();
             result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
@@ -1206,7 +1219,6 @@
             throw new SecurityException(msg);
         }
 
-        UserAccounts accounts = getUserAccounts(userId);
         if (!canUserModifyAccounts(userId)) {
             try {
                 response.onError(AccountManager.ERROR_CODE_USER_RESTRICTED,
@@ -1227,6 +1239,7 @@
         UserHandle user = new UserHandle(userId);
         long identityToken = clearCallingIdentity();
 
+        UserAccounts accounts = getUserAccounts(userId);
         cancelNotification(getSigninRequiredNotificationId(accounts, account), user);
         synchronized(accounts.credentialsPermissionNotificationIds) {
             for (Pair<Pair<Account, String>, Integer> pair:
@@ -1381,9 +1394,10 @@
         }
         if (accountType == null) throw new IllegalArgumentException("accountType is null");
         if (authToken == null) throw new IllegalArgumentException("authToken is null");
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             synchronized (accounts.cacheLock) {
                 final SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
                 db.beginTransaction();
@@ -1517,9 +1531,10 @@
                     account.type);
             throw new SecurityException(msg);
         }
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             return readAuthTokenInternal(accounts, account, authTokenType);
         } finally {
             restoreCallingIdentity(identityToken);
@@ -1544,9 +1559,10 @@
                     account.type);
             throw new SecurityException(msg);
         }
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             saveAuthTokenToDatabase(accounts, account, authTokenType, authToken);
         } finally {
             restoreCallingIdentity(identityToken);
@@ -1569,9 +1585,10 @@
                     account.type);
             throw new SecurityException(msg);
         }
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             setPasswordInternal(accounts, account, password, callingUid);
         } finally {
             restoreCallingIdentity(identityToken);
@@ -1632,9 +1649,10 @@
                     account.type);
             throw new SecurityException(msg);
         }
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             setPasswordInternal(accounts, account, null, callingUid);
         } finally {
             restoreCallingIdentity(identityToken);
@@ -1659,9 +1677,10 @@
                     account.type);
             throw new SecurityException(msg);
         }
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             setUserdataInternal(accounts, account, key, value);
         } finally {
             restoreCallingIdentity(identityToken);
@@ -1734,9 +1753,10 @@
         if (callingUid != Process.SYSTEM_UID) {
             throw new SecurityException("can only call from system");
         }
-        UserAccounts accounts = getUserAccounts(UserHandle.getUserId(callingUid));
+        int userId = UserHandle.getUserId(callingUid);
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             new Session(accounts, response, accountType, false /* expectActivityLaunch */,
                     false /* stripAuthTokenFromResult */,  null /* accountName */,
                     false /* authDetailsRequired */) {
@@ -1803,11 +1823,17 @@
             Slog.w(TAG, "Failed to report error back to the client." + e);
             return;
         }
-
-        final UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
+        long ident = Binder.clearCallingIdentity();
+        final UserAccounts accounts;
         final RegisteredServicesCache.ServiceInfo<AuthenticatorDescription> authenticatorInfo;
-        authenticatorInfo = mAuthenticatorCache.getServiceInfo(
-                AuthenticatorDescription.newKey(account.type), accounts.userId);
+        try {
+            accounts = getUserAccounts(userId);
+            authenticatorInfo = mAuthenticatorCache.getServiceInfo(
+                    AuthenticatorDescription.newKey(account.type), accounts.userId);
+        } finally {
+            Binder.restoreCallingIdentity(ident);
+        }
 
         final boolean customTokens =
                 authenticatorInfo != null && authenticatorInfo.type.customTokens;
@@ -1820,7 +1846,7 @@
         // Get the calling package. We will use it for the purpose of caching.
         final String callerPkg = loginOptions.getString(AccountManager.KEY_ANDROID_PACKAGE_NAME);
         List<String> callerOwnedPackageNames;
-        long ident = Binder.clearCallingIdentity();
+        ident = Binder.clearCallingIdentity();
         try {
             callerOwnedPackageNames = Arrays.asList(mPackageManager.getPackagesForUid(callerUid));
         } finally {
@@ -2108,17 +2134,18 @@
             return;
         }
 
-        UserAccounts accounts = getUserAccountsForCaller();
         final int pid = Binder.getCallingPid();
         final int uid = Binder.getCallingUid();
         final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
         options.putInt(AccountManager.KEY_CALLER_UID, uid);
         options.putInt(AccountManager.KEY_CALLER_PID, pid);
 
-        logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS);
-
+        int usrId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(usrId);
+            logRecordWithUid(
+                    accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, uid);
             new Session(accounts, response, accountType, expectActivityLaunch,
                     true /* stripAuthTokenFromResult */, null /* accountName */,
                     false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
@@ -2190,17 +2217,17 @@
             return;
         }
 
-        UserAccounts accounts = getUserAccounts(userId);
         final int pid = Binder.getCallingPid();
         final int uid = Binder.getCallingUid();
         final Bundle options = (optionsIn == null) ? new Bundle() : optionsIn;
         options.putInt(AccountManager.KEY_CALLER_UID, uid);
         options.putInt(AccountManager.KEY_CALLER_PID, pid);
 
-        logRecord(accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS);
-
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
+            logRecordWithUid(
+                    accounts, DebugDbHelper.ACTION_CALLED_ACCOUNT_ADD, TABLE_ACCOUNTS, userId);
             new Session(accounts, response, accountType, expectActivityLaunch,
                     true /* stripAuthTokenFromResult */, null /* accountName */,
                     false /* authDetailsRequired */, true /* updateLastAuthenticationTime */) {
@@ -2262,9 +2289,9 @@
         }
         if (response == null) throw new IllegalArgumentException("response is null");
         if (account == null) throw new IllegalArgumentException("account is null");
-        UserAccounts accounts = getUserAccounts(userId);
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             new Session(accounts, response, account.type, expectActivityLaunch,
                     true /* stripAuthTokenFromResult */, account.name,
                     true /* authDetailsRequired */, true /* updateLastAuthenticatedTime */) {
@@ -2298,9 +2325,10 @@
         if (response == null) throw new IllegalArgumentException("response is null");
         if (account == null) throw new IllegalArgumentException("account is null");
         if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             new Session(accounts, response, account.type, expectActivityLaunch,
                     true /* stripAuthTokenFromResult */, account.name,
                     false /* authDetailsRequired */, true /* updateLastCredentialTime */) {
@@ -2342,9 +2370,10 @@
                     accountType);
             throw new SecurityException(msg);
         }
-        UserAccounts accounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             new Session(accounts, response, accountType, expectActivityLaunch,
                     true /* stripAuthTokenFromResult */, null /* accountName */,
                     false /* authDetailsRequired */) {
@@ -2468,13 +2497,13 @@
      * @hide
      */
     public Account[] getAccounts(int userId) {
-        UserAccounts accounts = getUserAccounts(userId);
         int callingUid = Binder.getCallingUid();
         if (!isReadAccountsPermitted(callingUid, null)) {
             return new Account[0];
         }
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts accounts = getUserAccounts(userId);
             synchronized (accounts.cacheLock) {
                 return getAccountsFromCacheLocked(accounts, null, callingUid, null);
             }
@@ -2720,9 +2749,10 @@
             }
             return;
         }
-        UserAccounts userAccounts = getUserAccountsForCaller();
+        int userId = UserHandle.getCallingUserId();
         long identityToken = clearCallingIdentity();
         try {
+            UserAccounts userAccounts = getUserAccounts(userId);
             if (features == null || features.length == 0) {
                 Account[] accounts;
                 synchronized (userAccounts.cacheLock) {
@@ -3227,6 +3257,11 @@
         logRecord(db, action, tableName, -1, accounts);
     }
 
+    private void logRecordWithUid(UserAccounts accounts, String action, String tableName, int uid) {
+        SQLiteDatabase db = accounts.openHelper.getWritableDatabase();
+        logRecord(db, action, tableName, -1, accounts, uid);
+    }
+
     /*
      * This function receives an opened writable database.
      */
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 37aa408..eb6579c9 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -18,10 +18,7 @@
 
 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
-import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
 import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
-import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
-import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
 import static com.android.internal.util.XmlUtils.readBooleanAttribute;
 import static com.android.internal.util.XmlUtils.readIntAttribute;
@@ -68,6 +65,7 @@
 import android.os.storage.MountServiceInternal;
 import android.os.storage.StorageManager;
 import android.service.voice.IVoiceInteractionSession;
+import android.service.voice.VoiceInteractionSession;
 import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.DebugUtils;
@@ -76,6 +74,7 @@
 
 import com.android.internal.R;
 import com.android.internal.annotations.GuardedBy;
+import com.android.internal.app.AssistUtils;
 import com.android.internal.app.DumpHeapActivity;
 import com.android.internal.app.IAppOpsService;
 import com.android.internal.app.IVoiceInteractor;
@@ -3516,8 +3515,8 @@
                     intent.setComponent(new ComponentName(
                             ri.activityInfo.packageName, ri.activityInfo.name));
                     mStackSupervisor.startActivityLocked(null, intent, null, ri.activityInfo,
-                            null, null, null, null, 0, 0, 0, null, 0, 0, 0, null, false, null, null,
-                            null);
+                            null, null, null, null, 0, 0, 0, null, 0, 0, 0, null, false, false,
+                            null, null, null);
                 }
             }
         }
@@ -3803,13 +3802,14 @@
         // TODO: Switch to user app stacks here.
         return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
-                profilerInfo, null, null, options, userId, null, null);
+                profilerInfo, null, null, options, false, userId, null, null);
     }
 
     @Override
     public final int startActivityAsCaller(IApplicationThread caller, String callingPackage,
             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
-            int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
+            int startFlags, ProfilerInfo profilerInfo, Bundle options, boolean ignoreTargetSecurity,
+            int userId) {
 
         // This is very dangerous -- it allows you to perform a start activity (including
         // permission grants) as any app that may launch one of your own activities.  So
@@ -3843,6 +3843,16 @@
                                     + sourceRecord.launchedFromUid);
                 }
             }
+            if (ignoreTargetSecurity) {
+                if (intent.getComponent() == null) {
+                    throw new SecurityException(
+                            "Component must be specified with ignoreTargetSecurity");
+                }
+                if (intent.getSelector() != null) {
+                    throw new SecurityException(
+                            "Selector not allowed with ignoreTargetSecurity");
+                }
+            }
             targetUid = sourceRecord.launchedFromUid;
             targetPackage = sourceRecord.launchedFromPackage;
         }
@@ -3855,7 +3865,7 @@
         try {
             int ret = mStackSupervisor.startActivityMayWait(null, targetUid, targetPackage, intent,
                     resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, null,
-                    null, null, options, userId, null, null);
+                    null, null, options, ignoreTargetSecurity, userId, null, null);
             return ret;
         } catch (SecurityException e) {
             // XXX need to figure out how to propagate to original app.
@@ -3884,7 +3894,7 @@
         // TODO: Switch to user app stacks here.
         mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
                 null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, res, null,
-                options, userId, null, null);
+                options, false, userId, null, null);
         return res;
     }
 
@@ -3898,7 +3908,7 @@
         // TODO: Switch to user app stacks here.
         int ret = mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
-                null, null, config, options, userId, null, null);
+                null, null, config, options, false, userId, null, null);
         return ret;
     }
 
@@ -3956,7 +3966,7 @@
         // TODO: Switch to user app stacks here.
         return mStackSupervisor.startActivityMayWait(null, callingUid, callingPackage, intent,
                 resolvedType, session, interactor, null, null, 0, startFlags, profilerInfo, null,
-                null, options, userId, null, null);
+                null, options, false, userId, null, null);
     }
 
     @Override
@@ -4067,7 +4077,7 @@
             int res = mStackSupervisor.startActivityLocked(r.app.thread, intent,
                     r.resolvedType, aInfo, null, null, resultTo != null ? resultTo.appToken : null,
                     resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage,
-                    -1, r.launchedFromUid, 0, options, false, null, null, null);
+                    -1, r.launchedFromUid, 0, options, false, false, null, null, null);
             Binder.restoreCallingIdentity(origId);
 
             r.finishing = wasFinishing;
@@ -4125,7 +4135,7 @@
         // TODO: Switch to user app stacks here.
         int ret = mStackSupervisor.startActivityMayWait(null, uid, callingPackage, intent,
                 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
-                null, null, null, options, userId, container, inTask);
+                null, null, null, options, false, userId, container, inTask);
         return ret;
     }
 
@@ -10678,7 +10688,7 @@
     @Override
     public Bundle getAssistContextExtras(int requestType) {
         PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null,
-                UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT);
+                null, UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT);
         if (pae == null) {
             return null;
         }
@@ -10699,7 +10709,7 @@
     }
 
     @Override
-    public boolean isScreenCaptureAllowedOnCurrentActivity() {
+    public boolean isAssistDataAllowedOnCurrentActivity() {
         int userId = mCurrentUserId;
         synchronized (this) {
             ActivityRecord activity = getFocusedStack().topActivity();
@@ -10714,13 +10724,41 @@
     }
 
     @Override
-    public void requestAssistContextExtras(int requestType, IResultReceiver receiver) {
-        enqueueAssistContext(requestType, null, null, receiver, UserHandle.getCallingUserId(),
-                null, PENDING_ASSIST_EXTRAS_LONG_TIMEOUT);
+    public boolean showAssistFromActivity(IBinder token, Bundle args) {
+        long ident = Binder.clearCallingIdentity();
+        try {
+            synchronized (this) {
+                ActivityRecord caller = ActivityRecord.forTokenLocked(token);
+                ActivityRecord top = getFocusedStack().topActivity();
+                if (top != caller) {
+                    Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
+                            + " is not current top " + top);
+                    return false;
+                }
+                if (!top.nowVisible) {
+                    Slog.w(TAG, "showAssistFromActivity failed: caller " + caller
+                            + " is not visible");
+                    return false;
+                }
+            }
+            AssistUtils utils = new AssistUtils(mContext);
+            return utils.showSessionForActiveService(args,
+                    VoiceInteractionSession.SHOW_SOURCE_APPLICATION, null, token);
+        } finally {
+            Binder.restoreCallingIdentity(ident);
+        }
+    }
+
+    @Override
+    public boolean requestAssistContextExtras(int requestType, IResultReceiver receiver,
+            IBinder activityToken) {
+        return enqueueAssistContext(requestType, null, null, receiver, activityToken,
+                UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_LONG_TIMEOUT) != null;
     }
 
     private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint,
-            IResultReceiver receiver, int userHandle, Bundle args, long timeout) {
+            IResultReceiver receiver, IBinder activityToken, int userHandle, Bundle args,
+            long timeout) {
         enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
                 "enqueueAssistContext()");
         synchronized (this) {
@@ -10733,9 +10771,13 @@
                 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity);
                 return null;
             }
-            if (activity.app.pid == Binder.getCallingPid()) {
-                Slog.w(TAG, "getAssistContextExtras failed: request process same as " + activity);
-                return null;
+            if (activityToken != null) {
+                ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken);
+                if (activity != caller) {
+                    Slog.w(TAG, "enqueueAssistContext failed: caller " + caller
+                            + " is not current top " + activity);
+                    return null;
+                }
             }
             PendingAssistExtras pae;
             Bundle extras = new Bundle();
@@ -10801,6 +10843,8 @@
         }
 
         // We are now ready to launch the assist activity.
+        IResultReceiver sendReceiver = null;
+        Bundle sendBundle = null;
         synchronized (this) {
             buildAssistBundleLocked(pae, extras);
             boolean exists = mPendingAssistExtras.remove(pae);
@@ -10809,19 +10853,21 @@
                 // Timed out.
                 return;
             }
-            if (pae.receiver != null) {
+            if ((sendReceiver=pae.receiver) != null) {
                 // Caller wants result sent back to them.
-                Bundle topBundle = new Bundle();
-                topBundle.putBundle("data", pae.extras);
-                topBundle.putParcelable("structure", pae.structure);
-                topBundle.putParcelable("content", pae.content);
-                try {
-                    pae.receiver.send(0, topBundle);
-                } catch (RemoteException e) {
-                }
-                return;
+                sendBundle = new Bundle();
+                sendBundle.putBundle("data", pae.extras);
+                sendBundle.putParcelable("structure", pae.structure);
+                sendBundle.putParcelable("content", pae.content);
             }
         }
+        if (sendReceiver != null) {
+            try {
+                sendReceiver.send(0, sendBundle);
+            } catch (RemoteException e) {
+            }
+            return;
+        }
 
         long ident = Binder.clearCallingIdentity();
         try {
@@ -10842,7 +10888,7 @@
 
     public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle,
             Bundle args) {
-        return enqueueAssistContext(requestType, intent, hint, null, userHandle, args,
+        return enqueueAssistContext(requestType, intent, hint, null, null, userHandle, args,
                 PENDING_ASSIST_EXTRAS_TIMEOUT) != null;
     }
 
@@ -20525,7 +20571,7 @@
             }
             return mStackSupervisor.startActivityMayWait(appThread, -1, callingPackage, intent,
                     resolvedType, null, null, null, null, 0, 0, null, null,
-                    null, options, callingUser, null, tr);
+                    null, options, false, callingUser, null, tr);
         }
 
         @Override
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index 470bbb0e..a75cc48 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/am/ActivityStack.java
@@ -617,12 +617,9 @@
             for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
                 ActivityRecord r = activities.get(activityNdx);
                 if (notCurrentUserTask && (r.info.flags & FLAG_SHOW_FOR_ALL_USERS) == 0) {
-                    return null;
+                    continue;
                 }
                 if (!r.finishing && r.intent.getComponent().equals(cls) && r.userId == userId) {
-                    //Slog.i(TAG, "Found matching class!");
-                    //dump();
-                    //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
                     return r;
                 }
             }
@@ -3117,7 +3114,7 @@
                     int res = mStackSupervisor.startActivityLocked(srec.app.thread, destIntent,
                             null, aInfo, null, null, parent.appToken, null,
                             0, -1, parent.launchedFromUid, parent.launchedFromPackage,
-                            -1, parent.launchedFromUid, 0, null, true, null, null, null);
+                            -1, parent.launchedFromUid, 0, null, false, true, null, null, null);
                     foundParentInTask = res == ActivityManager.START_SUCCESS;
                 } catch (RemoteException e) {
                     foundParentInTask = false;
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index c12aff6..05c58d7 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -911,7 +911,8 @@
                 null /* voiceSession */, null /* voiceInteractor */, null /* resultTo */,
                 null /* resultWho */, 0 /* requestCode */, 0 /* callingPid */, 0 /* callingUid */,
                 null /* callingPackage */, 0 /* realCallingPid */, 0 /* realCallingUid */,
-                0 /* startFlags */, null /* options */, false /* componentSpecified */,
+                0 /* startFlags */, null /* options */, false /* ignoreTargetSecurity */,
+                false /* componentSpecified */,
                 null /* outActivity */, null /* container */,  null /* inTask */);
         if (inResumeTopActivity) {
             // If we are in resume section already, home activity will be initialized, but not
@@ -926,7 +927,8 @@
             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
             IBinder resultTo, String resultWho, int requestCode, int startFlags,
             ProfilerInfo profilerInfo, WaitResult outResult, Configuration config,
-            Bundle options, int userId, IActivityContainer iContainer, TaskRecord inTask) {
+            Bundle options, boolean ignoreTargetSecurity, int userId,
+            IActivityContainer iContainer, TaskRecord inTask) {
         // Refuse possible leaked file descriptors
         if (intent != null && intent.hasFileDescriptors()) {
             throw new IllegalArgumentException("File descriptors passed in Intent");
@@ -1043,7 +1045,7 @@
             int res = startActivityLocked(caller, intent, resolvedType, aInfo,
                     voiceSession, voiceInteractor, resultTo, resultWho,
                     requestCode, callingPid, callingUid, callingPackage,
-                    realCallingPid, realCallingUid, startFlags, options,
+                    realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity,
                     componentSpecified, null, container, inTask);
 
             Binder.restoreCallingIdentity(origId);
@@ -1159,7 +1161,7 @@
                     int res = startActivityLocked(caller, intent, resolvedTypes[i],
                             aInfo, null, null, resultTo, null, -1, callingPid, callingUid,
                             callingPackage, callingPid, callingUid,
-                            0, theseOptions, componentSpecified, outActivity, null, null);
+                            0, theseOptions, false, componentSpecified, outActivity, null, null);
                     if (res < 0) {
                         return res;
                     }
@@ -1400,8 +1402,8 @@
             IBinder resultTo, String resultWho, int requestCode,
             int callingPid, int callingUid, String callingPackage,
             int realCallingPid, int realCallingUid, int startFlags, Bundle options,
-            boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container,
-            TaskRecord inTask) {
+            boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
+            ActivityContainer container, TaskRecord inTask) {
         int err = ActivityManager.START_SUCCESS;
 
         ProcessRecord callerApp = null;
@@ -1546,7 +1548,7 @@
 
         if (startAnyPerm != PERMISSION_GRANTED) {
             final int componentRestriction = getComponentRestrictionForCallingPackage(
-                    aInfo, callingPackage, callingPid, callingUid);
+                    aInfo, callingPackage, callingPid, callingUid, ignoreTargetSecurity);
             final int actionRestriction = getActionRestrictionForCallingPackage(
                     intent.getAction(), callingPackage, callingPid, callingUid);
 
@@ -1675,13 +1677,13 @@
     }
 
     private int getComponentRestrictionForCallingPackage(ActivityInfo activityInfo,
-            String callingPackage, int callingPid, int callingUid) {
+            String callingPackage, int callingPid, int callingUid, boolean ignoreTargetSecurity) {
         if (activityInfo.permission == null) {
             return ACTIVITY_RESTRICTION_NONE;
         }
 
-        if (mService.checkComponentPermission(activityInfo.permission, callingPid, callingUid,
-                activityInfo.applicationInfo.uid, activityInfo.exported)
+        if (!ignoreTargetSecurity && mService.checkComponentPermission(activityInfo.permission,
+                callingPid, callingUid, activityInfo.applicationInfo.uid, activityInfo.exported)
                 == PackageManager.PERMISSION_DENIED) {
             return ACTIVITY_RESTRICTION_PERMISSION;
         }
@@ -1693,7 +1695,9 @@
 
         if (mService.mAppOpsService.noteOperation(opCode, callingUid,
                 callingPackage) != AppOpsManager.MODE_ALLOWED) {
-            return ACTIVITY_RESTRICTION_APPOP;
+            if (!ignoreTargetSecurity) {
+                return ACTIVITY_RESTRICTION_APPOP;
+            }
         }
 
         return ACTIVITY_RESTRICTION_NONE;
@@ -4296,7 +4300,7 @@
 
             intent.addFlags(FORCE_NEW_TASK_FLAGS);
             return startActivityMayWait(null, -1, null, intent, mimeType, null, null, null, null,
-                    0, 0, null, null, null, null, userId, this, null);
+                    0, 0, null, null, null, null, false, userId, this, null);
         }
 
         @Override
diff --git a/services/core/java/com/android/server/am/BroadcastQueue.java b/services/core/java/com/android/server/am/BroadcastQueue.java
index 91d97ef..a956c56 100644
--- a/services/core/java/com/android/server/am/BroadcastQueue.java
+++ b/services/core/java/com/android/server/am/BroadcastQueue.java
@@ -321,14 +321,12 @@
     }
 
     public void skipCurrentReceiverLocked(ProcessRecord app) {
-        BroadcastRecord r = app.curReceiver;
-        if (r != null && r.queue == this) {
-            // The current broadcast is waiting for this app's receiver
-            // to be finished.  Looks like that's not going to happen, so
-            // let the broadcast continue.
-            logBroadcastReceiverDiscardLocked(r);
-            finishReceiverLocked(r, r.resultCode, r.resultData,
-                    r.resultExtras, r.resultAbort, false);
+        BroadcastRecord r = null;
+        if (mOrderedBroadcasts.size() > 0) {
+            BroadcastRecord br = mOrderedBroadcasts.get(0);
+            if (br.curApp == app) {
+                r = br;
+            }
         }
         if (r == null && mPendingBroadcast != null && mPendingBroadcast.curApp == app) {
             if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST,
diff --git a/services/core/java/com/android/server/am/RecentTasks.java b/services/core/java/com/android/server/am/RecentTasks.java
index 9f11def..6ee1650 100644
--- a/services/core/java/com/android/server/am/RecentTasks.java
+++ b/services/core/java/com/android/server/am/RecentTasks.java
@@ -446,13 +446,23 @@
                 if (i > MAX_RECENT_BITMAPS) {
                     tr.freeLastThumbnail();
                 }
-                if (task.realActivity == null || tr.realActivity == null ||
-                        !task.realActivity.equals(tr.realActivity)) {
+                final boolean sameAffinity =
+                        task.affinity != null && task.affinity.equals(tr.affinity);
+                final boolean trIsDocument = tr.intent != null && tr.intent.isDocument();
+                final boolean bothDocuments = document && trIsDocument;
+                if (!sameAffinity && !bothDocuments) {
+                    // Not the same affinity and not documents. Move along...
                     continue;
                 }
-                final boolean trIsDocument = tr.intent != null && tr.intent.isDocument();
-                if (document && trIsDocument) {
-                    // These are the same document activity (not necessarily the same doc).
+
+                if (bothDocuments) {
+                    // Do these documents belong to the same activity?
+                    final boolean sameActivity = task.realActivity != null
+                            && tr.realActivity != null
+                            && task.realActivity.equals(tr.realActivity);
+                    if (!sameActivity) {
+                        continue;
+                    }
                     if (maxRecents > 0) {
                         --maxRecents;
                         continue;
diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java
index eef3d63..1223a00 100644
--- a/services/core/java/com/android/server/audio/AudioService.java
+++ b/services/core/java/com/android/server/audio/AudioService.java
@@ -5126,6 +5126,11 @@
             if (UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID) {
                 continue;
             }
+            // Skip packages that have permission to interact across users
+            if (pm.checkPermission(Manifest.permission.INTERACT_ACROSS_USERS, pkg.packageName)
+                    == PackageManager.PERMISSION_GRANTED) {
+                continue;
+            }
             if (homeActivityName != null
                     && pkg.packageName.equals(homeActivityName.getPackageName())
                     && pkg.applicationInfo.isSystemApp()) {
diff --git a/services/core/java/com/android/server/fingerprint/FingerprintService.java b/services/core/java/com/android/server/fingerprint/FingerprintService.java
index a71dfcd..c705fbf 100644
--- a/services/core/java/com/android/server/fingerprint/FingerprintService.java
+++ b/services/core/java/com/android/server/fingerprint/FingerprintService.java
@@ -74,7 +74,6 @@
     private static final int MSG_USER_SWITCHING = 10;
     private static final int ENROLLMENT_TIMEOUT_MS = 60 * 1000; // 1 minute
 
-    private boolean mIsKeyguard; // true if the authentication client is keyguard
     private ClientMonitor mAuthClient = null;
     private ClientMonitor mEnrollClient = null;
     private ClientMonitor mRemoveClient = null;
@@ -86,6 +85,7 @@
     private static final int FINGERPRINT_ACQUIRED_GOOD = 0;
 
     Handler mHandler = new Handler() {
+        @Override
         public void handleMessage(android.os.Message msg) {
             switch (msg.what) {
                 case MSG_USER_SWITCHING:
@@ -123,20 +123,29 @@
     public void binderDied() {
         Slog.v(TAG, "fingerprintd died");
         mDaemon = null;
+        dispatchError(mHalDeviceId, FingerprintManager.FINGERPRINT_ERROR_HW_UNAVAILABLE);
     }
 
     public IFingerprintDaemon getFingerprintDaemon() {
         if (mDaemon == null) {
             mDaemon = IFingerprintDaemon.Stub.asInterface(ServiceManager.getService(FINGERPRINTD));
-            if (mDaemon == null) {
-                Slog.w(TAG, "fingerprind service not available");
-            } else {
+            if (mDaemon != null) {
                 try {
                     mDaemon.asBinder().linkToDeath(this, 0);
-                }   catch (RemoteException e) {
-                    Slog.w(TAG, "caught remote exception in linkToDeath: ", e);
-                    mDaemon = null; // try again!
+                    mDaemon.init(mDaemonCallback);
+                    mHalDeviceId = mDaemon.openHal();
+                    if (mHalDeviceId != 0) {
+                        updateActiveGroup(ActivityManager.getCurrentUser());
+                    } else {
+                        Slog.w(TAG, "Failed to open Fingerprint HAL!");
+                        mDaemon = null;
+                    }
+                } catch (RemoteException e) {
+                    Slog.e(TAG, "Failed to open fingeprintd HAL", e);
+                    mDaemon = null; // try again later!
                 }
+            } else {
+                Slog.w(TAG, "fingerprint service not available");
             }
         }
         return mDaemon;
@@ -155,7 +164,6 @@
     protected void dispatchRemoved(long deviceId, int fingerId, int groupId) {
         final ClientMonitor client = mRemoveClient;
         if (fingerId != 0) {
-            ContentResolver res = mContext.getContentResolver();
             removeTemplateForUser(mRemoveClient, fingerId);
         }
         if (client != null && client.sendRemoved(fingerId, groupId)) {
@@ -274,7 +282,7 @@
             Slog.w(TAG, "enroll: no fingeprintd!");
             return;
         }
-        stopPendingOperations();
+        stopPendingOperations(true);
         mEnrollClient = new ClientMonitor(token, receiver, groupId, restricted);
         final int timeout = (int) (ENROLLMENT_TIMEOUT_MS / MS_PER_SEC);
         try {
@@ -315,17 +323,23 @@
         return 0;
     }
 
-    private void stopPendingOperations() {
+    private void stopPendingOperations(boolean initiatedByClient) {
         if (mEnrollClient != null) {
-            stopEnrollment(mEnrollClient.token, true);
+            stopEnrollment(mEnrollClient.token, initiatedByClient);
         }
         if (mAuthClient != null) {
-            stopAuthentication(mAuthClient.token, true);
+            stopAuthentication(mAuthClient.token, initiatedByClient);
         }
         // mRemoveClient is allowed to continue
     }
 
-    void stopEnrollment(IBinder token, boolean notify) {
+    /**
+     * Stop enrollment in progress and inform client if they initiated it.
+     *
+     * @param token token for client
+     * @param initiatedByClient if this call is the result of client action (e.g. calling cancel)
+     */
+    void stopEnrollment(IBinder token, boolean initiatedByClient) {
         IFingerprintDaemon daemon = getFingerprintDaemon();
         if (daemon == null) {
             Slog.w(TAG, "stopEnrollment: no fingeprintd!");
@@ -333,15 +347,15 @@
         }
         final ClientMonitor client = mEnrollClient;
         if (client == null || client.token != token) return;
-        try {
-            int result = daemon.cancelEnrollment();
-            if (result != 0) {
-                Slog.w(TAG, "startEnrollCancel failed, result = " + result);
+        if (initiatedByClient) {
+            try {
+                int result = daemon.cancelEnrollment();
+                if (result != 0) {
+                    Slog.w(TAG, "startEnrollCancel failed, result = " + result);
+                }
+            } catch (RemoteException e) {
+                Slog.e(TAG, "stopEnrollment failed", e);
             }
-        } catch (RemoteException e) {
-            Slog.e(TAG, "stopEnrollment failed", e);
-        }
-        if (notify) {
             client.sendError(FingerprintManager.FINGERPRINT_ERROR_CANCELED);
         }
         removeClient(mEnrollClient);
@@ -354,7 +368,7 @@
             Slog.w(TAG, "startAuthentication: no fingeprintd!");
             return;
         }
-        stopPendingOperations();
+        stopPendingOperations(true);
         mAuthClient = new ClientMonitor(token, receiver, groupId, restricted);
         if (inLockoutMode()) {
             Slog.v(TAG, "In lockout mode; disallowing authentication");
@@ -374,7 +388,13 @@
         }
     }
 
-    void stopAuthentication(IBinder token, boolean notify) {
+    /**
+     * Stop authentication in progress and inform client if they initiated it.
+     *
+     * @param token token for client
+     * @param initiatedByClient if this call is the result of client action (e.g. calling cancel)
+     */
+    void stopAuthentication(IBinder token, boolean initiatedByClient) {
         IFingerprintDaemon daemon = getFingerprintDaemon();
         if (daemon == null) {
             Slog.w(TAG, "stopAuthentication: no fingeprintd!");
@@ -382,15 +402,15 @@
         }
         final ClientMonitor client = mAuthClient;
         if (client == null || client.token != token) return;
-        try {
-            int result = daemon.cancelAuthentication();
-            if (result != 0) {
-                Slog.w(TAG, "stopAuthentication failed, result=" + result);
+        if (initiatedByClient) {
+            try {
+                int result = daemon.cancelAuthentication();
+                if (result != 0) {
+                    Slog.w(TAG, "stopAuthentication failed, result=" + result);
+                }
+            } catch (RemoteException e) {
+                Slog.e(TAG, "stopAuthentication failed", e);
             }
-        } catch (RemoteException e) {
-            Slog.e(TAG, "stopAuthentication failed", e);
-        }
-        if (notify) {
             client.sendError(FingerprintManager.FINGERPRINT_ERROR_CANCELED);
         }
         removeClient(mAuthClient);
@@ -486,12 +506,14 @@
             receiver = null;
         }
 
+        @Override
         public void binderDied() {
             token = null;
             removeClient(this);
             receiver = null;
         }
 
+        @Override
         protected void finalize() throws Throwable {
             try {
                 if (token != null) {
@@ -562,12 +584,6 @@
                 result |= true; // we have a valid fingerprint
                 mLockoutReset.run();
             }
-            // For fingerprint devices that support touch-to-wake, this will ensure the device
-            // wakes up and turns the screen on when fingerprint is authenticated.
-            if (mIsKeyguard && authenticated) {
-                mPowerManager.wakeUp(SystemClock.uptimeMillis(),
-                        "android.server.fingerprint:AUTH");
-            }
             return result;
         }
 
@@ -712,7 +728,6 @@
             mHandler.post(new Runnable() {
                 @Override
                 public void run() {
-                    mIsKeyguard = KEYGUARD_PACKAGE.equals(opPackageName);
                     startAuthentication(token, opId, groupId, receiver, flags, restricted);
                 }
             });
@@ -806,15 +821,6 @@
     public void onStart() {
         publishBinderService(Context.FINGERPRINT_SERVICE, new FingerprintServiceWrapper());
         IFingerprintDaemon daemon = getFingerprintDaemon();
-        if (daemon != null) {
-            try {
-                daemon.init(mDaemonCallback);
-                mHalDeviceId = daemon.openHal();
-            	updateActiveGroup(ActivityManager.getCurrentUser());
-            } catch (RemoteException e) {
-                Slog.e(TAG, "Failed to open fingeprintd HAL", e);
-            }
-        }
         if (DEBUG) Slog.v(TAG, "Fingerprint HAL id: " + mHalDeviceId);
         listenForUserSwitches();
     }
diff --git a/services/core/java/com/android/server/media/MediaSessionRecord.java b/services/core/java/com/android/server/media/MediaSessionRecord.java
index 569a0fc..f92f631 100644
--- a/services/core/java/com/android/server/media/MediaSessionRecord.java
+++ b/services/core/java/com/android/server/media/MediaSessionRecord.java
@@ -241,19 +241,10 @@
             flags &= ~AudioManager.FLAG_PLAY_SOUND;
         }
         if (mVolumeType == PlaybackInfo.PLAYBACK_TYPE_LOCAL) {
-            int stream = AudioAttributes.toLegacyStreamType(mAudioAttrs);
             // Adjust the volume with a handler not to be blocked by other system service.
-            if (useSuggested) {
-                if (AudioSystem.isStreamActive(stream, 0)) {
-                    postAdjustSuggestedStreamVolume(stream, direction, flags, packageName, uid);
-                } else {
-                    flags |= previousFlagPlaySound;
-                    postAdjustSuggestedStreamVolume(AudioManager.USE_DEFAULT_STREAM_TYPE, direction,
-                            flags, packageName, uid);
-                }
-            } else {
-                postAdjustStreamVolume(stream, direction, flags, packageName, uid);
-            }
+            int stream = AudioAttributes.toLegacyStreamType(mAudioAttrs);
+            postAdjustLocalVolume(stream, direction, flags, packageName, uid, useSuggested,
+                    previousFlagPlaySound);
         } else {
             if (mVolumeControlType == VolumeProvider.VOLUME_CONTROL_FIXED) {
                 // Nothing to do, the volume cannot be changed
@@ -459,24 +450,25 @@
         return mPackageName + "/" + mTag;
     }
 
-    private void postAdjustSuggestedStreamVolume(final int streamType, final int direction,
-            final int flags, final String callingPackage, final int uid) {
+    private void postAdjustLocalVolume(final int stream, final int direction, final int flags,
+            final String packageName, final int uid, final boolean useSuggested,
+            final int previousFlagPlaySound) {
         mHandler.post(new Runnable() {
             @Override
             public void run() {
-                mAudioManagerInternal.adjustSuggestedStreamVolumeForUid(streamType, direction,
-                        flags, callingPackage, uid);
-            }
-        });
-    }
-
-    private void postAdjustStreamVolume(final int streamType, final int direction, final int flags,
-            final String callingPackage, final int uid) {
-        mHandler.post(new Runnable() {
-            @Override
-            public void run() {
-                mAudioManagerInternal.adjustStreamVolumeForUid(streamType, direction, flags,
-                        callingPackage, uid);
+                if (useSuggested) {
+                    if (AudioSystem.isStreamActive(stream, 0)) {
+                        mAudioManagerInternal.adjustSuggestedStreamVolumeForUid(stream, direction,
+                                flags, packageName, uid);
+                    } else {
+                        mAudioManagerInternal.adjustSuggestedStreamVolumeForUid(
+                                AudioManager.USE_DEFAULT_STREAM_TYPE, direction,
+                                flags | previousFlagPlaySound, packageName, uid);
+                    }
+                } else {
+                    mAudioManagerInternal.adjustStreamVolumeForUid(stream, direction, flags,
+                            packageName, uid);
+                }
             }
         });
     }
@@ -1067,23 +1059,22 @@
 
         @Override
         public ParcelableVolumeInfo getVolumeAttributes() {
+            int volumeType;
+            AudioAttributes attributes;
             synchronized (mLock) {
-                int type;
-                int max;
-                int current;
                 if (mVolumeType == PlaybackInfo.PLAYBACK_TYPE_REMOTE) {
-                    type = mVolumeControlType;
-                    max = mMaxVolume;
-                    current = mOptimisticVolume != -1 ? mOptimisticVolume
-                            : mCurrentVolume;
-                } else {
-                    int stream = AudioAttributes.toLegacyStreamType(mAudioAttrs);
-                    type = VolumeProvider.VOLUME_CONTROL_ABSOLUTE;
-                    max = mAudioManager.getStreamMaxVolume(stream);
-                    current = mAudioManager.getStreamVolume(stream);
+                    int current = mOptimisticVolume != -1 ? mOptimisticVolume : mCurrentVolume;
+                    return new ParcelableVolumeInfo(
+                            mVolumeType, mAudioAttrs, mVolumeControlType, mMaxVolume, current);
                 }
-                return new ParcelableVolumeInfo(mVolumeType, mAudioAttrs, type, max, current);
+                volumeType = mVolumeType;
+                attributes = mAudioAttrs;
             }
+            int stream = AudioAttributes.toLegacyStreamType(attributes);
+            int max = mAudioManager.getStreamMaxVolume(stream);
+            int current = mAudioManager.getStreamVolume(stream);
+            return new ParcelableVolumeInfo(
+                    volumeType, attributes, VolumeProvider.VOLUME_CONTROL_ABSOLUTE, max, current);
         }
 
         @Override
diff --git a/services/core/java/com/android/server/media/MediaSessionService.java b/services/core/java/com/android/server/media/MediaSessionService.java
index 8086461..7028fa6 100644
--- a/services/core/java/com/android/server/media/MediaSessionService.java
+++ b/services/core/java/com/android/server/media/MediaSessionService.java
@@ -988,7 +988,7 @@
                         keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED,
                                 WAKELOCK_RELEASE_ON_FINISHED);
                     }
-                    getContext().sendOrderedBroadcastAsUser(keyIntent, UserHandle.ALL,
+                    getContext().sendOrderedBroadcastAsUser(keyIntent, UserHandle.CURRENT,
                             null, mKeyEventDone, mHandler, Activity.RESULT_OK, null, null);
                 }
             }
diff --git a/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java
index e3c6037..f04790e 100644
--- a/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java
@@ -29,7 +29,6 @@
 import android.content.pm.ResolveInfo;
 import android.net.Uri;
 import android.os.Build;
-import android.os.Debug;
 import android.os.UserHandle;
 import android.provider.CalendarContract;
 import android.provider.ContactsContract;
@@ -73,6 +72,7 @@
     static {
         CONTACTS_PERMISSIONS.add(Manifest.permission.READ_CONTACTS);
         CONTACTS_PERMISSIONS.add(Manifest.permission.WRITE_CONTACTS);
+        CONTACTS_PERMISSIONS.add(Manifest.permission.GET_ACCOUNTS);
     }
 
     private static final Set<String> LOCATION_PERMISSIONS = new ArraySet<>();
@@ -118,16 +118,6 @@
         STORAGE_PERMISSIONS.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
     }
 
-    private static final Set<String> ACCOUNTS_PERMISSIONS = new ArraySet<>();
-    static {
-        //ACCOUNTS_PERMISSIONS.add(Manifest.permission.GET_ACCOUNTS);
-    }
-
-    private static final Set<String> SETTINGS_PERMISSIONS = new ArraySet<>();
-    static {
-        SETTINGS_PERMISSIONS.add(Manifest.permission.WRITE_SETTINGS);
-    }
-
     private final PackageManagerService mService;
 
     private PackagesProvider mImePackagesProvider;
@@ -161,7 +151,7 @@
         mDialerAppPackagesProvider = provider;
     }
 
-    public void setSyncAdapterPackagesProviderrLPw(SyncAdapterPackagesProvider provider) {
+    public void setSyncAdapterPackagesProviderLPw(SyncAdapterPackagesProvider provider) {
         mSyncAdapterPackagesProvider = provider;
     }
 
@@ -256,7 +246,7 @@
 
             // SetupWizard
             Intent setupIntent = new Intent(Intent.ACTION_MAIN);
-            setupIntent.addCategory(Intent.CATEGORY_HOME);
+            setupIntent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
             PackageParser.Package setupPackage = getDefaultSystemHandlerActivityPackageLPr(
                     setupIntent, userId);
             if (setupPackage != null
@@ -358,7 +348,6 @@
                     && doesPackageSupportRuntimePermissions(calendarPackage)) {
                 grantRuntimePermissionsLPw(calendarPackage, CALENDAR_PERMISSIONS, userId);
                 grantRuntimePermissionsLPw(calendarPackage, CONTACTS_PERMISSIONS, userId);
-                grantRuntimePermissionsLPw(calendarPackage, ACCOUNTS_PERMISSIONS, userId);
             }
 
             // Calendar provider
@@ -368,14 +357,12 @@
                 grantRuntimePermissionsLPw(calendarProviderPackage, CONTACTS_PERMISSIONS, userId);
                 grantRuntimePermissionsLPw(calendarProviderPackage, CALENDAR_PERMISSIONS,
                         true, userId);
-                grantRuntimePermissionsLPw(calendarProviderPackage, ACCOUNTS_PERMISSIONS, userId);
                 grantRuntimePermissionsLPw(calendarProviderPackage, STORAGE_PERMISSIONS, userId);
             }
 
             // Calendar provider sync adapters
             List<PackageParser.Package> calendarSyncAdapters = getHeadlessSyncAdapterPackagesLPr(
-                    calendarSyncAdapterPackages,
-                            userId);
+                    calendarSyncAdapterPackages, userId);
             final int calendarSyncAdapterCount = calendarSyncAdapters.size();
             for (int i = 0; i < calendarSyncAdapterCount; i++) {
                 PackageParser.Package calendarSyncAdapter = calendarSyncAdapters.get(i);
@@ -393,13 +380,11 @@
                     && doesPackageSupportRuntimePermissions(contactsPackage)) {
                 grantRuntimePermissionsLPw(contactsPackage, CONTACTS_PERMISSIONS, userId);
                 grantRuntimePermissionsLPw(contactsPackage, PHONE_PERMISSIONS, userId);
-                grantRuntimePermissionsLPw(contactsPackage, ACCOUNTS_PERMISSIONS, userId);
             }
 
             // Contacts provider sync adapters
             List<PackageParser.Package> contactsSyncAdapters = getHeadlessSyncAdapterPackagesLPr(
-                    contactsSyncAdapterPackages,
-                            userId);
+                    contactsSyncAdapterPackages, userId);
             final int contactsSyncAdapterCount = contactsSyncAdapters.size();
             for (int i = 0; i < contactsSyncAdapterCount; i++) {
                 PackageParser.Package contactsSyncAdapter = contactsSyncAdapters.get(i);
@@ -416,7 +401,6 @@
                         true, userId);
                 grantRuntimePermissionsLPw(contactsProviderPackage, PHONE_PERMISSIONS,
                         true, userId);
-                grantRuntimePermissionsLPw(contactsProviderPackage, ACCOUNTS_PERMISSIONS, userId);
                 grantRuntimePermissionsLPw(contactsProviderPackage, STORAGE_PERMISSIONS, userId);
             }
 
@@ -427,7 +411,7 @@
                     getDefaultSystemHandlerActivityPackageLPr(deviceProvisionIntent, userId);
             if (deviceProvisionPackage != null
                     && doesPackageSupportRuntimePermissions(deviceProvisionPackage)) {
-                grantRuntimePermissionsLPw(deviceProvisionPackage, ACCOUNTS_PERMISSIONS, userId);
+                grantRuntimePermissionsLPw(deviceProvisionPackage, CONTACTS_PERMISSIONS, userId);
             }
 
             // Maps
@@ -575,9 +559,9 @@
         }
         PackageParser.Package smsPackage = getPackageLPr(packageName);
         if (smsPackage != null && doesPackageSupportRuntimePermissions(smsPackage)) {
-            grantRuntimePermissionsLPw(smsPackage, PHONE_PERMISSIONS, userId);
-            grantRuntimePermissionsLPw(smsPackage, CONTACTS_PERMISSIONS, userId);
-            grantRuntimePermissionsLPw(smsPackage, SMS_PERMISSIONS, userId);
+            grantRuntimePermissionsLPw(smsPackage, PHONE_PERMISSIONS, false, true, userId);
+            grantRuntimePermissionsLPw(smsPackage, CONTACTS_PERMISSIONS, false, true, userId);
+            grantRuntimePermissionsLPw(smsPackage, SMS_PERMISSIONS, false, true, userId);
         }
     }
 
@@ -589,10 +573,10 @@
         PackageParser.Package dialerPackage = getPackageLPr(packageName);
         if (dialerPackage != null
                 && doesPackageSupportRuntimePermissions(dialerPackage)) {
-            grantRuntimePermissionsLPw(dialerPackage, PHONE_PERMISSIONS, userId);
-            grantRuntimePermissionsLPw(dialerPackage, CONTACTS_PERMISSIONS, userId);
-            grantRuntimePermissionsLPw(dialerPackage, SMS_PERMISSIONS, userId);
-            grantRuntimePermissionsLPw(dialerPackage, MICROPHONE_PERMISSIONS, userId);
+            grantRuntimePermissionsLPw(dialerPackage, PHONE_PERMISSIONS, false, true, userId);
+            grantRuntimePermissionsLPw(dialerPackage, CONTACTS_PERMISSIONS, false, true, userId);
+            grantRuntimePermissionsLPw(dialerPackage, SMS_PERMISSIONS, false, true, userId);
+            grantRuntimePermissionsLPw(dialerPackage, MICROPHONE_PERMISSIONS, false, true, userId);
         }
     }
 
@@ -619,7 +603,7 @@
         PackageParser.Package browserPackage = getSystemPackageLPr(packageName);
         if (browserPackage != null
                 && doesPackageSupportRuntimePermissions(browserPackage)) {
-            grantRuntimePermissionsLPw(browserPackage, LOCATION_PERMISSIONS, userId);
+            grantRuntimePermissionsLPw(browserPackage, LOCATION_PERMISSIONS, false, false, userId);
         }
     }
 
@@ -628,10 +612,12 @@
         List<ResolveInfo> handlers = mService.mActivities.queryIntent(intent,
                 intent.resolveType(mService.mContext.getContentResolver()),
                 PackageManager.GET_DISABLED_COMPONENTS, userId);
+        if (handlers == null) {
+            return null;
+        }
         final int handlerCount = handlers.size();
         for (int i = 0; i < handlerCount; i++) {
             ResolveInfo handler = handlers.get(i);
-            // TODO: This is a temporary hack to figure out the setup app.
             PackageParser.Package handlerPackage = getSystemPackageLPr(
                     handler.activityInfo.packageName);
             if (handlerPackage != null) {
@@ -690,11 +676,16 @@
 
     private void grantRuntimePermissionsLPw(PackageParser.Package pkg, Set<String> permissions,
             int userId) {
-        grantRuntimePermissionsLPw(pkg, permissions, false, userId);
+        grantRuntimePermissionsLPw(pkg, permissions, false, false, userId);
     }
 
     private void grantRuntimePermissionsLPw(PackageParser.Package pkg, Set<String> permissions,
             boolean systemFixed, int userId) {
+        grantRuntimePermissionsLPw(pkg, permissions, systemFixed, false, userId);
+    }
+
+    private void grantRuntimePermissionsLPw(PackageParser.Package pkg, Set<String> permissions,
+            boolean systemFixed, boolean overrideUserChoice,  int userId) {
         List<String> requestedPermissions = pkg.requestedPermissions;
 
         if (pkg.isUpdatedSystemApp()) {
@@ -713,7 +704,17 @@
                 // If any flags are set to the permission, then it is either set in
                 // its current state by the system or device/profile owner or the user.
                 // In all these cases we do not want to clobber the current state.
-                if (flags == 0) {
+                // Unless the caller wants to override user choices. The override is
+                // to make sure we can grant the needed permission to the default
+                // sms and phone apps after the user chooses this in the UI.
+                if (flags == 0 || overrideUserChoice) {
+                    // Never clobber policy or system.
+                    final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
+                            | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
+                    if ((flags & fixedFlags) != 0) {
+                        continue;
+                    }
+
                     mService.grantRuntimePermission(pkg.packageName, permission, userId);
                     if (DEBUG) {
                         Log.i(TAG, "Granted " + permission + " to default handler "
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index 2abd924..0366fff 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -43,7 +43,6 @@
 import android.content.Intent;
 import android.content.IntentSender;
 import android.content.IntentSender.SendIntentException;
-import android.content.pm.ApplicationInfo;
 import android.content.pm.IPackageInstaller;
 import android.content.pm.IPackageInstallerCallback;
 import android.content.pm.IPackageInstallerSession;
@@ -71,7 +70,6 @@
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.os.storage.StorageManager;
-import android.os.storage.VolumeInfo;
 import android.system.ErrnoException;
 import android.system.Os;
 import android.text.TextUtils;
@@ -93,7 +91,6 @@
 import com.android.internal.util.ImageUtils;
 import com.android.internal.util.IndentingPrintWriter;
 import com.android.server.IoThread;
-import com.google.android.collect.Sets;
 
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
@@ -108,6 +105,7 @@
 import java.nio.charset.StandardCharsets;
 import java.security.SecureRandom;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 import java.util.Objects;
 import java.util.Random;
@@ -123,6 +121,7 @@
     /** XML constants used in {@link #mSessionsFile} */
     private static final String TAG_SESSIONS = "sessions";
     private static final String TAG_SESSION = "session";
+    private static final String TAG_GRANTED_RUNTIME_PERMISSION = "granted-runtime-permission";
     private static final String ATTR_SESSION_ID = "sessionId";
     private static final String ATTR_USER_ID = "userId";
     private static final String ATTR_INSTALLER_PACKAGE_NAME = "installerPackageName";
@@ -144,6 +143,7 @@
     private static final String ATTR_REFERRER_URI = "referrerUri";
     private static final String ATTR_ABI_OVERRIDE = "abiOverride";
     private static final String ATTR_VOLUME_UUID = "volumeUuid";
+    private static final String ATTR_NAME = "name";
 
     /** Automatically destroy sessions older than this */
     private static final long MAX_AGE_MILLIS = 3 * DateUtils.DAY_IN_MILLIS;
@@ -221,7 +221,7 @@
 
             reconcileStagesLocked(StorageManager.UUID_PRIVATE_INTERNAL);
 
-            final ArraySet<File> unclaimedIcons = Sets.newArraySet(
+            final ArraySet<File> unclaimedIcons = newArraySet(
                     mSessionsDir.listFiles());
 
             // Ignore stages and icons claimed by active sessions
@@ -245,7 +245,7 @@
 
     private void reconcileStagesLocked(String volumeUuid) {
         final File stagingDir = buildStagingDir(volumeUuid);
-        final ArraySet<File> unclaimedStages = Sets.newArraySet(
+        final ArraySet<File> unclaimedStages = newArraySet(
                 stagingDir.listFiles(sStageFilter));
 
         // Ignore stages claimed by active sessions
@@ -374,16 +374,15 @@
             }
         } catch (FileNotFoundException e) {
             // Missing sessions are okay, probably first boot
-        } catch (IOException e) {
-            Slog.wtf(TAG, "Failed reading install sessions", e);
-        } catch (XmlPullParserException e) {
+        } catch (IOException | XmlPullParserException e) {
             Slog.wtf(TAG, "Failed reading install sessions", e);
         } finally {
             IoUtils.closeQuietly(fis);
         }
     }
 
-    private PackageInstallerSession readSessionLocked(XmlPullParser in) throws IOException {
+    private PackageInstallerSession readSessionLocked(XmlPullParser in) throws IOException,
+            XmlPullParserException {
         final int sessionId = readIntAttribute(in, ATTR_SESSION_ID);
         final int userId = readIntAttribute(in, ATTR_USER_ID);
         final String installerPackageName = readStringAttribute(in, ATTR_INSTALLER_PACKAGE_NAME);
@@ -409,6 +408,7 @@
         params.referrerUri = readUriAttribute(in, ATTR_REFERRER_URI);
         params.abiOverride = readStringAttribute(in, ATTR_ABI_OVERRIDE);
         params.volumeUuid = readStringAttribute(in, ATTR_VOLUME_UUID);
+        params.grantedRuntimePermissions = readGrantedRuntimePermissions(in);
 
         final File appIconFile = buildAppIconFile(sessionId);
         if (appIconFile.exists()) {
@@ -501,9 +501,51 @@
             params.appIconLastModified = appIconFile.lastModified();
         }
 
+        writeGrantedRuntimePermissions(out, params.grantedRuntimePermissions);
+
         out.endTag(null, TAG_SESSION);
     }
 
+    private static void writeGrantedRuntimePermissions(XmlSerializer out,
+            String[] grantedRuntimePermissions) throws IOException {
+        if (grantedRuntimePermissions != null) {
+            for (String permission : grantedRuntimePermissions) {
+                out.startTag(null, TAG_GRANTED_RUNTIME_PERMISSION);
+                writeStringAttribute(out, ATTR_NAME, permission);
+                out.endTag(null, TAG_GRANTED_RUNTIME_PERMISSION);
+            }
+        }
+    }
+
+    private static String[] readGrantedRuntimePermissions(XmlPullParser in)
+            throws IOException, XmlPullParserException {
+        List<String> permissions = null;
+
+        final int outerDepth = in.getDepth();
+        int type;
+        while ((type = in.next()) != XmlPullParser.END_DOCUMENT
+                && (type != XmlPullParser.END_TAG || in.getDepth() > outerDepth)) {
+            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
+                continue;
+            }
+            if (TAG_GRANTED_RUNTIME_PERMISSION.equals(in.getName())) {
+                String permission = readStringAttribute(in, ATTR_NAME);
+                if (permissions == null) {
+                    permissions = new ArrayList<>();
+                }
+                permissions.add(permission);
+            }
+        }
+
+        if (permissions == null) {
+            return null;
+        }
+
+        String[] permissionsArray = new String[permissions.size()];
+        permissions.toArray(permissionsArray);
+        return permissionsArray;
+    }
+
     private File buildAppIconFile(int sessionId) {
         return new File(mSessionsDir, "app_icon." + sessionId + ".png");
     }
@@ -1049,6 +1091,15 @@
                 .build();
     }
 
+    public static <E> ArraySet<E> newArraySet(E... elements) {
+        final ArraySet<E> set = new ArraySet<E>();
+        if (elements != null) {
+            set.ensureCapacity(elements.length);
+            Collections.addAll(set, elements);
+        }
+        return set;
+    }
+
     private static class Callbacks extends Handler {
         private static final int MSG_SESSION_CREATED = 1;
         private static final int MSG_SESSION_BADGING_CHANGED = 2;
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index ef9bc8b..0b74996 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -16,7 +16,6 @@
 
 package com.android.server.pm;
 
-import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
 import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
@@ -225,6 +224,7 @@
 import com.android.server.Watchdog;
 import com.android.server.pm.PermissionsState.PermissionState;
 import com.android.server.pm.Settings.DatabaseVersion;
+import com.android.server.pm.Settings.VersionInfo;
 import com.android.server.storage.DeviceStorageMonitorInternal;
 
 import org.xmlpull.v1.XmlPullParser;
@@ -801,12 +801,9 @@
     }
 
     private static boolean hasValidDomains(ActivityIntentInfo filter) {
-        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
-                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
-        if (!hasHTTPorHTTPS) {
-            return false;
-        }
-        return true;
+        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
+                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
+                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
     }
 
     private IntentFilterVerifier mIntentFilterVerifier;
@@ -1342,8 +1339,8 @@
                             // permissions if requested before broadcasting the install.
                             if ((args.installFlags
                                     & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
-                                grantRequestedRuntimePermissions(res.pkg,
-                                        args.user.getIdentifier());
+                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
+                                        args.installGrantPermissions);
                             }
 
                             // Determine the set of users who are adding this
@@ -1658,6 +1655,11 @@
 
         @Override
         public void onVolumeForgotten(String fsUuid) {
+            if (TextUtils.isEmpty(fsUuid)) {
+                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
+                return;
+            }
+
             // Remove any apps installed on the forgotten volume
             synchronized (mPackages) {
                 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
@@ -1667,17 +1669,23 @@
                             UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
                 }
 
+                mSettings.onVolumeForgotten(fsUuid);
                 mSettings.writeLPr();
             }
         }
     };
 
-    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
+    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
+            String[] grantedPermissions) {
         if (userId >= UserHandle.USER_OWNER) {
-            grantRequestedRuntimePermissionsForUser(pkg, userId);
+            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
         } else if (userId == UserHandle.USER_ALL) {
-            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
-                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
+            final int[] userIds;
+            synchronized (mPackages) {
+                userIds = UserManagerService.getInstance().getUserIds();
+            }
+            for (int someUserId : userIds) {
+                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
             }
         }
 
@@ -1687,7 +1695,8 @@
         }
     }
 
-    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
+    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
+            String[] grantedPermissions) {
         SettingBase sb = (SettingBase) pkg.mExtras;
         if (sb == null) {
             return;
@@ -1697,7 +1706,8 @@
 
         for (String permission : pkg.requestedPermissions) {
             BasePermission bp = mSettings.mPermissions.get(permission);
-            if (bp != null && bp.isRuntime()) {
+            if (bp != null && bp.isRuntime() && (grantedPermissions == null
+                    || ArrayUtils.contains(grantedPermissions, permission))) {
                 permissionsState.grantRuntimePermission(bp, userId);
             }
         }
@@ -2236,17 +2246,16 @@
             // cases get permissions that the user didn't initially explicitly
             // allow...  it would be nice to have some better way to handle
             // this situation.
-            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
-                    != mSdkVersion;
-            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
-                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
-                    + "; regranting permissions for internal storage");
-            mSettings.mInternalSdkPlatform = mSdkVersion;
+            final VersionInfo ver = mSettings.getInternalVersion();
 
-            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
-                    | (regrantPermissions
-                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
-                            : 0));
+            int updateFlags = UPDATE_PERMISSIONS_ALL;
+            if (ver.sdkVersion != mSdkVersion) {
+                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
+                        + mSdkVersion + "; regranting permissions for internal storage");
+                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
+            }
+            updatePermissionsLPw(null, null, updateFlags);
+            ver.sdkVersion = mSdkVersion;
 
             // If this is the first boot, and it is a normal boot, then
             // we need to initialize the default preferred apps.
@@ -2258,20 +2267,22 @@
 
             // If this is first boot after an OTA, and a normal boot, then
             // we need to clear code cache directories.
-            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
+            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
             if (mIsUpgrade && !onlyCore) {
                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
-                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
+                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
+                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
+                    }
                 }
-                mSettings.mFingerprint = Build.FINGERPRINT;
+                ver.fingerprint = Build.FINGERPRINT;
             }
 
             checkDefaultBrowser();
 
             // All the changes are done during package scanning.
-            mSettings.updateInternalDatabaseVersion();
+            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
 
             // can downgrade to reader
             mSettings.writeLPr();
@@ -2964,6 +2975,10 @@
     public boolean activitySupportsIntent(ComponentName component, Intent intent,
             String resolvedType) {
         synchronized (mPackages) {
+            if (component.equals(mResolveComponentName)) {
+                // The resolver supports EVERYTHING!
+                return true;
+            }
             PackageParser.Activity a = mActivities.mActivities.get(component);
             if (a == null) {
                 return false;
@@ -3385,7 +3400,7 @@
         }
 
         mContext.enforceCallingOrSelfPermission(
-                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
+                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
                 "grantRuntimePermission");
 
         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
@@ -3469,7 +3484,7 @@
         }
 
         mContext.enforceCallingOrSelfPermission(
-                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
+                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
                 "revokeRuntimePermission");
 
         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
@@ -3520,7 +3535,7 @@
     @Override
     public void resetRuntimePermissions() {
         mContext.enforceCallingOrSelfPermission(
-                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
+                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
                 "revokeRuntimePermission");
 
         int callingUid = Binder.getCallingUid();
@@ -3530,16 +3545,19 @@
                     "resetRuntimePermissions");
         }
 
-        final int[] userIds;
-
         synchronized (mPackages) {
             updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
-            final int userCount = UserManagerService.getInstance().getUserIds().length;
-            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
-        }
-
-        for (int userId : userIds) {
-            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
+            for (int userId : UserManagerService.getInstance().getUserIds()) {
+                final int packageCount = mPackages.size();
+                for (int i = 0; i < packageCount; i++) {
+                    PackageParser.Package pkg = mPackages.valueAt(i);
+                    if (!(pkg.mExtras instanceof PackageSetting)) {
+                        continue;
+                    }
+                    PackageSetting ps = (PackageSetting) pkg.mExtras;
+                    resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
+                }
+            }
         }
     }
 
@@ -3549,9 +3567,7 @@
             return 0;
         }
 
-        mContext.enforceCallingOrSelfPermission(
-                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
-                "getPermissionFlags");
+        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
 
         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
                 "getPermissionFlags");
@@ -3584,9 +3600,7 @@
             return;
         }
 
-        mContext.enforceCallingOrSelfPermission(
-                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
-                "updatePermissionFlags");
+        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
 
         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
                 "updatePermissionFlags");
@@ -3646,9 +3660,7 @@
             return;
         }
 
-        mContext.enforceCallingOrSelfPermission(
-                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
-                "updatePermissionFlagsForAllApps");
+        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
 
         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
                 "updatePermissionFlagsForAllApps");
@@ -3678,6 +3690,17 @@
         }
     }
 
+    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
+        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
+                != PackageManager.PERMISSION_GRANTED
+            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
+                != PackageManager.PERMISSION_GRANTED) {
+            throw new SecurityException(message + " requires "
+                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
+                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
+        }
+    }
+
     @Override
     public boolean shouldShowRequestPermissionRationale(String permissionName,
             String packageName, int userId) {
@@ -3904,10 +3927,8 @@
      * were updated, return true.
      */
     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
-        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
-                DatabaseVersion.SIGNATURE_END_ENTITY))
-                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
-                        DatabaseVersion.SIGNATURE_END_ENTITY));
+        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
+        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
     }
 
     /**
@@ -3954,13 +3975,8 @@
     }
 
     private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
-        if (isExternal(scannedPkg)) {
-            return mSettings.isExternalDatabaseVersionOlderThan(
-                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
-        } else {
-            return mSettings.isInternalDatabaseVersionOlderThan(
-                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
-        }
+        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
+        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
     }
 
     private int compareSignaturesRecover(PackageSignatures existingSigs,
@@ -4420,9 +4436,7 @@
             synchronized(mPackages) {
                 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
                         intent, resolvedType, 0, sourceUserId, parent.id);
-                return xpDomainInfo != null
-                        && xpDomainInfo.bestDomainVerificationStatus !=
-                                INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
+                return xpDomainInfo != null;
             }
         }
         return false;
@@ -4579,6 +4593,11 @@
                         result.bestDomainVerificationStatus);
             }
         }
+        // Don't consider matches with status NEVER across profiles.
+        if (result != null && result.bestDomainVerificationStatus
+                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
+            return null;
+        }
         return result;
     }
 
@@ -4716,8 +4735,7 @@
                 } else {
                     // Browser/generic handling case.  If there's a default browser, go straight
                     // to that (but only if there is no other higher-priority match).
-                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
-                            UserHandle.myUserId());
+                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
                     int maxMatchPrio = 0;
                     ResolveInfo defaultBrowserMatch = null;
                     final int numCandidates = matchAllList.size();
@@ -6159,12 +6177,16 @@
                 return false;
             }
         }
-
-        synchronized (mInstallLock) {
-            final String[] instructionSets = new String[] { targetInstructionSet };
-            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
-                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
-            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
+        long callingId = Binder.clearCallingIdentity();
+        try {
+            synchronized (mInstallLock) {
+                final String[] instructionSets = new String[] { targetInstructionSet };
+                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
+                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
+                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
+            }
+        } finally {
+            Binder.restoreCallingIdentity(callingId);
         }
     }
 
@@ -7299,6 +7321,9 @@
             for (i=0; i<N; i++) {
                 PackageParser.Permission p = pkg.permissions.get(i);
 
+                // Assume by default that we did not install this permission into the system.
+                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
+
                 // Now that permission groups have a special meaning, we ignore permission
                 // groups for legacy apps to prevent unexpected behavior. In particular,
                 // permissions for one app being granted to someone just becuase they happen
@@ -7328,6 +7353,7 @@
                             bp.perm = p;
                             bp.uid = pkg.applicationInfo.uid;
                             bp.sourcePackage = p.info.packageName;
+                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
                         } else if (!currentOwnerIsSystem) {
                             String msg = "New decl " + p.owner + " of permission  "
                                     + p.info.name + " is system; overriding " + bp.sourcePackage;
@@ -7353,6 +7379,7 @@
                             bp.perm = p;
                             bp.uid = pkg.applicationInfo.uid;
                             bp.sourcePackage = p.info.packageName;
+                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
                             if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
                                 if (r == null) {
                                     r = new StringBuilder(256);
@@ -9445,7 +9472,7 @@
 
         final Message msg = mHandler.obtainMessage(INIT_COPY);
         msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
-                null, verificationParams, user, packageAbiOverride);
+                null, verificationParams, user, packageAbiOverride, null);
         mHandler.sendMessage(msg);
     }
 
@@ -9465,7 +9492,8 @@
 
         final Message msg = mHandler.obtainMessage(INIT_COPY);
         msg.obj = new InstallParams(origin, null, observer, params.installFlags,
-                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
+                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
+                params.grantedRuntimePermissions);
         mHandler.sendMessage(msg);
     }
 
@@ -9929,7 +9957,7 @@
             if (packageName != null) {
                 result |= updateIntentVerificationStatus(packageName,
                         PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
-                        UserHandle.myUserId());
+                        userId);
                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
                         packageName, userId);
             }
@@ -10345,10 +10373,13 @@
         private InstallArgs mArgs;
         private int mRet;
         final String packageAbiOverride;
+        final String[] grantedRuntimePermissions;
+
 
         InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
                 int installFlags, String installerPackageName, String volumeUuid,
-                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
+                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
+                String[] grantedPermissions) {
             super(user);
             this.origin = origin;
             this.move = move;
@@ -10358,6 +10389,7 @@
             this.volumeUuid = volumeUuid;
             this.verificationParams = verificationParams;
             this.packageAbiOverride = packageAbiOverride;
+            this.grantedRuntimePermissions = grantedPermissions;
         }
 
         @Override
@@ -10621,6 +10653,12 @@
                     final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
                             receivers, verificationState);
 
+                    // Apps installed for "all" users use the device owner to verify the app
+                    UserHandle verifierUser = getUser();
+                    if (verifierUser == UserHandle.ALL) {
+                        verifierUser = UserHandle.OWNER;
+                    }
+
                     /*
                      * If any sufficient verifiers were listed in the package
                      * manifest, attempt to ask them.
@@ -10636,8 +10674,7 @@
 
                                 final Intent sufficientIntent = new Intent(verification);
                                 sufficientIntent.setComponent(verifierComponent);
-
-                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
+                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
                             }
                         }
                     }
@@ -10652,7 +10689,7 @@
                          * target BroadcastReceivers have run.
                          */
                         verification.setComponent(requiredVerifierComponent);
-                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
+                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
                                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
                                 new BroadcastReceiver() {
                                     @Override
@@ -10782,6 +10819,7 @@
         final ManifestDigest manifestDigest;
         final UserHandle user;
         final String abiOverride;
+        final String[] installGrantPermissions;
 
         // The list of instruction sets supported by this app. This is currently
         // only used during the rmdex() phase to clean up resources. We can get rid of this
@@ -10791,7 +10829,7 @@
         InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
                 int installFlags, String installerPackageName, String volumeUuid,
                 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
-                String abiOverride) {
+                String abiOverride, String[] installGrantPermissions) {
             this.origin = origin;
             this.move = move;
             this.installFlags = installFlags;
@@ -10802,6 +10840,7 @@
             this.user = user;
             this.instructionSets = instructionSets;
             this.abiOverride = abiOverride;
+            this.installGrantPermissions = installGrantPermissions;
         }
 
         abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
@@ -10894,7 +10933,8 @@
         FileInstallArgs(InstallParams params) {
             super(params.origin, params.move, params.observer, params.installFlags,
                     params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
-                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
+                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
+                    params.grantedRuntimePermissions);
             if (isFwdLocked()) {
                 throw new IllegalArgumentException("Forward locking only supported in ASEC");
             }
@@ -10903,7 +10943,7 @@
         /** Existing install */
         FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
             super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
-                    null);
+                    null, null);
             this.codeFile = (codePath != null) ? new File(codePath) : null;
             this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
         }
@@ -11119,7 +11159,8 @@
         AsecInstallArgs(InstallParams params) {
             super(params.origin, params.move, params.observer, params.installFlags,
                     params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
-                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
+                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
+                    params.grantedRuntimePermissions);
         }
 
         /** Existing install */
@@ -11127,7 +11168,7 @@
                         boolean isExternal, boolean isForwardLocked) {
             super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
                     | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
-                    instructionSets, null);
+                    instructionSets, null, null);
             // Hackily pretend we're still looking at a full code path
             if (!fullCodePath.endsWith(RES_FILE_NAME)) {
                 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
@@ -11144,7 +11185,7 @@
         AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
             super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
                     | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
-                    instructionSets, null);
+                    instructionSets, null, null);
             this.cid = cid;
             setMountPath(PackageHelper.getSdDir(cid));
         }
@@ -11411,7 +11452,8 @@
         MoveInstallArgs(InstallParams params) {
             super(params.origin, params.move, params.observer, params.installFlags,
                     params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
-                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
+                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
+                    params.grantedRuntimePermissions);
         }
 
         int copyApk(IMediaContainerService imcs, boolean temp) {
@@ -12238,6 +12280,20 @@
             // We did an in-place move, so dex is ready to roll
             scanFlags |= SCAN_NO_DEX;
             scanFlags |= SCAN_MOVE;
+
+            synchronized (mPackages) {
+                final PackageSetting ps = mSettings.mPackages.get(pkgName);
+                if (ps == null) {
+                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
+                            "Missing settings for moved package " + pkgName);
+                }
+
+                // We moved the entire application as-is, so bring over the
+                // previously derived ABI information.
+                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
+                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
+            }
+
         } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
             // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
             scanFlags |= SCAN_NO_DEX;
@@ -12455,6 +12511,18 @@
         return installFlags;
     }
 
+    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
+        if (isExternal(pkg)) {
+            if (TextUtils.isEmpty(pkg.volumeUuid)) {
+                return mSettings.getExternalVersion();
+            } else {
+                return mSettings.findOrCreateVersion(pkg.volumeUuid);
+            }
+        } else {
+            return mSettings.getInternalVersion();
+        }
+    }
+
     private void deleteTempPackageFiles() {
         final FilenameFilter filter = new FilenameFilter() {
             public boolean accept(File dir, String name) {
@@ -14625,12 +14693,12 @@
                 pw.println("    s[hared-users]: dump shared user IDs");
                 pw.println("    m[essages]: print collected runtime messages");
                 pw.println("    v[erifiers]: print package verifier info");
-                pw.println("    version: print database version info");
-                pw.println("    write: write current settings now");
-                pw.println("    <package.name>: info about given package");
-                pw.println("    installs: details about install sessions");
                 pw.println("    d[omain-preferred-apps]: print domains preferred apps");
                 pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
+                pw.println("    version: print database version info");
+                pw.println("    write: write current settings now");
+                pw.println("    installs: details about install sessions");
+                pw.println("    <package.name>: info about given package");
                 return;
             } else if ("--checkin".equals(opt)) {
                 checkin = true;
@@ -14720,16 +14788,7 @@
                     if (dumpState.onTitlePrinted())
                         pw.println();
                     pw.println("Database versions:");
-                    pw.print("  SDK Version:");
-                    pw.print(" internal=");
-                    pw.print(mSettings.mInternalSdkPlatform);
-                    pw.print(" external=");
-                    pw.println(mSettings.mExternalSdkPlatform);
-                    pw.print("  DB Version:");
-                    pw.print(" internal=");
-                    pw.print(mSettings.mInternalDatabaseVersion);
-                    pw.print(" external=");
-                    pw.println(mSettings.mExternalDatabaseVersion);
+                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
                 }
             }
 
@@ -15076,8 +15135,9 @@
         }
         if (filters != null && filters.size() > 0) {
             for (IntentFilter filter : filters) {
-                if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
-                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
+                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
+                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
+                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
                     result.addAll(filter.getHostsList());
                 }
             }
@@ -15375,20 +15435,18 @@
             // cases get permissions that the user didn't initially explicitly
             // allow... it would be nice to have some better way to handle
             // this situation.
-            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
-            if (regrantPermissions)
-                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
-                        + mSdkVersion + "; regranting permissions for external storage");
-            mSettings.mExternalSdkPlatform = mSdkVersion;
+            final VersionInfo ver = mSettings.getExternalVersion();
 
-            // Make sure group IDs have been assigned, and any permission
-            // changes in other apps are accounted for
-            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
-                    | (regrantPermissions
-                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
-                            : 0));
+            int updateFlags = UPDATE_PERMISSIONS_ALL;
+            if (ver.sdkVersion != mSdkVersion) {
+                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
+                        + mSdkVersion + "; regranting permissions for external");
+                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
+            }
+            updatePermissionsLPw(null, null, updateFlags);
 
-            mSettings.updateExternalDatabaseVersion();
+            // Yay, everything is now upgraded
+            ver.forceCurrent();
 
             // can downgrade to reader
             // Persist settings
@@ -15480,6 +15538,7 @@
         final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
         synchronized (mInstallLock) {
         synchronized (mPackages) {
+            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
             final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
             for (PackageSetting ps : packages) {
                 final PackageParser.Package pkg;
@@ -15489,9 +15548,22 @@
                 } catch (PackageManagerException e) {
                     Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
                 }
+
+                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
+                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
+                }
             }
 
-            // TODO: regrant any permissions that changed based since original install
+            int updateFlags = UPDATE_PERMISSIONS_ALL;
+            if (ver.sdkVersion != mSdkVersion) {
+                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
+                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
+                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
+            }
+            updatePermissionsLPw(null, null, updateFlags);
+
+            // Yay, everything is now upgraded
+            ver.forceCurrent();
 
             mSettings.writeLPr();
         }
@@ -15533,12 +15605,8 @@
      * recycled.
      */
     private void reconcileUsers(String volumeUuid) {
-        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
-        if (ArrayUtils.isEmpty(files)) {
-            Slog.d(TAG, "No users found on " + volumeUuid);
-            return;
-        }
-
+        final File[] files = FileUtils
+                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
         for (File file : files) {
             if (!file.isDirectory()) continue;
 
@@ -15594,12 +15662,8 @@
      * another volume.
      */
     private void reconcileApps(String volumeUuid) {
-        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
-        if (ArrayUtils.isEmpty(files)) {
-            Slog.d(TAG, "No apps found on " + volumeUuid);
-            return;
-        }
-
+        final File[] files = FileUtils
+                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
         for (File file : files) {
             final boolean isPackage = (isApkFile(file) || file.isDirectory())
                     && !PackageInstallerService.isStageName(file.getName());
@@ -15730,7 +15794,12 @@
         }
 
         // Now that we're guarded by frozen state, kill app during move
-        killApplication(packageName, appId, "move pkg");
+        final long token = Binder.clearCallingIdentity();
+        try {
+            killApplication(packageName, appId, "move pkg");
+        } finally {
+            Binder.restoreCallingIdentity(token);
+        }
 
         final Bundle extras = new Bundle();
         extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
@@ -15864,7 +15933,7 @@
         final Message msg = mHandler.obtainMessage(INIT_COPY);
         final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
         msg.obj = new InstallParams(origin, move, installObserver, installFlags,
-                installerPackageName, volumeUuid, null, user, packageAbiOverride);
+                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
         mHandler.sendMessage(msg);
     }
 
@@ -16031,7 +16100,9 @@
 
     @Override
     public void setPermissionEnforced(String permission, boolean enforced) {
-        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
+        // TODO: Now that we no longer change GID for storage, this should to away.
+        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
+                "setPermissionEnforced");
         if (READ_EXTERNAL_STORAGE.equals(permission)) {
             synchronized (mPackages) {
                 if (mSettings.mReadExternalStorageEnforced == null
@@ -16407,7 +16478,7 @@
         @Override
         public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
             synchronized (mPackages) {
-                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
+                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
             }
         }
 
diff --git a/services/core/java/com/android/server/pm/PackageSettingBase.java b/services/core/java/com/android/server/pm/PackageSettingBase.java
index 4faf75a..bbdfe31 100644
--- a/services/core/java/com/android/server/pm/PackageSettingBase.java
+++ b/services/core/java/com/android/server/pm/PackageSettingBase.java
@@ -238,6 +238,7 @@
         installStatus = base.installStatus;
         keySetData = base.keySetData;
         verificationInfo = base.verificationInfo;
+        installerPackageName = base.installerPackageName;
     }
 
     private PackageUserState modifyUserState(int userId) {
diff --git a/services/core/java/com/android/server/pm/Settings.java b/services/core/java/com/android/server/pm/Settings.java
index 312b7b3..736b153 100644
--- a/services/core/java/com/android/server/pm/Settings.java
+++ b/services/core/java/com/android/server/pm/Settings.java
@@ -45,6 +45,7 @@
 import android.os.SystemClock;
 import android.os.UserHandle;
 import android.os.UserManager;
+import android.os.storage.StorageManager;
 import android.os.storage.VolumeInfo;
 import android.util.AtomicFile;
 import android.text.TextUtils;
@@ -56,6 +57,7 @@
 import com.android.internal.os.BackgroundThread;
 import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.FastXmlSerializer;
+import com.android.internal.util.IndentingPrintWriter;
 import com.android.internal.util.JournaledFile;
 import com.android.internal.util.Preconditions;
 import com.android.internal.util.XmlUtils;
@@ -125,7 +127,7 @@
      * Note that care should be taken to make sure all database upgrades are
      * idempotent.
      */
-    private static final int CURRENT_DATABASE_VERSION = DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
+    public static final int CURRENT_DATABASE_VERSION = DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
 
     /**
      * This class contains constants that can be referred to from upgrade code.
@@ -173,11 +175,12 @@
             "persistent-preferred-activities";
     static final String TAG_CROSS_PROFILE_INTENT_FILTERS =
             "crossProfile-intent-filters";
-    public static final String TAG_DOMAIN_VERIFICATION = "domain-verification";
-    public static final String TAG_DEFAULT_APPS= "default-apps";
-    public static final String TAG_ALL_INTENT_FILTER_VERIFICATION =
+    private static final String TAG_DOMAIN_VERIFICATION = "domain-verification";
+    private static final String TAG_DEFAULT_APPS = "default-apps";
+    private static final String TAG_ALL_INTENT_FILTER_VERIFICATION =
             "all-intent-filter-verifications";
-    public static final String TAG_DEFAULT_BROWSER= "default-browser";
+    private static final String TAG_DEFAULT_BROWSER = "default-browser";
+    private static final String TAG_VERSION = "version";
 
     private static final String ATTR_NAME = "name";
     private static final String ATTR_USER = "user";
@@ -195,9 +198,12 @@
     private static final String ATTR_INSTALLED = "inst";
     private static final String ATTR_BLOCK_UNINSTALL = "blockUninstall";
     private static final String ATTR_DOMAIN_VERIFICATON_STATE = "domainVerificationStatus";
-    private static final String ATTR_PACKAGE_NAME= "packageName";
+    private static final String ATTR_PACKAGE_NAME = "packageName";
     private static final String ATTR_FINGERPRINT = "fingerprint";
     private static final String ATTR_APP_LINK_GENERATION = "app-link-generation";
+    private static final String ATTR_VOLUME_UUID = "volumeUuid";
+    private static final String ATTR_SDK_VERSION = "sdkVersion";
+    private static final String ATTR_DATABASE_VERSION = "databaseVersion";
 
     private final Object mLock;
 
@@ -222,27 +228,43 @@
 
     private static int mFirstAvailableUid = 0;
 
-    // TODO: store SDK versions and fingerprint for each volume UUID
-
-    // These are the last platform API version we were using for
-    // the apps installed on internal and external storage.  It is
-    // used to grant newer permissions one time during a system upgrade.
-    int mInternalSdkPlatform;
-    int mExternalSdkPlatform;
+    /** Map from volume UUID to {@link VersionInfo} */
+    private ArrayMap<String, VersionInfo> mVersion = new ArrayMap<>();
 
     /**
-     * The current database version for apps on internal storage. This is
-     * used to upgrade the format of the packages.xml database not necessarily
-     * tied to an SDK version.
+     * Version details for a storage volume that may hold apps.
      */
-    int mInternalDatabaseVersion;
-    int mExternalDatabaseVersion;
+    public static class VersionInfo {
+        /**
+         * These are the last platform API version we were using for the apps
+         * installed on internal and external storage. It is used to grant newer
+         * permissions one time during a system upgrade.
+         */
+        int sdkVersion;
 
-    /**
-     * Last known value of {@link Build#FINGERPRINT}. Used to determine when an
-     * system update has occurred, meaning we need to clear code caches.
-     */
-    String mFingerprint;
+        /**
+         * The current database version for apps on internal storage. This is
+         * used to upgrade the format of the packages.xml database not
+         * necessarily tied to an SDK version.
+         */
+        int databaseVersion;
+
+        /**
+         * Last known value of {@link Build#FINGERPRINT}. Used to determine when
+         * an system update has occurred, meaning we need to clear code caches.
+         */
+        String fingerprint;
+
+        /**
+         * Force all version information to match current system values,
+         * typically after resolving any required upgrade steps.
+         */
+        public void forceCurrent() {
+            sdkVersion = Build.VERSION.SDK_INT;
+            databaseVersion = CURRENT_DATABASE_VERSION;
+            fingerprint = Build.FINGERPRINT;
+        }
+    }
 
     Boolean mReadExternalStorageEnforced;
 
@@ -1056,13 +1078,7 @@
             }
             return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
         }
-        int status = (int)(ps.getDomainVerificationStatusForUser(userId) >> 32);
-        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
-            if (ps.getIntentFilterVerificationInfo() != null) {
-                status = ps.getIntentFilterVerificationInfo().getStatus();
-            }
-        }
-        return status;
+        return (int)(ps.getDomainVerificationStatusForUser(userId) >> 32);
     }
 
     boolean updateIntentFilterVerificationStatusLPw(String packageName, final int status, int userId) {
@@ -1184,38 +1200,26 @@
                 .onDefaultRuntimePermissionsGrantedLPr(userId);
     }
 
-    /**
-     * Returns whether the current database has is older than {@code version}
-     * for apps on internal storage.
-     */
-    public boolean isInternalDatabaseVersionOlderThan(int version) {
-        return mInternalDatabaseVersion < version;
+    public VersionInfo findOrCreateVersion(String volumeUuid) {
+        VersionInfo ver = mVersion.get(volumeUuid);
+        if (ver == null) {
+            ver = new VersionInfo();
+            ver.forceCurrent();
+            mVersion.put(volumeUuid, ver);
+        }
+        return ver;
     }
 
-    /**
-     * Returns whether the current database has is older than {@code version}
-     * for apps on external storage.
-     */
-    public boolean isExternalDatabaseVersionOlderThan(int version) {
-        return mExternalDatabaseVersion < version;
+    public VersionInfo getInternalVersion() {
+        return mVersion.get(StorageManager.UUID_PRIVATE_INTERNAL);
     }
 
-    /**
-     * Updates the database version for apps on internal storage. Called after
-     * call the updates to the database format are done for apps on internal
-     * storage after the initial start-up scan.
-     */
-    public void updateInternalDatabaseVersion() {
-        mInternalDatabaseVersion = CURRENT_DATABASE_VERSION;
+    public VersionInfo getExternalVersion() {
+        return mVersion.get(StorageManager.UUID_PRIMARY_PHYSICAL);
     }
 
-    /**
-     * Updates the database version for apps on internal storage. Called after
-     * call the updates to the database format are done for apps on internal
-     * storage after the initial start-up scan.
-     */
-    public void updateExternalDatabaseVersion() {
-        mExternalDatabaseVersion = CURRENT_DATABASE_VERSION;
+    public void onVolumeForgotten(String fsUuid) {
+        mVersion.remove(fsUuid);
     }
 
     /**
@@ -2056,16 +2060,17 @@
 
             serializer.startTag(null, "packages");
 
-            serializer.startTag(null, "last-platform-version");
-            serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
-            serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
-            serializer.attribute(null, "fingerprint", mFingerprint);
-            serializer.endTag(null, "last-platform-version");
+            for (int i = 0; i < mVersion.size(); i++) {
+                final String volumeUuid = mVersion.keyAt(i);
+                final VersionInfo ver = mVersion.valueAt(i);
 
-            serializer.startTag(null, "database-version");
-            serializer.attribute(null, "internal", Integer.toString(mInternalDatabaseVersion));
-            serializer.attribute(null, "external", Integer.toString(mExternalDatabaseVersion));
-            serializer.endTag(null, "database-version");
+                serializer.startTag(null, TAG_VERSION);
+                XmlUtils.writeStringAttribute(serializer, ATTR_VOLUME_UUID, volumeUuid);
+                XmlUtils.writeIntAttribute(serializer, ATTR_SDK_VERSION, ver.sdkVersion);
+                XmlUtils.writeIntAttribute(serializer, ATTR_DATABASE_VERSION, ver.databaseVersion);
+                XmlUtils.writeStringAttribute(serializer, ATTR_FINGERPRINT, ver.fingerprint);
+                serializer.endTag(null, TAG_VERSION);
+            }
 
             if (mVerifierDeviceIdentity != null) {
                 serializer.startTag(null, "verifier");
@@ -2495,8 +2500,10 @@
                     mReadMessages.append("No settings file found\n");
                     PackageManagerService.reportSettingsProblem(Log.INFO,
                             "No settings file; creating initial state");
-                    mInternalSdkPlatform = mExternalSdkPlatform = sdkVersion;
-                    mFingerprint = Build.FINGERPRINT;
+                    // It's enough to just touch version details to create them
+                    // with default values
+                    findOrCreateVersion(StorageManager.UUID_PRIVATE_INTERNAL);
+                    findOrCreateVersion(StorageManager.UUID_PRIMARY_PHYSICAL);
                     return false;
                 }
                 str = new FileInputStream(mSettingsFilename);
@@ -2580,48 +2587,27 @@
                 } else if (tagName.equals("restored-ivi")) {
                     readRestoredIntentFilterVerifications(parser);
                 } else if (tagName.equals("last-platform-version")) {
-                    mInternalSdkPlatform = mExternalSdkPlatform = 0;
-                    try {
-                        String internal = parser.getAttributeValue(null, "internal");
-                        if (internal != null) {
-                            mInternalSdkPlatform = Integer.parseInt(internal);
-                        }
-                        String external = parser.getAttributeValue(null, "external");
-                        if (external != null) {
-                            mExternalSdkPlatform = Integer.parseInt(external);
-                        }
-                    } catch (NumberFormatException e) {
-                    }
-                    mFingerprint = parser.getAttributeValue(null, "fingerprint");
+                    // Upgrade from older XML schema
+                    final VersionInfo internal = findOrCreateVersion(
+                            StorageManager.UUID_PRIVATE_INTERNAL);
+                    final VersionInfo external = findOrCreateVersion(
+                            StorageManager.UUID_PRIMARY_PHYSICAL);
 
-                    // If the build is setup to drop runtime permissions
-                    // on update drop the files before loading them.
-                    if (PackageManagerService.CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE) {
-                        if (!Build.FINGERPRINT.equals(mFingerprint)) {
-                            if (users == null) {
-                                mRuntimePermissionsPersistence.deleteUserRuntimePermissionsFile(
-                                        UserHandle.USER_OWNER);
-                            } else {
-                                for (UserInfo user : users) {
-                                    mRuntimePermissionsPersistence.deleteUserRuntimePermissionsFile(
-                                            user.id);
-                                }
-                            }
-                        }
-                    }
+                    internal.sdkVersion = XmlUtils.readIntAttribute(parser, "internal", 0);
+                    external.sdkVersion = XmlUtils.readIntAttribute(parser, "external", 0);
+                    internal.fingerprint = external.fingerprint =
+                            XmlUtils.readStringAttribute(parser, "fingerprint");
+
                 } else if (tagName.equals("database-version")) {
-                    mInternalDatabaseVersion = mExternalDatabaseVersion = 0;
-                    try {
-                        String internalDbVersionString = parser.getAttributeValue(null, "internal");
-                        if (internalDbVersionString != null) {
-                            mInternalDatabaseVersion = Integer.parseInt(internalDbVersionString);
-                        }
-                        String externalDbVersionString = parser.getAttributeValue(null, "external");
-                        if (externalDbVersionString != null) {
-                            mExternalDatabaseVersion = Integer.parseInt(externalDbVersionString);
-                        }
-                    } catch (NumberFormatException ignored) {
-                    }
+                    // Upgrade from older XML schema
+                    final VersionInfo internal = findOrCreateVersion(
+                            StorageManager.UUID_PRIVATE_INTERNAL);
+                    final VersionInfo external = findOrCreateVersion(
+                            StorageManager.UUID_PRIMARY_PHYSICAL);
+
+                    internal.databaseVersion = XmlUtils.readIntAttribute(parser, "internal", 0);
+                    external.databaseVersion = XmlUtils.readIntAttribute(parser, "external", 0);
+
                 } else if (tagName.equals("verifier")) {
                     final String deviceIdentity = parser.getAttributeValue(null, "device");
                     try {
@@ -2635,6 +2621,14 @@
                     mReadExternalStorageEnforced = "1".equals(enforcement);
                 } else if (tagName.equals("keyset-settings")) {
                     mKeySetManagerService.readKeySetsLPw(parser, mKeySetRefs);
+                } else if (TAG_VERSION.equals(tagName)) {
+                    final String volumeUuid = XmlUtils.readStringAttribute(parser,
+                            ATTR_VOLUME_UUID);
+                    final VersionInfo ver = findOrCreateVersion(volumeUuid);
+                    ver.sdkVersion = XmlUtils.readIntAttribute(parser, ATTR_SDK_VERSION);
+                    ver.databaseVersion = XmlUtils.readIntAttribute(parser, ATTR_SDK_VERSION);
+                    ver.fingerprint = XmlUtils.readStringAttribute(parser, ATTR_FINGERPRINT);
+
                 } else {
                     Slog.w(PackageManagerService.TAG, "Unknown element under <packages>: "
                             + parser.getName());
@@ -2655,6 +2649,23 @@
             Slog.wtf(PackageManagerService.TAG, "Error reading package manager settings", e);
         }
 
+        // If the build is setup to drop runtime permissions
+        // on update drop the files before loading them.
+        if (PackageManagerService.CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE) {
+            final VersionInfo internal = getInternalVersion();
+            if (!Build.FINGERPRINT.equals(internal.fingerprint)) {
+                if (users == null) {
+                    mRuntimePermissionsPersistence.deleteUserRuntimePermissionsFile(
+                            UserHandle.USER_OWNER);
+                } else {
+                    for (UserInfo user : users) {
+                        mRuntimePermissionsPersistence.deleteUserRuntimePermissionsFile(
+                                user.id);
+                    }
+                }
+            }
+        }
+
         final int N = mPendingPackages.size();
 
         for (int i = 0; i < N; i++) {
@@ -3898,6 +3909,29 @@
         ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE, "CANT_SAVE_STATE",
     };
 
+    void dumpVersionLPr(IndentingPrintWriter pw) {
+        pw.increaseIndent();
+        for (int i= 0; i < mVersion.size(); i++) {
+            final String volumeUuid = mVersion.keyAt(i);
+            final VersionInfo ver = mVersion.valueAt(i);
+            if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
+                pw.println("Internal:");
+            } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
+                pw.println("External:");
+            } else {
+                pw.println("UUID " + volumeUuid + ":");
+            }
+            pw.increaseIndent();
+            pw.printPair("sdkVersion", ver.sdkVersion);
+            pw.printPair("databaseVersion", ver.databaseVersion);
+            pw.println();
+            pw.printPair("fingerprint", ver.fingerprint);
+            pw.println();
+            pw.decreaseIndent();
+        }
+        pw.decreaseIndent();
+    }
+
     void dumpPackageLPr(PrintWriter pw, String prefix, String checkinTag,
             ArraySet<String> permissionNames, PackageSetting ps, SimpleDateFormat sdf,
             Date date, List<UserInfo> users) {
@@ -4086,6 +4120,28 @@
         pw.print(prefix); pw.print("  pkgFlags="); printFlags(pw, ps.pkgFlags, FLAG_DUMP_SPEC);
                 pw.println();
 
+        if (ps.pkg != null && ps.pkg.permissions != null && ps.pkg.permissions.size() > 0) {
+            final ArrayList<PackageParser.Permission> perms = ps.pkg.permissions;
+            pw.print(prefix); pw.println("  declared permissions:");
+            for (int i=0; i<perms.size(); i++) {
+                PackageParser.Permission perm = perms.get(i);
+                if (permissionNames != null
+                        && !permissionNames.contains(perm.info.name)) {
+                    continue;
+                }
+                pw.print(prefix); pw.print("    "); pw.print(perm.info.name);
+                pw.print(": prot=");
+                pw.print(PermissionInfo.protectionToString(perm.info.protectionLevel));
+                if ((perm.info.flags&PermissionInfo.FLAG_COSTS_MONEY) != 0) {
+                    pw.print(", COSTS_MONEY");
+                }
+                if ((perm.info.flags&PermissionInfo.FLAG_INSTALLED) != 0) {
+                    pw.print(", INSTALLED");
+                }
+                pw.println();
+            }
+        }
+
         if (ps.sharedUser == null || permissionNames != null) {
             PermissionsState permissionsState = ps.getPermissionsState();
             dumpInstallPermissionsLPr(pw, prefix + "  ", permissionNames, permissionsState);
@@ -4121,14 +4177,14 @@
                 if (cmp != null && cmp.size() > 0) {
                     pw.print(prefix); pw.println("    disabledComponents:");
                     for (String s : cmp) {
-                        pw.print(prefix); pw.print("    "); pw.println(s);
+                        pw.print(prefix); pw.print("      "); pw.println(s);
                     }
                 }
                 cmp = ps.getEnabledComponents(user.id);
                 if (cmp != null && cmp.size() > 0) {
                     pw.print(prefix); pw.println("    enabledComponents:");
                     for (String s : cmp) {
-                        pw.print(prefix); pw.print("    "); pw.println(s);
+                        pw.print(prefix); pw.print("      "); pw.println(s);
                     }
                 }
             }
@@ -4233,11 +4289,14 @@
                     pw.print(" type="); pw.print(p.type);
                     pw.print(" prot=");
                     pw.println(PermissionInfo.protectionToString(p.protectionLevel));
-            if (p.packageSetting != null) {
-                pw.print("    packageSetting="); pw.println(p.packageSetting);
-            }
             if (p.perm != null) {
                 pw.print("    perm="); pw.println(p.perm);
+                if (p.perm.info.flags != PermissionInfo.FLAG_INSTALLED) {
+                    pw.print("    flags=0x"); pw.println(Integer.toHexString(p.perm.info.flags));
+                }
+            }
+            if (p.packageSetting != null) {
+                pw.print("    packageSetting="); pw.println(p.packageSetting);
             }
             if (READ_EXTERNAL_STORAGE.equals(p.name)) {
                 pw.print("    enforced=");
@@ -4338,24 +4397,32 @@
                     continue;
                 }
                 pw.print(prefix); pw.print("  "); pw.print(permissionState.getName());
-                pw.print(", granted="); pw.print(permissionState.isGranted());
-                    pw.print(", flags="); pw.println(permissionFlagsToString(
-                        permissionState.getFlags()));
+                pw.print(": granted="); pw.print(permissionState.isGranted());
+                    pw.println(permissionFlagsToString(", flags=",
+                            permissionState.getFlags()));
             }
         }
     }
 
-    private static String permissionFlagsToString(int flags) {
-        StringBuilder flagsString = new StringBuilder();
-        flagsString.append("[ ");
+    private static String permissionFlagsToString(String prefix, int flags) {
+        StringBuilder flagsString = null;
         while (flags != 0) {
+            if (flagsString == null) {
+                flagsString = new StringBuilder();
+                flagsString.append(prefix);
+                flagsString.append("[ ");
+            }
             final int flag = 1 << Integer.numberOfTrailingZeros(flags);
             flags &= ~flag;
             flagsString.append(PackageManager.permissionFlagToString(flag));
             flagsString.append(' ');
         }
-        flagsString.append(']');
-        return flagsString.toString();
+        if (flagsString != null) {
+            flagsString.append(']');
+            return flagsString.toString();
+        } else {
+            return "";
+        }
     }
 
     void dumpInstallPermissionsLPr(PrintWriter pw, String prefix, ArraySet<String> permissionNames,
@@ -4369,8 +4436,8 @@
                     continue;
                 }
                 pw.print(prefix); pw.print("  "); pw.print(permissionState.getName());
-                    pw.print(", granted="); pw.print(permissionState.isGranted());
-                    pw.print(", flags="); pw.println(permissionFlagsToString(
+                    pw.print(": granted="); pw.print(permissionState.isGranted());
+                    pw.println(permissionFlagsToString(", flags=",
                         permissionState.getFlags()));
             }
         }
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 978ed51..dc3e2d6 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -104,7 +104,6 @@
 import android.view.Surface;
 import android.view.View;
 import android.view.ViewConfiguration;
-import android.view.Window;
 import android.view.WindowManager;
 import android.view.WindowManagerGlobal;
 import android.view.WindowManagerInternal;
@@ -120,12 +119,13 @@
 import com.android.internal.widget.PointerLocationView;
 import com.android.server.LocalServices;
 import com.android.server.policy.keyguard.KeyguardServiceDelegate;
-import com.android.server.policy.keyguard.KeyguardServiceDelegate.ShowListener;
+import com.android.server.policy.keyguard.KeyguardServiceDelegate.DrawnListener;
 
 import java.io.File;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.PrintWriter;
+import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
 
@@ -323,10 +323,10 @@
             mHandler.sendEmptyMessage(MSG_WINDOW_MANAGER_DRAWN_COMPLETE);
         }
     };
-    final ShowListener mKeyguardDelegateCallback = new ShowListener() {
+    final DrawnListener mKeyguardDrawnCallback = new DrawnListener() {
         @Override
-        public void onShown(IBinder windowToken) {
-            if (DEBUG_WAKEUP) Slog.d(TAG, "mKeyguardDelegate.ShowListener.onShown.");
+        public void onDrawn() {
+            if (DEBUG_WAKEUP) Slog.d(TAG, "mKeyguardDelegate.ShowListener.onDrawn.");
             mHandler.sendEmptyMessage(MSG_KEYGUARD_DRAWN_COMPLETE);
         }
     };
@@ -358,6 +358,7 @@
 
     boolean mSystemReady;
     boolean mSystemBooted;
+    private boolean mDeferBindKeyguard;
     boolean mHdmiPlugged;
     HdmiControl mHdmiControl;
     IUiModeManager mUiModeManager;
@@ -1875,21 +1876,33 @@
         if (permission != null) {
             if (permission == android.Manifest.permission.SYSTEM_ALERT_WINDOW) {
                 final int callingUid = Binder.getCallingUid();
-                // check if this is a system uid first before bothering with
-                // obtaining package name
+                // system processes will be automatically allowed privilege to draw
                 if (callingUid == Process.SYSTEM_UID) {
                     return WindowManagerGlobal.ADD_OKAY;
                 }
 
+                // check if user has enabled this operation. SecurityException will be thrown if
+                // this app has not been allowed by the user
                 final int mode = mAppOpsManager.checkOp(outAppOp[0], callingUid,
                         attrs.packageName);
-                if (mode == AppOpsManager.MODE_DEFAULT) {
-                    if (mContext.checkCallingPermission(permission) !=
-                            PackageManager.PERMISSION_GRANTED) {
+                switch (mode) {
+                    case AppOpsManager.MODE_ALLOWED:
+                    case AppOpsManager.MODE_IGNORED:
+                        // although we return ADD_OKAY for MODE_IGNORED, the added window will
+                        // actually be hidden in WindowManagerService
+                        return WindowManagerGlobal.ADD_OKAY;
+                    case AppOpsManager.MODE_ERRORED:
                         return WindowManagerGlobal.ADD_PERMISSION_DENIED;
-                    }
+                    default:
+                        // in the default mode, we will make a decision here based on
+                        // checkCallingPermission()
+                        if (mContext.checkCallingPermission(permission) !=
+                                PackageManager.PERMISSION_GRANTED) {
+                            return WindowManagerGlobal.ADD_PERMISSION_DENIED;
+                        } else {
+                            return WindowManagerGlobal.ADD_OKAY;
+                        }
                 }
-                return WindowManagerGlobal.ADD_OKAY;
             }
 
             if (mContext.checkCallingOrSelfPermission(permission)
@@ -5483,11 +5496,7 @@
         }
 
         if (mKeyguardDelegate != null) {
-            mKeyguardDelegate.onStartedWakingUp(mKeyguardDelegateCallback);
-            // ... eventually calls finishKeyguardDrawn
-        } else {
-            if (DEBUG_WAKEUP) Slog.d(TAG, "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
-            finishKeyguardDrawn();
+            mKeyguardDelegate.onStartedWakingUp();
         }
     }
 
@@ -5526,9 +5535,13 @@
             if (mKeyguardDelegate != null) {
                 mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
             }
+            mWindowManagerDrawComplete = false;
         }
 
-        finishScreenTurningOn();
+        // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
+        // as well as enabling the orientation change logic/sensor.
+        mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
+                WAITING_FOR_DRAWN_TIMEOUT);
     }
 
     // Called on the DisplayManager's DisplayPowerController thread.
@@ -5557,12 +5570,15 @@
             mScreenOnFully = false;
             mWindowManagerDrawComplete = false;
             mScreenOnListener = screenOnListener;
-        }
 
-        mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
-                WAITING_FOR_DRAWN_TIMEOUT);
-        // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
-        // as well as enabling the orientation change logic/sensor.
+            if (mKeyguardDelegate != null) {
+                mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback);
+            } else {
+                if (DEBUG_WAKEUP) Slog.d(TAG,
+                        "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
+                finishKeyguardDrawn();
+            }
+        }
     }
 
     private void finishWindowsDrawn() {
@@ -5999,6 +6015,7 @@
 
         readCameraLensCoverState();
         updateUiMode();
+        boolean bindKeyguardNow;
         synchronized (mLock) {
             updateOrientationListenerLp();
             mSystemReady = true;
@@ -6008,13 +6025,36 @@
                     updateSettings();
                 }
             });
+
+            bindKeyguardNow = mDeferBindKeyguard;
+            if (bindKeyguardNow) {
+                // systemBooted ran but wasn't able to bind to the Keyguard, we'll do it now.
+                mDeferBindKeyguard = false;
+            }
+        }
+
+        if (bindKeyguardNow) {
+            mKeyguardDelegate.bindService(mContext);
+            mKeyguardDelegate.onBootCompleted();
         }
     }
 
     /** {@inheritDoc} */
     @Override
     public void systemBooted() {
-        if (mKeyguardDelegate != null) {
+        boolean bindKeyguardNow = false;
+        synchronized (mLock) {
+            // Time to bind Keyguard; take care to only bind it once, either here if ready or
+            // in systemReady if not.
+            if (mKeyguardDelegate != null) {
+                bindKeyguardNow = true;
+            } else {
+                // Because mKeyguardDelegate is null, we know that the synchronized block in
+                // systemReady didn't run yet and setting this will actually have an effect.
+                mDeferBindKeyguard = true;
+            }
+        }
+        if (bindKeyguardNow) {
             mKeyguardDelegate.bindService(mContext);
             mKeyguardDelegate.onBootCompleted();
         }
diff --git a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java
index b9f132b..0f3a199 100644
--- a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java
+++ b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java
@@ -18,9 +18,9 @@
 import android.view.WindowManager;
 import android.view.WindowManagerPolicy.OnKeyguardExitResult;
 
+import com.android.internal.policy.IKeyguardDrawnCallback;
 import com.android.internal.policy.IKeyguardExitCallback;
 import com.android.internal.policy.IKeyguardService;
-import com.android.internal.policy.IKeyguardShowCallback;
 
 /**
  * A local class that keeps a cache of keyguard state that can be restored in the event
@@ -35,9 +35,9 @@
     private final Context mContext;
     private final View mScrim; // shown if keyguard crashes
     private final KeyguardState mKeyguardState = new KeyguardState();
-    private ShowListener mShowListenerWhenConnect;
+    private DrawnListener mDrawnListenerWhenConnect;
 
-    /* package */ static final class KeyguardState {
+    private static final class KeyguardState {
         KeyguardState() {
             // Assume keyguard is showing and secure until we know for sure. This is here in
             // the event something checks before the service is actually started.
@@ -61,23 +61,23 @@
         public boolean bootCompleted;
     };
 
-    public interface ShowListener {
-        public void onShown(IBinder windowToken);
+    public interface DrawnListener {
+        void onDrawn();
     }
 
     // A delegate class to map a particular invocation with a ShowListener object.
-    private final class KeyguardShowDelegate extends IKeyguardShowCallback.Stub {
-        private ShowListener mShowListener;
+    private final class KeyguardShowDelegate extends IKeyguardDrawnCallback.Stub {
+        private DrawnListener mDrawnListener;
 
-        KeyguardShowDelegate(ShowListener showListener) {
-            mShowListener = showListener;
+        KeyguardShowDelegate(DrawnListener drawnListener) {
+            mDrawnListener = drawnListener;
         }
 
         @Override
-        public void onShown(IBinder windowToken) throws RemoteException {
+        public void onDrawn() throws RemoteException {
             if (DEBUG) Log.v(TAG, "**** SHOWN CALLED ****");
-            if (mShowListener != null) {
-                mShowListener.onShown(windowToken);
+            if (mDrawnListener != null) {
+                mDrawnListener.onDrawn();
             }
             hideScrim();
         }
@@ -119,8 +119,13 @@
             mKeyguardState.showing = false;
             mKeyguardState.showingAndNotOccluded = false;
             mKeyguardState.secure = false;
-            mKeyguardState.deviceHasKeyguard = false;
-            hideScrim();
+            synchronized (mKeyguardState) {
+                // TODO: Fix synchronisation model in this class. The other state in this class
+                // is at least self-healing but a race condition here can lead to the scrim being
+                // stuck on keyguard-less devices.
+                mKeyguardState.deviceHasKeyguard = false;
+                hideScrim();
+            }
         } else {
             if (DEBUG) Log.v(TAG, "*** Keyguard started");
         }
@@ -136,9 +141,10 @@
                 // If the system is ready, it means keyguard crashed and restarted.
                 mKeyguardService.onSystemReady();
                 // This is used to hide the scrim once keyguard displays.
-                mKeyguardService.onStartedWakingUp(new KeyguardShowDelegate(
-                        mShowListenerWhenConnect));
-                mShowListenerWhenConnect = null;
+                mKeyguardService.onStartedWakingUp();
+                mKeyguardService.onScreenTurningOn(
+                        new KeyguardShowDelegate(mDrawnListenerWhenConnect));
+                mDrawnListenerWhenConnect = null;
             }
             if (mKeyguardState.bootCompleted) {
                 mKeyguardService.onBootCompleted();
@@ -216,16 +222,23 @@
         mKeyguardState.dreaming = false;
     }
 
-    public void onStartedWakingUp(final ShowListener showListener) {
+    public void onStartedWakingUp() {
         if (mKeyguardService != null) {
-            if (DEBUG) Log.v(TAG, "onScreenTurnedOn(showListener = " + showListener + ")");
-            mKeyguardService.onStartedWakingUp(new KeyguardShowDelegate(showListener));
+            if (DEBUG) Log.v(TAG, "onStartedWakingUp()");
+            mKeyguardService.onStartedWakingUp();
+        }
+    }
+
+    public void onScreenTurningOn(final DrawnListener drawnListener) {
+        if (mKeyguardService != null) {
+            if (DEBUG) Log.v(TAG, "onScreenTurnedOn(showListener = " + drawnListener + ")");
+            mKeyguardService.onScreenTurningOn(new KeyguardShowDelegate(drawnListener));
         } else {
             // try again when we establish a connection
-            Slog.w(TAG, "onScreenTurnedOn(): no keyguard service!");
+            Slog.w(TAG, "onScreenTurningOn(): no keyguard service!");
             // This shouldn't happen, but if it does, show the scrim immediately and
             // invoke the listener's callback after the service actually connects.
-            mShowListenerWhenConnect = showListener;
+            mDrawnListenerWhenConnect = drawnListener;
             showScrim();
         }
     }
@@ -307,13 +320,15 @@
     }
 
     public void showScrim() {
-        if (!mKeyguardState.deviceHasKeyguard) return;
-        mScrim.post(new Runnable() {
-            @Override
-            public void run() {
-                mScrim.setVisibility(View.VISIBLE);
-            }
-        });
+        synchronized (mKeyguardState) {
+            if (!mKeyguardState.deviceHasKeyguard) return;
+            mScrim.post(new Runnable() {
+                @Override
+                public void run() {
+                    mScrim.setVisibility(View.VISIBLE);
+                }
+            });
+        }
     }
 
     public void hideScrim() {
diff --git a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java
index 51d59fa..5810a45 100644
--- a/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java
+++ b/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java
@@ -22,9 +22,9 @@
 import android.os.RemoteException;
 import android.util.Slog;
 
+import com.android.internal.policy.IKeyguardDrawnCallback;
 import com.android.internal.policy.IKeyguardExitCallback;
 import com.android.internal.policy.IKeyguardService;
-import com.android.internal.policy.IKeyguardShowCallback;
 import com.android.internal.policy.IKeyguardStateCallback;
 
 /**
@@ -124,9 +124,18 @@
     }
 
     @Override
-    public void onStartedWakingUp(IKeyguardShowCallback callback) {
+    public void onStartedWakingUp() {
         try {
-            mService.onStartedWakingUp(callback);
+            mService.onStartedWakingUp();
+        } catch (RemoteException e) {
+            Slog.w(TAG , "Remote Exception", e);
+        }
+    }
+
+    @Override
+    public void onScreenTurningOn(IKeyguardDrawnCallback callback) {
+        try {
+            mService.onScreenTurningOn(callback);
         } catch (RemoteException e) {
             Slog.w(TAG , "Remote Exception", e);
         }
diff --git a/services/core/java/com/android/server/tv/TvInputManagerService.java b/services/core/java/com/android/server/tv/TvInputManagerService.java
index 51df31f..a5344b4 100644
--- a/services/core/java/com/android/server/tv/TvInputManagerService.java
+++ b/services/core/java/com/android/server/tv/TvInputManagerService.java
@@ -133,7 +133,7 @@
         mTvInputHardwareManager = new TvInputHardwareManager(context, new HardwareListener());
 
         synchronized (mLock) {
-            mUserStates.put(mCurrentUserId, new UserState(mContext, mCurrentUserId));
+            getOrCreateUserStateLocked(mCurrentUserId);
         }
     }
 
@@ -222,7 +222,7 @@
             @Override
             public void onPackageRemoved(String packageName, int uid) {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(getChangingUserId());
+                    UserState userState = getOrCreateUserStateLocked(getChangingUserId());
                     if (!userState.packageSet.contains(packageName)) {
                         // Not a TV input package.
                         return;
@@ -281,7 +281,7 @@
     }
 
     private void buildTvInputListLocked(int userId, String[] updatedPackages) {
-        UserState userState = getUserStateLocked(userId);
+        UserState userState = getOrCreateUserStateLocked(userId);
         userState.packageSet.clear();
 
         if (DEBUG) Slog.d(TAG, "buildTvInputList");
@@ -368,7 +368,7 @@
     }
 
     private void buildTvContentRatingSystemListLocked(int userId) {
-        UserState userState = getUserStateLocked(userId);
+        UserState userState = getOrCreateUserStateLocked(userId);
         userState.contentRatingSystemList.clear();
 
         final PackageManager pm = mContext.getPackageManager();
@@ -402,11 +402,7 @@
             clearSessionAndServiceStatesLocked(mUserStates.get(mCurrentUserId));
 
             mCurrentUserId = userId;
-            UserState userState = mUserStates.get(userId);
-            if (userState == null) {
-                userState = new UserState(mContext, userId);
-                mUserStates.put(userId, userState);
-            }
+            getOrCreateUserStateLocked(userId);
             buildTvInputListLocked(userId, null);
             buildTvContentRatingSystemListLocked(userId);
             mWatchLogHandler.obtainMessage(WatchLogHandler.MSG_SWITCH_CONTENT_RESOLVER,
@@ -473,16 +469,17 @@
         return context.getContentResolver();
     }
 
-    private UserState getUserStateLocked(int userId) {
+    private UserState getOrCreateUserStateLocked(int userId) {
         UserState userState = mUserStates.get(userId);
         if (userState == null) {
-            throw new IllegalStateException("User state not found for user ID " + userId);
+            userState = new UserState(mContext, userId);
+            mUserStates.put(userId, userState);
         }
         return userState;
     }
 
     private ServiceState getServiceStateLocked(ComponentName component, int userId) {
-        UserState userState = getUserStateLocked(userId);
+        UserState userState = getOrCreateUserStateLocked(userId);
         ServiceState serviceState = userState.serviceStateMap.get(component);
         if (serviceState == null) {
             throw new IllegalStateException("Service state not found for " + component + " (userId="
@@ -492,7 +489,7 @@
     }
 
     private SessionState getSessionStateLocked(IBinder sessionToken, int callingUid, int userId) {
-        UserState userState = getUserStateLocked(userId);
+        UserState userState = getOrCreateUserStateLocked(userId);
         SessionState sessionState = userState.sessionStateMap.get(sessionToken);
         if (sessionState == null) {
             throw new SessionNotFoundException("Session state not found for token " + sessionToken);
@@ -530,7 +527,7 @@
     }
 
     private void updateServiceConnectionLocked(ComponentName component, int userId) {
-        UserState userState = getUserStateLocked(userId);
+        UserState userState = getOrCreateUserStateLocked(userId);
         ServiceState serviceState = userState.serviceStateMap.get(component);
         if (serviceState == null) {
             return;
@@ -574,7 +571,7 @@
     private void abortPendingCreateSessionRequestsLocked(ServiceState serviceState,
             String inputId, int userId) {
         // Let clients know the create session requests are failed.
-        UserState userState = getUserStateLocked(userId);
+        UserState userState = getOrCreateUserStateLocked(userId);
         List<SessionState> sessionsToAbort = new ArrayList<>();
         for (IBinder sessionToken : serviceState.sessionTokens) {
             SessionState sessionState = userState.sessionStateMap.get(sessionToken);
@@ -593,7 +590,7 @@
 
     private void createSessionInternalLocked(ITvInputService service, IBinder sessionToken,
             int userId) {
-        UserState userState = getUserStateLocked(userId);
+        UserState userState = getOrCreateUserStateLocked(userId);
         SessionState sessionState = userState.sessionStateMap.get(sessionToken);
         if (DEBUG) {
             Slog.d(TAG, "createSessionInternalLocked(inputId=" + sessionState.info.getId() + ")");
@@ -629,7 +626,7 @@
         try {
             sessionState = getSessionStateLocked(sessionToken, callingUid, userId);
             if (sessionState.session != null) {
-                UserState userState = getUserStateLocked(userId);
+                UserState userState = getOrCreateUserStateLocked(userId);
                 if (sessionToken == userState.mainSessionToken) {
                     setMainLocked(sessionToken, false, callingUid, userId);
                 }
@@ -646,7 +643,7 @@
     }
 
     private void removeSessionStateLocked(IBinder sessionToken, int userId) {
-        UserState userState = getUserStateLocked(userId);
+        UserState userState = getOrCreateUserStateLocked(userId);
         if (sessionToken == userState.mainSessionToken) {
             if (DEBUG) {
                 Slog.d(TAG, "mainSessionToken=null");
@@ -768,7 +765,7 @@
     }
 
     private void setStateLocked(String inputId, int state, int userId) {
-        UserState userState = getUserStateLocked(userId);
+        UserState userState = getOrCreateUserStateLocked(userId);
         TvInputState inputState = userState.inputMap.get(inputId);
         ServiceState serviceState = userState.serviceStateMap.get(inputState.info.getComponent());
         int oldState = inputState.state;
@@ -791,7 +788,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     List<TvInputInfo> inputList = new ArrayList<>();
                     for (TvInputState state : userState.inputMap.values()) {
                         inputList.add(state.info);
@@ -810,7 +807,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     TvInputState state = userState.inputMap.get(inputId);
                     return state == null ? null : state.info;
                 }
@@ -826,7 +823,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     TvInputState state = userState.inputMap.get(inputId);
                     return state == null ? INPUT_STATE_CONNECTED : state.state;
                 }
@@ -842,7 +839,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     return userState.contentRatingSystemList;
                 }
             } finally {
@@ -857,7 +854,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    final UserState userState = getUserStateLocked(resolvedUserId);
+                    final UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     userState.callbackSet.add(callback);
                     try {
                         callback.asBinder().linkToDeath(new IBinder.DeathRecipient() {
@@ -886,7 +883,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     userState.callbackSet.remove(callback);
                 }
             } finally {
@@ -901,7 +898,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     return userState.persistentDataStore.isParentalControlsEnabled();
                 }
             } finally {
@@ -917,7 +914,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     userState.persistentDataStore.setParentalControlsEnabled(enabled);
                 }
             } finally {
@@ -932,7 +929,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     return userState.persistentDataStore.isRatingBlocked(
                             TvContentRating.unflattenFromString(rating));
                 }
@@ -948,7 +945,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     List<String> ratings = new ArrayList<>();
                     for (TvContentRating rating
                             : userState.persistentDataStore.getBlockedRatings()) {
@@ -969,7 +966,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     userState.persistentDataStore.addBlockedRating(
                             TvContentRating.unflattenFromString(rating));
                 }
@@ -986,7 +983,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     userState.persistentDataStore.removeBlockedRating(
                             TvContentRating.unflattenFromString(rating));
                 }
@@ -1013,7 +1010,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     TvInputState inputState = userState.inputMap.get(inputId);
                     if (inputState == null) {
                         Slog.w(TAG, "Failed to find input state for inputId=" + inputId);
@@ -1084,7 +1081,7 @@
             final long identity = Binder.clearCallingIdentity();
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     if (userState.mainSessionToken == sessionToken) {
                         return;
                     }
@@ -1211,7 +1208,7 @@
                             return;
                         }
 
-                        UserState userState = getUserStateLocked(resolvedUserId);
+                        UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                         SessionState sessionState = userState.sessionStateMap.get(sessionToken);
 
                         // Log the start of watch.
@@ -1639,7 +1636,7 @@
             try {
                 String hardwareInputId = null;
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     if (userState.inputMap.get(inputId) == null) {
                         Slog.e(TAG, "input not found for " + inputId);
                         return false;
@@ -1669,7 +1666,7 @@
                     userId, "isSingleSessionActive");
             try {
                 synchronized (mLock) {
-                    UserState userState = getUserStateLocked(resolvedUserId);
+                    UserState userState = getOrCreateUserStateLocked(resolvedUserId);
                     if (userState.sessionStateMap.size() == 1) {
                         return true;
                     } else if (userState.sessionStateMap.size() == 2) {
@@ -1710,7 +1707,7 @@
 
                 for (int i = 0; i < mUserStates.size(); i++) {
                     int userId = mUserStates.keyAt(i);
-                    UserState userState = getUserStateLocked(userId);
+                    UserState userState = getOrCreateUserStateLocked(userId);
                     pw.println("UserState (" + userId + "):");
                     pw.increaseIndent();
 
@@ -1864,7 +1861,7 @@
         @Override
         public void binderDied() {
             synchronized (mLock) {
-                UserState userState = getUserStateLocked(userId);
+                UserState userState = getOrCreateUserStateLocked(userId);
                 // DO NOT remove the client state of clientStateMap in this method. It will be
                 // removed in releaseSessionLocked().
                 ClientState clientState = userState.clientStateMap.get(clientToken);
@@ -1945,7 +1942,7 @@
                     }
                 }
                 // If there are any other sessions based on this session, they should be released.
-                UserState userState = getUserStateLocked(userId);
+                UserState userState = getOrCreateUserStateLocked(userId);
                 for (SessionState sessionState : userState.sessionStateMap.values()) {
                     if (sessionToken == sessionState.hardwareSessionToken) {
                         releaseSessionLocked(sessionState.sessionToken, Process.SYSTEM_UID,
@@ -1977,7 +1974,7 @@
                 Slog.d(TAG, "onServiceConnected(component=" + component + ")");
             }
             synchronized (mLock) {
-                UserState userState = getUserStateLocked(mUserId);
+                UserState userState = getOrCreateUserStateLocked(mUserId);
                 ServiceState serviceState = userState.serviceStateMap.get(mComponent);
                 serviceState.service = ITvInputService.Stub.asInterface(service);
 
@@ -2038,7 +2035,7 @@
                         + mComponent + " (expected), " + component + " (actual).");
             }
             synchronized (mLock) {
-                UserState userState = getUserStateLocked(mUserId);
+                UserState userState = getOrCreateUserStateLocked(mUserId);
                 ServiceState serviceState = userState.serviceStateMap.get(mComponent);
                 if (serviceState != null) {
                     serviceState.reconnecting = true;
@@ -2163,7 +2160,7 @@
             }
 
             IBinder clientToken = mSessionState.client.asBinder();
-            UserState userState = getUserStateLocked(mSessionState.userId);
+            UserState userState = getOrCreateUserStateLocked(mSessionState.userId);
             ClientState clientState = userState.clientStateMap.get(clientToken);
             if (clientState == null) {
                 clientState = new ClientState(clientToken, mSessionState.userId);
@@ -2509,7 +2506,7 @@
         @Override
         public void onHardwareDeviceAdded(TvInputHardwareInfo info) {
             synchronized (mLock) {
-                UserState userState = getUserStateLocked(mCurrentUserId);
+                UserState userState = getOrCreateUserStateLocked(mCurrentUserId);
                 // Broadcast the event to all hardware inputs.
                 for (ServiceState serviceState : userState.serviceStateMap.values()) {
                     if (!serviceState.isHardware || serviceState.service == null) continue;
@@ -2525,7 +2522,7 @@
         @Override
         public void onHardwareDeviceRemoved(TvInputHardwareInfo info) {
             synchronized (mLock) {
-                UserState userState = getUserStateLocked(mCurrentUserId);
+                UserState userState = getOrCreateUserStateLocked(mCurrentUserId);
                 // Broadcast the event to all hardware inputs.
                 for (ServiceState serviceState : userState.serviceStateMap.values()) {
                     if (!serviceState.isHardware || serviceState.service == null) continue;
@@ -2541,7 +2538,7 @@
         @Override
         public void onHdmiDeviceAdded(HdmiDeviceInfo deviceInfo) {
             synchronized (mLock) {
-                UserState userState = getUserStateLocked(mCurrentUserId);
+                UserState userState = getOrCreateUserStateLocked(mCurrentUserId);
                 // Broadcast the event to all hardware inputs.
                 for (ServiceState serviceState : userState.serviceStateMap.values()) {
                     if (!serviceState.isHardware || serviceState.service == null) continue;
@@ -2557,7 +2554,7 @@
         @Override
         public void onHdmiDeviceRemoved(HdmiDeviceInfo deviceInfo) {
             synchronized (mLock) {
-                UserState userState = getUserStateLocked(mCurrentUserId);
+                UserState userState = getOrCreateUserStateLocked(mCurrentUserId);
                 // Broadcast the event to all hardware inputs.
                 for (ServiceState serviceState : userState.serviceStateMap.values()) {
                     if (!serviceState.isHardware || serviceState.service == null) continue;
diff --git a/services/core/java/com/android/server/wm/WindowAnimator.java b/services/core/java/com/android/server/wm/WindowAnimator.java
index 7630178..85a9624 100644
--- a/services/core/java/com/android/server/wm/WindowAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowAnimator.java
@@ -500,7 +500,13 @@
                         mPostKeyguardExitAnimation.getStartOffset(),
                         mPostKeyguardExitAnimation.getDuration());
                 mKeyguardGoingAway = false;
-            } else if (mPostKeyguardExitAnimation.hasEnded()) {
+            }
+            // mPostKeyguardExitAnimation might either be ended normally, cancelled, or "orphaned",
+            // meaning that the window it was running on was removed. We check for hasEnded() for
+            // ended normally and cancelled case, and check the time for the "orphaned" case.
+            else if (mPostKeyguardExitAnimation.hasEnded()
+                    || mCurrentTime - mPostKeyguardExitAnimation.getStartTime()
+                            > mPostKeyguardExitAnimation.getDuration()) {
                 // Done with the animation, reset.
                 if (DEBUG_KEYGUARD) Slog.v(TAG, "Done with Keyguard exit animations.");
                 mPostKeyguardExitAnimation = null;
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 05c111c..d9828cc 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -2543,8 +2543,10 @@
             win.attach();
             mWindowMap.put(client.asBinder(), win);
             if (win.mAppOp != AppOpsManager.OP_NONE) {
-                if (mAppOps.startOpNoThrow(win.mAppOp, win.getOwningUid(), win.getOwningPackage())
-                        != AppOpsManager.MODE_ALLOWED) {
+                int startOpResult = mAppOps.startOpNoThrow(win.mAppOp, win.getOwningUid(),
+                        win.getOwningPackage());
+                if ((startOpResult != AppOpsManager.MODE_ALLOWED) &&
+                        (startOpResult != AppOpsManager.MODE_DEFAULT)) {
                     win.setAppOpVisibilityLw(false);
                 }
             }
@@ -2728,10 +2730,10 @@
             wasVisible = win.isWinVisibleLw();
             if (wasVisible) {
 
-                int transit = WindowManagerPolicy.TRANSIT_EXIT;
-                if (win.mAttrs.type == TYPE_APPLICATION_STARTING) {
-                    transit = WindowManagerPolicy.TRANSIT_PREVIEW_DONE;
-                }
+                final int transit = (!startingWindow)
+                        ? WindowManagerPolicy.TRANSIT_EXIT
+                        : WindowManagerPolicy.TRANSIT_PREVIEW_DONE;
+
                 // Try starting an animation.
                 if (win.mWinAnimator.applyAnimationLocked(transit, false)) {
                     win.mExiting = true;
@@ -2743,12 +2745,13 @@
                 }
             }
             final AppWindowToken appToken = win.mAppToken;
+            final boolean isAnimating = win.mWinAnimator.isAnimating();
             // The starting window is the last window in this app token and it isn't animating.
             // Allow it to be removed now as there is no additional window or animation that will
             // trigger its removal.
             final boolean lastWinStartingNotAnimating = startingWindow && appToken!= null
-                    && appToken.allAppWindows.size() == 1 && !win.mWinAnimator.isAnimating();
-            if (!lastWinStartingNotAnimating && (win.mExiting || win.mWinAnimator.isAnimating())) {
+                    && appToken.allAppWindows.size() == 1 && !isAnimating;
+            if (!lastWinStartingNotAnimating && (win.mExiting || isAnimating)) {
                 // The exit animation is running... wait for it!
                 win.mExiting = true;
                 win.mRemoveOnExit = true;
@@ -2899,7 +2902,8 @@
                     if (win.mAppOp != AppOpsManager.OP_NONE) {
                         final int mode = mAppOps.checkOpNoThrow(win.mAppOp, win.getOwningUid(),
                                 win.getOwningPackage());
-                        win.setAppOpVisibilityLw(mode == AppOpsManager.MODE_ALLOWED);
+                        win.setAppOpVisibilityLw(mode == AppOpsManager.MODE_ALLOWED ||
+                                mode == AppOpsManager.MODE_DEFAULT);
                     }
                 }
             }
@@ -4524,7 +4528,10 @@
         }
 
         wtoken.willBeHidden = false;
-        if (wtoken.hidden == visible) {
+        // Allow for state changes and animation to be applied if token is transitioning
+        // visibility state or the token was marked as hidden and is exiting before we had a chance
+        // to play the transition animation.
+        if (wtoken.hidden == visible || (wtoken.hidden && wtoken.mIsExiting)) {
             boolean changed = false;
             if (DEBUG_APP_TRANSITIONS) Slog.v(
                 TAG, "Changing app " + wtoken + " hidden=" + wtoken.hidden
@@ -10008,7 +10015,7 @@
                     w.mContentChanged = false;
 
                     // Moved from updateWindowsAndWallpaperLocked().
-                    if (w.mHasSurface && !w.isHiddenFromUserLocked()) {
+                    if (w.mHasSurface) {
                         // Take care of the window being ready to display.
                         final boolean committed =
                                 winAnimator.commitFinishDrawingLocked();
@@ -10022,20 +10029,20 @@
                                         WindowManagerPolicy.FINISH_LAYOUT_REDO_LAYOUT;
                                 if (DEBUG_LAYOUT_REPEATS) {
                                     debugLayoutRepeats(
-                                        "dream and commitFinishDrawingLocked true",
-                                        displayContent.pendingLayoutChanges);
+                                            "dream and commitFinishDrawingLocked true",
+                                            displayContent.pendingLayoutChanges);
                                 }
                             }
                             if ((w.mAttrs.flags & FLAG_SHOW_WALLPAPER) != 0) {
                                 if (DEBUG_WALLPAPER_LIGHT) Slog.v(TAG,
-                                        "First draw done in potential wallpaper target " + w);
+                                            "First draw done in potential wallpaper target " + w);
                                 mInnerFields.mWallpaperMayChange = true;
                                 displayContent.pendingLayoutChanges |=
                                         WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
                                 if (DEBUG_LAYOUT_REPEATS) {
                                     debugLayoutRepeats(
-                                        "wallpaper and commitFinishDrawingLocked true",
-                                        displayContent.pendingLayoutChanges);
+                                            "wallpaper and commitFinishDrawingLocked true",
+                                            displayContent.pendingLayoutChanges);
                                 }
                             }
                         }
@@ -10043,52 +10050,49 @@
                         winAnimator.setSurfaceBoundariesLocked(recoveringMemory);
                     }
 
-                    // Check the draw state of the window, but only if it is visible to the user.
-                    if (!w.isHiddenFromUserLocked()) {
-                        final AppWindowToken atoken = w.mAppToken;
-                        if (DEBUG_STARTING_WINDOW && atoken != null
-                                && w == atoken.startingWindow) {
-                            Slog.d(TAG, "updateWindows: starting " + w + " isOnScreen="
-                                + w.isOnScreen() + " allDrawn=" + atoken.allDrawn
-                                + " freezingScreen=" + atoken.mAppAnimator.freezingScreen);
+                    final AppWindowToken atoken = w.mAppToken;
+                    if (DEBUG_STARTING_WINDOW && atoken != null
+                            && w == atoken.startingWindow) {
+                        Slog.d(TAG, "updateWindows: starting " + w + " isOnScreen="
+                            + w.isOnScreen() + " allDrawn=" + atoken.allDrawn
+                            + " freezingScreen=" + atoken.mAppAnimator.freezingScreen);
+                    }
+                    if (atoken != null
+                            && (!atoken.allDrawn || atoken.mAppAnimator.freezingScreen)) {
+                        if (atoken.lastTransactionSequence != mTransactionSequence) {
+                            atoken.lastTransactionSequence = mTransactionSequence;
+                            atoken.numInterestingWindows = atoken.numDrawnWindows = 0;
+                            atoken.startingDisplayed = false;
                         }
-                        if (atoken != null
-                                && (!atoken.allDrawn || atoken.mAppAnimator.freezingScreen)) {
-                            if (atoken.lastTransactionSequence != mTransactionSequence) {
-                                atoken.lastTransactionSequence = mTransactionSequence;
-                                atoken.numInterestingWindows = atoken.numDrawnWindows = 0;
-                                atoken.startingDisplayed = false;
+                        if ((w.isOnScreenIgnoringKeyguard()
+                                || winAnimator.mAttrType == TYPE_BASE_APPLICATION)
+                                && !w.mExiting && !w.mDestroying) {
+                            if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) {
+                                Slog.v(TAG, "Eval win " + w + ": isDrawn=" + w.isDrawnLw()
+                                        + ", isAnimating=" + winAnimator.isAnimating());
+                                if (!w.isDrawnLw()) {
+                                    Slog.v(TAG, "Not displayed: s=" + winAnimator.mSurfaceControl
+                                            + " pv=" + w.mPolicyVisibility
+                                            + " mDrawState=" + winAnimator.drawStateToString()
+                                            + " ah=" + w.mAttachedHidden
+                                            + " th=" + atoken.hiddenRequested
+                                            + " a=" + winAnimator.mAnimating);
+                                }
                             }
-                            if ((w.isOnScreenIgnoringKeyguard()
-                                    || winAnimator.mAttrType == TYPE_BASE_APPLICATION)
-                                    && !w.mExiting && !w.mDestroying) {
-                                if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) {
-                                    Slog.v(TAG, "Eval win " + w + ": isDrawn=" + w.isDrawnLw()
-                                            + ", isAnimating=" + winAnimator.isAnimating());
-                                    if (!w.isDrawnLw()) {
-                                        Slog.v(TAG, "Not displayed: s=" + winAnimator.mSurfaceControl
-                                                + " pv=" + w.mPolicyVisibility
-                                                + " mDrawState=" + winAnimator.drawStateToString()
-                                                + " ah=" + w.mAttachedHidden
-                                                + " th=" + atoken.hiddenRequested
-                                                + " a=" + winAnimator.mAnimating);
+                            if (w != atoken.startingWindow) {
+                                if (!atoken.mAppAnimator.freezingScreen || !w.mAppFreezing) {
+                                    atoken.numInterestingWindows++;
+                                    if (w.isDrawnLw()) {
+                                        atoken.numDrawnWindows++;
+                                        if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) Slog.v(TAG,
+                                                "tokenMayBeDrawn: " + atoken
+                                                + " freezingScreen=" + atoken.mAppAnimator.freezingScreen
+                                                + " mAppFreezing=" + w.mAppFreezing);
+                                        updateAllDrawn = true;
                                     }
                                 }
-                                if (w != atoken.startingWindow) {
-                                    if (!atoken.mAppAnimator.freezingScreen || !w.mAppFreezing) {
-                                        atoken.numInterestingWindows++;
-                                        if (w.isDrawnLw()) {
-                                            atoken.numDrawnWindows++;
-                                            if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) Slog.v(TAG,
-                                                    "tokenMayBeDrawn: " + atoken
-                                                    + " freezingScreen=" + atoken.mAppAnimator.freezingScreen
-                                                    + " mAppFreezing=" + w.mAppFreezing);
-                                            updateAllDrawn = true;
-                                        }
-                                    }
-                                } else if (w.isDrawnLw()) {
-                                    atoken.startingDisplayed = true;
-                                }
+                            } else if (w.isDrawnLw()) {
+                                atoken.startingDisplayed = true;
                             }
                         }
                     }
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index 96cd14b..3251a56 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -1667,6 +1667,8 @@
     // This must be called while inside a transaction.
     boolean performShowLocked() {
         if (mWin.isHiddenFromUserLocked()) {
+            if (DEBUG_VISIBILITY) Slog.w(TAG, "hiding " + mWin + ", belonging to " + mWin.mOwnerUid);
+            mWin.hideLw(false);
             return false;
         }
         if (DEBUG_VISIBILITY || (DEBUG_STARTING_WINDOW &&
diff --git a/services/usb/java/com/android/server/usb/UsbDeviceManager.java b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
index 653cbd8..4cfa37a 100644
--- a/services/usb/java/com/android/server/usb/UsbDeviceManager.java
+++ b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
@@ -49,10 +49,8 @@
 import com.android.server.FgThread;
 
 import java.io.File;
-import java.io.FileDescriptor;
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.io.PrintWriter;
 import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
@@ -122,6 +120,8 @@
     // Request is cancelled if host does not configure device within 10 seconds.
     private static final int ACCESSORY_REQUEST_TIMEOUT = 10 * 1000;
 
+    private static final String BOOT_MODE_PROPERTY = "ro.bootmode";
+
     private UsbHandler mHandler;
     private boolean mBootCompleted;
 
@@ -468,6 +468,7 @@
                 functions = getDefaultFunctions();
             }
             functions = applyAdbFunction(functions);
+            functions = applyOemOverrideFunction(functions);
             functions = applyUserRestrictions(functions);
 
             if (!mCurrentFunctions.equals(functions) || !mCurrentFunctionsApplied
@@ -804,8 +805,7 @@
         }
 
         private String getDefaultFunctions() {
-            return SystemProperties.get(USB_PERSISTENT_CONFIG_PROPERTY,
-                    UsbManager.USB_FUNCTION_ADB);
+            return mAdbEnabled ? UsbManager.USB_FUNCTION_ADB : UsbManager.USB_FUNCTION_MTP;
         }
 
         public void dump(IndentingPrintWriter pw) {
@@ -888,6 +888,24 @@
         }
     }
 
+    private String applyOemOverrideFunction(String usbFunctions) {
+        if ((usbFunctions == null) || (mOemModeMap == null)) return usbFunctions;
+
+        String bootMode = SystemProperties.get(BOOT_MODE_PROPERTY, "unknown");
+
+        List<Pair<String, String>> overrides = mOemModeMap.get(bootMode);
+        if (overrides != null) {
+            for (Pair<String, String> pair: overrides) {
+                if (pair.first.equals(usbFunctions)) {
+                    Slog.d(TAG, "OEM USB override: " + pair.first + " ==> " + pair.second);
+                    return pair.second;
+                }
+            }
+        }
+        // return passed in functions as is.
+        return usbFunctions;
+    }
+
     public void allowUsbDebugging(boolean alwaysAllow, String publicKey) {
         if (mDebuggingManager != null) {
             mDebuggingManager.allowUsbDebugging(alwaysAllow, publicKey);
diff --git a/services/usb/java/com/android/server/usb/UsbHostManager.java b/services/usb/java/com/android/server/usb/UsbHostManager.java
index 6300a9a..965341e 100644
--- a/services/usb/java/com/android/server/usb/UsbHostManager.java
+++ b/services/usb/java/com/android/server/usb/UsbHostManager.java
@@ -231,6 +231,8 @@
             mNewConfigurations = null;
             mNewInterfaces = null;
             mNewEndpoints = null;
+            mNewConfiguration = null;
+            mNewInterface = null;
         }
     }
 
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
index 36478da..a8874d0 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerService.java
@@ -448,7 +448,7 @@
                 }
                 final long caller = Binder.clearCallingIdentity();
                 try {
-                    mImpl.showSessionLocked(args, flags, null /* showCallback */);
+                    mImpl.showSessionLocked(args, flags, null, null);
                 } finally {
                     Binder.restoreCallingIdentity(caller);
                 }
@@ -463,12 +463,9 @@
                     throw new SecurityException(
                             "deliverNewSession without running voice interaction service");
                 }
-                final int callingPid = Binder.getCallingPid();
-                final int callingUid = Binder.getCallingUid();
                 final long caller = Binder.clearCallingIdentity();
                 try {
-                    return mImpl.deliverNewSessionLocked(callingPid, callingUid, token, session,
-                            interactor);
+                    return mImpl.deliverNewSessionLocked(token, session, interactor);
                 } finally {
                     Binder.restoreCallingIdentity(caller);
                 }
@@ -484,7 +481,7 @@
                 }
                 final long caller = Binder.clearCallingIdentity();
                 try {
-                    return mImpl.showSessionLocked(sessionArgs, flags, null /* showCallback */);
+                    return mImpl.showSessionLocked(sessionArgs, flags, null, null);
                 } finally {
                     Binder.restoreCallingIdentity(caller);
                 }
@@ -533,11 +530,9 @@
                     Slog.w(TAG, "setKeepAwake without running voice interaction service");
                     return;
                 }
-                final int callingPid = Binder.getCallingPid();
-                final int callingUid = Binder.getCallingUid();
                 final long caller = Binder.clearCallingIdentity();
                 try {
-                    mImpl.setKeepAwakeLocked(callingPid, callingUid, token, keepAwake);
+                    mImpl.setKeepAwakeLocked(token, keepAwake);
                 } finally {
                     Binder.restoreCallingIdentity(caller);
                 }
@@ -551,11 +546,9 @@
                     Slog.w(TAG, "closeSystemDialogs without running voice interaction service");
                     return;
                 }
-                final int callingPid = Binder.getCallingPid();
-                final int callingUid = Binder.getCallingUid();
                 final long caller = Binder.clearCallingIdentity();
                 try {
-                    mImpl.closeSystemDialogsLocked(callingPid, callingUid, token);
+                    mImpl.closeSystemDialogsLocked(token);
                 } finally {
                     Binder.restoreCallingIdentity(caller);
                 }
@@ -578,6 +571,58 @@
             }
         }
 
+        @Override
+        public void setDisabledShowContext(int flags) {
+            synchronized (this) {
+                if (mImpl == null) {
+                    Slog.w(TAG, "setDisabledShowContext without running voice interaction service");
+                    return;
+                }
+                final int callingUid = Binder.getCallingUid();
+                final long caller = Binder.clearCallingIdentity();
+                try {
+                    mImpl.setDisabledShowContextLocked(callingUid, flags);
+                } finally {
+                    Binder.restoreCallingIdentity(caller);
+                }
+            }
+        }
+
+        @Override
+        public int getDisabledShowContext() {
+            synchronized (this) {
+                if (mImpl == null) {
+                    Slog.w(TAG, "getDisabledShowContext without running voice interaction service");
+                    return 0;
+                }
+                final int callingUid = Binder.getCallingUid();
+                final long caller = Binder.clearCallingIdentity();
+                try {
+                    return mImpl.getDisabledShowContextLocked(callingUid);
+                } finally {
+                    Binder.restoreCallingIdentity(caller);
+                }
+            }
+        }
+
+        @Override
+        public int getUserDisabledShowContext() {
+            synchronized (this) {
+                if (mImpl == null) {
+                    Slog.w(TAG,
+                            "getUserDisabledShowContext without running voice interaction service");
+                    return 0;
+                }
+                final int callingUid = Binder.getCallingUid();
+                final long caller = Binder.clearCallingIdentity();
+                try {
+                    return mImpl.getUserDisabledShowContextLocked(callingUid);
+                } finally {
+                    Binder.restoreCallingIdentity(caller);
+                }
+            }
+        }
+
         //----------------- Model management APIs --------------------------------//
 
         @Override
@@ -761,22 +806,22 @@
         }
 
         @Override
-        public void showSessionForActiveService(Bundle args,
-                IVoiceInteractionSessionShowCallback showCallback) {
+        public boolean showSessionForActiveService(Bundle args, int sourceFlags,
+                IVoiceInteractionSessionShowCallback showCallback, IBinder activityToken) {
             enforceCallingPermission(Manifest.permission.ACCESS_VOICE_INTERACTION_SERVICE);
             synchronized (this) {
                 if (mImpl == null) {
                     Slog.w(TAG, "showSessionForActiveService without running voice interaction"
                             + "service");
-                    return;
+                    return false;
                 }
                 final long caller = Binder.clearCallingIdentity();
                 try {
-                    mImpl.showSessionLocked(args,
-                            VoiceInteractionSession.SHOW_SOURCE_ASSIST_GESTURE
+                    return mImpl.showSessionLocked(args,
+                            sourceFlags
                                     | VoiceInteractionSession.SHOW_WITH_ASSIST
                                     | VoiceInteractionSession.SHOW_WITH_SCREENSHOT,
-                            showCallback);
+                            showCallback, activityToken);
                 } finally {
                     Binder.restoreCallingIdentity(caller);
                 }
@@ -849,6 +894,28 @@
         }
 
         @Override
+        public void onLockscreenShown() {
+            enforceCallingPermission(Manifest.permission.ACCESS_VOICE_INTERACTION_SERVICE);
+            synchronized (this) {
+                if (mImpl == null) {
+                    return;
+                }
+                final long caller = Binder.clearCallingIdentity();
+                try {
+                    if (mImpl.mActiveSession != null && mImpl.mActiveSession.mSession != null) {
+                        try {
+                            mImpl.mActiveSession.mSession.onLockscreenShown();
+                        } catch (RemoteException e) {
+                            Log.w(TAG, "Failed to call onLockscreenShown", e);
+                        }
+                    }
+                } finally {
+                    Binder.restoreCallingIdentity(caller);
+                }
+            }
+        }
+
+        @Override
         public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
             if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
                     != PackageManager.PERMISSION_GRANTED) {
@@ -870,7 +937,8 @@
         }
 
         private void enforceCallingPermission(String permission) {
-            if (mContext.checkCallingPermission(permission) != PackageManager.PERMISSION_GRANTED) {
+            if (mContext.checkCallingOrSelfPermission(permission)
+                    != PackageManager.PERMISSION_GRANTED) {
                 throw new SecurityException("Caller does not hold the permission " + permission);
             }
         }
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java
index e5faf4d..a4facc1 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java
@@ -65,6 +65,7 @@
     IVoiceInteractionService mService;
 
     VoiceInteractionSessionConnection mActiveSession;
+    int mDisabledShowContext;
 
     final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
         @Override
@@ -141,12 +142,13 @@
     }
 
     public boolean showSessionLocked(Bundle args, int flags,
-            IVoiceInteractionSessionShowCallback showCallback) {
+            IVoiceInteractionSessionShowCallback showCallback, IBinder activityToken) {
         if (mActiveSession == null) {
             mActiveSession = new VoiceInteractionSessionConnection(mLock, mSessionComponentName,
                     mUser, mContext, this, mInfo.getServiceInfo().applicationInfo.uid, mHandler);
         }
-        return mActiveSession.showLocked(args, flags, showCallback);
+        return mActiveSession.showLocked(args, flags, mDisabledShowContext, showCallback,
+                activityToken);
     }
 
     public boolean hideSessionLocked() {
@@ -156,7 +158,7 @@
         return false;
     }
 
-    public boolean deliverNewSessionLocked(int callingPid, int callingUid, IBinder token,
+    public boolean deliverNewSessionLocked(IBinder token,
             IVoiceInteractionSession session, IVoiceInteractor interactor) {
         if (mActiveSession == null || token != mActiveSession.mToken) {
             Slog.w(TAG, "deliverNewSession does not match active session");
@@ -188,8 +190,7 @@
         }
     }
 
-    public void setKeepAwakeLocked(int callingPid, int callingUid, IBinder token,
-            boolean keepAwake) {
+    public void setKeepAwakeLocked(IBinder token, boolean keepAwake) {
         try {
             if (mActiveSession == null || token != mActiveSession.mToken) {
                 Slog.w(TAG, "setKeepAwake does not match active session");
@@ -201,7 +202,7 @@
         }
     }
 
-    public void closeSystemDialogsLocked(int callingPid, int callingUid, IBinder token) {
+    public void closeSystemDialogsLocked(IBinder token) {
         try {
             if (mActiveSession == null || token != mActiveSession.mToken) {
                 Slog.w(TAG, "closeSystemDialogs does not match active session");
@@ -222,6 +223,33 @@
         mActiveSession = null;
     }
 
+    public void setDisabledShowContextLocked(int callingUid, int flags) {
+        int activeUid = mInfo.getServiceInfo().applicationInfo.uid;
+        if (callingUid != activeUid) {
+            throw new SecurityException("Calling uid " + callingUid
+                    + " does not match active uid " + activeUid);
+        }
+        mDisabledShowContext = flags;
+    }
+
+    public int getDisabledShowContextLocked(int callingUid) {
+        int activeUid = mInfo.getServiceInfo().applicationInfo.uid;
+        if (callingUid != activeUid) {
+            throw new SecurityException("Calling uid " + callingUid
+                    + " does not match active uid " + activeUid);
+        }
+        return mDisabledShowContext;
+    }
+
+    public int getUserDisabledShowContextLocked(int callingUid) {
+        int activeUid = mInfo.getServiceInfo().applicationInfo.uid;
+        if (callingUid != activeUid) {
+            throw new SecurityException("Calling uid " + callingUid
+                    + " does not match active uid " + activeUid);
+        }
+        return mActiveSession != null ? mActiveSession.getUserDisabledShowContextLocked() : 0;
+    }
+
     public void dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args) {
         if (!mValid) {
             pw.print("  NOT VALID: ");
@@ -235,6 +263,10 @@
         pw.print("  mComponent="); pw.println(mComponent.flattenToShortString());
         pw.print("  Session service="); pw.println(mInfo.getSessionService());
         pw.print("  Settings activity="); pw.println(mInfo.getSettingsActivity());
+        if (mDisabledShowContext != 0) {
+            pw.print("  mDisabledShowContext=");
+            pw.println(Integer.toHexString(mDisabledShowContext));
+        }
         pw.print("  mBound="); pw.print(mBound);  pw.print(" mService="); pw.println(mService);
         if (mActiveSession != null) {
             pw.println("  Active session:");
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java
index bd043ac..47a9fcd 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java
@@ -183,8 +183,21 @@
         }
     }
 
-    public boolean showLocked(Bundle args, int flags,
-            IVoiceInteractionSessionShowCallback showCallback) {
+    public int getUserDisabledShowContextLocked() {
+        int flags = 0;
+        if (Settings.Secure.getIntForUser(mContext.getContentResolver(),
+                Settings.Secure.ASSIST_STRUCTURE_ENABLED, 1, mUser) == 0) {
+            flags |= VoiceInteractionSession.SHOW_WITH_ASSIST;
+        }
+        if (Settings.Secure.getIntForUser(mContext.getContentResolver(),
+                Settings.Secure.ASSIST_SCREENSHOT_ENABLED, 1, mUser) == 0) {
+            flags |= VoiceInteractionSession.SHOW_WITH_SCREENSHOT;
+        }
+        return flags;
+    }
+
+    public boolean showLocked(Bundle args, int flags, int disabledContext,
+            IVoiceInteractionSessionShowCallback showCallback, IBinder activityToken) {
         if (mBound) {
             if (!mFullyBound) {
                 mFullyBound = mContext.bindServiceAsUser(mBindIntent, mFullConnection,
@@ -193,29 +206,34 @@
                         new UserHandle(mUser));
             }
             mShown = true;
-            boolean isScreenCaptureAllowed = true;
+            boolean isAssistDataAllowed = true;
             try {
-                isScreenCaptureAllowed = mAm.isScreenCaptureAllowedOnCurrentActivity();
+                isAssistDataAllowed = mAm.isAssistDataAllowedOnCurrentActivity();
             } catch (RemoteException e) {
             }
-            boolean structureEnabled = Settings.Secure.getIntForUser(mContext.getContentResolver(),
-                    Settings.Secure.ASSIST_STRUCTURE_ENABLED, 1, mUser) != 0
-                    && isScreenCaptureAllowed;
-            boolean screenshotEnabled = Settings.Secure.getIntForUser(mContext.getContentResolver(),
-                    Settings.Secure.ASSIST_SCREENSHOT_ENABLED, 1, mUser) != 0
-                    && isScreenCaptureAllowed;
+            disabledContext |= getUserDisabledShowContextLocked();
+            boolean structureEnabled = isAssistDataAllowed
+                    && (disabledContext&VoiceInteractionSession.SHOW_WITH_ASSIST) == 0;
+            boolean screenshotEnabled = isAssistDataAllowed
+                    && (disabledContext&VoiceInteractionSession.SHOW_WITH_SCREENSHOT) == 0;
             mShowArgs = args;
             mShowFlags = flags;
             mHaveAssistData = false;
             boolean needDisclosure = false;
-            if ((flags& VoiceInteractionSession.SHOW_WITH_ASSIST) != 0) {
+            if ((flags&VoiceInteractionSession.SHOW_WITH_ASSIST) != 0) {
                 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ASSIST_STRUCTURE, mCallingUid,
                         mSessionComponentName.getPackageName()) == AppOpsManager.MODE_ALLOWED
                         && structureEnabled) {
                     try {
-                        needDisclosure = true;
-                        mAm.requestAssistContextExtras(ActivityManager.ASSIST_CONTEXT_FULL,
-                                mAssistReceiver);
+                        if (mAm.requestAssistContextExtras(ActivityManager.ASSIST_CONTEXT_FULL,
+                                mAssistReceiver, activityToken)) {
+                            needDisclosure = true;
+                        } else {
+                            // Wasn't allowed...  given that, let's not do the screenshot either.
+                            mHaveAssistData = true;
+                            mAssistData = null;
+                            screenshotEnabled = false;
+                        }
                     } catch (RemoteException e) {
                     }
                 } else {
@@ -226,7 +244,7 @@
                 mAssistData = null;
             }
             mHaveScreenshot = false;
-            if ((flags& VoiceInteractionSession.SHOW_WITH_SCREENSHOT) != 0) {
+            if ((flags&VoiceInteractionSession.SHOW_WITH_SCREENSHOT) != 0) {
                 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ASSIST_SCREENSHOT, mCallingUid,
                         mSessionComponentName.getPackageName()) == AppOpsManager.MODE_ALLOWED
                         && screenshotEnabled) {
diff --git a/telecomm/java/android/telecom/Connection.java b/telecomm/java/android/telecom/Connection.java
index 58fb088..bf78712 100644
--- a/telecomm/java/android/telecom/Connection.java
+++ b/telecomm/java/android/telecom/Connection.java
@@ -1050,6 +1050,7 @@
     private int mConnectionCapabilities;
     private VideoProvider mVideoProvider;
     private boolean mAudioModeIsVoip;
+    private long mConnectTimeMillis = Conference.CONNECT_TIME_NOT_SPECIFIED;
     private StatusHints mStatusHints;
     private int mVideoState;
     private DisconnectCause mDisconnectCause;
@@ -1162,6 +1163,19 @@
     }
 
     /**
+     * Retrieves the connection start time of the {@code Connnection}, if specified.  A value of
+     * {@link Conference#CONNECT_TIME_NOT_SPECIFIED} indicates that Telecom should determine the
+     * start time of the conference.
+     *
+     * @return The time at which the {@code Connnection} was connected.
+     *
+     * @hide
+     */
+    public final long getConnectTimeMillis() {
+        return mConnectTimeMillis;
+    }
+
+    /**
      * @return The status hints for this connection.
      */
     public final StatusHints getStatusHints() {
@@ -1476,6 +1490,18 @@
     }
 
     /**
+     * Sets the time at which a call became active on this Connection. This is set only
+     * when a conference call becomes active on this connection.
+     *
+     * @param connectionTimeMillis The connection time, in milliseconds.
+     *
+     * @hide
+     */
+    public final void setConnectTimeMillis(long connectTimeMillis) {
+        mConnectTimeMillis = connectTimeMillis;
+    }
+
+    /**
      * Sets the label and icon status to display in the in-call UI.
      *
      * @param statusHints The status label and icon to set.
diff --git a/telecomm/java/android/telecom/ConnectionService.java b/telecomm/java/android/telecom/ConnectionService.java
index d2e7a74..96f44b9 100644
--- a/telecomm/java/android/telecom/ConnectionService.java
+++ b/telecomm/java/android/telecom/ConnectionService.java
@@ -651,6 +651,7 @@
                         connection.getVideoState(),
                         connection.isRingbackRequested(),
                         connection.getAudioModeIsVoip(),
+                        connection.getConnectTimeMillis(),
                         connection.getStatusHints(),
                         connection.getDisconnectCause(),
                         createIdList(connection.getConferenceables()),
@@ -979,6 +980,7 @@
                     connection.getVideoState(),
                     connection.isRingbackRequested(),
                     connection.getAudioModeIsVoip(),
+                    connection.getConnectTimeMillis(),
                     connection.getStatusHints(),
                     connection.getDisconnectCause(),
                     emptyList,
diff --git a/telecomm/java/android/telecom/ParcelableConnection.java b/telecomm/java/android/telecom/ParcelableConnection.java
index 683ab6a..fe0a4d8 100644
--- a/telecomm/java/android/telecom/ParcelableConnection.java
+++ b/telecomm/java/android/telecom/ParcelableConnection.java
@@ -44,6 +44,7 @@
     private final int mVideoState;
     private final boolean mRingbackRequested;
     private final boolean mIsVoipAudioMode;
+    private final long mConnectTimeMillis;
     private final StatusHints mStatusHints;
     private final DisconnectCause mDisconnectCause;
     private final List<String> mConferenceableConnectionIds;
@@ -62,6 +63,7 @@
             int videoState,
             boolean ringbackRequested,
             boolean isVoipAudioMode,
+            long connectTimeMillis,
             StatusHints statusHints,
             DisconnectCause disconnectCause,
             List<String> conferenceableConnectionIds,
@@ -77,6 +79,7 @@
         mVideoState = videoState;
         mRingbackRequested = ringbackRequested;
         mIsVoipAudioMode = isVoipAudioMode;
+        mConnectTimeMillis = connectTimeMillis;
         mStatusHints = statusHints;
         mDisconnectCause = disconnectCause;
         mConferenceableConnectionIds = conferenceableConnectionIds;
@@ -128,6 +131,10 @@
         return mIsVoipAudioMode;
     }
 
+    public long getConnectTimeMillis() {
+        return mConnectTimeMillis;
+    }
+
     public final StatusHints getStatusHints() {
         return mStatusHints;
     }
@@ -176,6 +183,7 @@
             int videoState = source.readInt();
             boolean ringbackRequested = source.readByte() == 1;
             boolean audioModeIsVoip = source.readByte() == 1;
+            long connectTimeMillis = source.readLong();
             StatusHints statusHints = source.readParcelable(classLoader);
             DisconnectCause disconnectCause = source.readParcelable(classLoader);
             List<String> conferenceableConnectionIds = new ArrayList<>();
@@ -194,6 +202,7 @@
                     videoState,
                     ringbackRequested,
                     audioModeIsVoip,
+                    connectTimeMillis,
                     statusHints,
                     disconnectCause,
                     conferenceableConnectionIds,
@@ -227,6 +236,7 @@
         destination.writeInt(mVideoState);
         destination.writeByte((byte) (mRingbackRequested ? 1 : 0));
         destination.writeByte((byte) (mIsVoipAudioMode ? 1 : 0));
+        destination.writeLong(mConnectTimeMillis);
         destination.writeParcelable(mStatusHints, 0);
         destination.writeParcelable(mDisconnectCause, 0);
         destination.writeStringList(mConferenceableConnectionIds);
diff --git a/telecomm/java/android/telecom/Voicemail.java b/telecomm/java/android/telecom/Voicemail.java
index 151917e..ca235bf 100644
--- a/telecomm/java/android/telecom/Voicemail.java
+++ b/telecomm/java/android/telecom/Voicemail.java
@@ -36,10 +36,11 @@
     private final Uri mUri;
     private final Boolean mIsRead;
     private final Boolean mHasContent;
+    private final String mTranscription;
 
     private Voicemail(Long timestamp, String number, PhoneAccountHandle phoneAccountHandle, Long id,
             Long duration, String source, String providerData, Uri uri, Boolean isRead,
-            Boolean hasContent) {
+            Boolean hasContent, String transcription) {
         mTimestamp = timestamp;
         mNumber = number;
         mPhoneAccount = phoneAccountHandle;
@@ -50,6 +51,7 @@
         mUri = uri;
         mIsRead = isRead;
         mHasContent = hasContent;
+        mTranscription = transcription;
     }
 
     /**
@@ -88,6 +90,7 @@
         private Uri mBuilderUri;
         private Boolean mBuilderIsRead;
         private boolean mBuilderHasContent;
+        private String mBuilderTranscription;
 
         /** You should use the correct factory method to construct a builder. */
         private Builder() {
@@ -143,6 +146,11 @@
             return this;
         }
 
+        public Builder setTranscription(String transcription) {
+            mBuilderTranscription = transcription;
+            return this;
+        }
+
         public Voicemail build() {
             mBuilderId = mBuilderId == null ? -1 : mBuilderId;
             mBuilderTimestamp = mBuilderTimestamp == null ? 0 : mBuilderTimestamp;
@@ -150,7 +158,7 @@
             mBuilderIsRead = mBuilderIsRead == null ? false : mBuilderIsRead;
             return new Voicemail(mBuilderTimestamp, mBuilderNumber, mBuilderPhoneAccount,
                     mBuilderId, mBuilderDuration, mBuilderSourcePackage, mBuilderSourceData,
-                    mBuilderUri, mBuilderIsRead, mBuilderHasContent);
+                    mBuilderUri, mBuilderIsRead, mBuilderHasContent, mBuilderTranscription);
         }
     }
 
@@ -230,6 +238,13 @@
         return mHasContent;
     }
 
+    /**
+     * Returns the text transcription of this voicemail, or null if this field is not set.
+     */
+    public String getTranscription() {
+        return mTranscription;
+    }
+
     @Override
     public int describeContents() {
         return 0;
@@ -265,6 +280,7 @@
         } else {
             dest.writeInt(0);
         }
+        dest.writeCharSequence(mTranscription);
     }
 
     public static final Creator<Voicemail> CREATOR
@@ -299,5 +315,6 @@
         }
         mIsRead = in.readInt() > 0 ? true : false;
         mHasContent = in.readInt() > 0 ? true : false;
+        mTranscription = (String) in.readCharSequence();
     }
 }
diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java
index f4a6064..32b7383 100644
--- a/telephony/java/android/telephony/SubscriptionManager.java
+++ b/telephony/java/android/telephony/SubscriptionManager.java
@@ -21,12 +21,15 @@
 import android.annotation.SdkConstant.SdkConstantType;
 import android.content.Context;
 import android.content.Intent;
+import android.content.res.Configuration;
+import android.content.res.Resources;
 import android.net.Uri;
 import android.telephony.Rlog;
 import android.os.Handler;
 import android.os.Message;
 import android.os.ServiceManager;
 import android.os.RemoteException;
+import android.util.DisplayMetrics;
 
 import com.android.internal.telephony.ISub;
 import com.android.internal.telephony.IOnSubscriptionsChangedListener;
@@ -248,6 +251,78 @@
     public static final String MNC = "mnc";
 
     /**
+     *  TelephonyProvider column name for extreme threat in CB settings
+     * @hide
+     */
+    public static final String CB_EXTREME_THREAT_ALERT = "enable_cmas_extreme_threat_alerts";
+
+    /**
+     * TelephonyProvider column name for severe threat in CB settings
+     *@hide
+     */
+    public static final String CB_SEVERE_THREAT_ALERT = "enable_cmas_severe_threat_alerts";
+
+    /**
+     * TelephonyProvider column name for amber alert in CB settings
+     *@hide
+     */
+    public static final String CB_AMBER_ALERT = "enable_cmas_amber_alerts";
+
+    /**
+     * TelephonyProvider column name for emergency alert in CB settings
+     *@hide
+     */
+    public static final String CB_EMERGENCY_ALERT = "enable_emergency_alerts";
+
+    /**
+     * TelephonyProvider column name for alert sound duration in CB settings
+     *@hide
+     */
+    public static final String CB_ALERT_SOUND_DURATION = "alert_sound_duration";
+
+    /**
+     * TelephonyProvider column name for alert reminder interval in CB settings
+     *@hide
+     */
+    public static final String CB_ALERT_REMINDER_INTERVAL = "alert_reminder_interval";
+
+    /**
+     * TelephonyProvider column name for enabling vibrate in CB settings
+     *@hide
+     */
+    public static final String CB_ALERT_VIBRATE = "enable_alert_vibrate";
+
+    /**
+     * TelephonyProvider column name for enabling alert speech in CB settings
+     *@hide
+     */
+    public static final String CB_ALERT_SPEECH = "enable_alert_speech";
+
+    /**
+     * TelephonyProvider column name for ETWS test alert in CB settings
+     *@hide
+     */
+    public static final String CB_ETWS_TEST_ALERT = "enable_etws_test_alerts";
+
+    /**
+     * TelephonyProvider column name for enable channel50 alert in CB settings
+     *@hide
+     */
+    public static final String CB_CHANNEL_50_ALERT = "enable_channel_50_alerts";
+
+    /**
+     * TelephonyProvider column name for CMAS test alert in CB settings
+     *@hide
+     */
+    public static final String CB_CMAS_TEST_ALERT= "enable_cmas_test_alerts";
+
+    /**
+     * TelephonyProvider column name for Opt out dialog in CB settings
+     *@hide
+     */
+    public static final String CB_OPT_OUT_DIALOG = "show_cmas_opt_out_dialog";
+
+    /**
      * Broadcast Action: The user has changed one of the default subs related to
      * data, phone calls, or sms</p>
      *
@@ -1137,6 +1212,112 @@
     }
 
     /**
+     * Store properties associated with SubscriptionInfo in database
+     * @param subId Subscription Id of Subscription
+     * @param propKey Column name in database associated with SubscriptionInfo
+     * @param propValue Value to store in DB for particular subId & column name
+     * @hide
+     */
+    public static void setSubscriptionProperty(int subId, String propKey, String propValue) {
+        try {
+            ISub iSub = ISub.Stub.asInterface(ServiceManager.getService("isub"));
+            if (iSub != null) {
+                iSub.setSubscriptionProperty(subId, propKey, propValue);
+            }
+        } catch (RemoteException ex) {
+            // ignore it
+        }
+    }
+
+    /**
+     * Store properties associated with SubscriptionInfo in database
+     * @param subId Subscription Id of Subscription
+     * @param propKey Column name in SubscriptionInfo database
+     * @return Value associated with subId and propKey column in database
+     * @hide
+     */
+    private static String getSubscriptionProperty(int subId, String propKey,
+            Context context) {
+        String resultValue = null;
+        try {
+            ISub iSub = ISub.Stub.asInterface(ServiceManager.getService("isub"));
+            if (iSub != null) {
+                resultValue = iSub.getSubscriptionProperty(subId, propKey, 
+                    context.getOpPackageName());
+            }
+        } catch (RemoteException ex) {
+            // ignore it
+        }
+        return resultValue;
+    }
+
+    /**
+     * Returns boolean value corresponding to query result.
+     * @param subId Subscription Id of Subscription
+     * @param propKey Column name in SubscriptionInfo database
+     * @param defValue Default boolean value to be returned
+     * @return boolean result value to be returned
+     * @hide
+     */
+    public static boolean getBooleanSubscriptionProperty(int subId, String propKey,
+            boolean defValue, Context context) {
+        String result = getSubscriptionProperty(subId, propKey, context);
+        if (result != null) {
+            try {
+                return Integer.parseInt(result) == 1;
+            } catch (NumberFormatException err) {
+                logd("getBooleanSubscriptionProperty NumberFormat exception");
+            }
+        }
+        return defValue;
+    }
+
+    /**
+     * Returns integer value corresponding to query result.
+     * @param subId Subscription Id of Subscription
+     * @param propKey Column name in SubscriptionInfo database
+     * @param defValue Default integer value to be returned
+     * @return integer result value to be returned
+     * @hide
+     */
+    public static int getIntegerSubscriptionProperty(int subId, String propKey, int defValue,
+            Context context) {
+        String result = getSubscriptionProperty(subId, propKey, context);
+        if (result != null) {
+            try {
+                return Integer.parseInt(result);
+            } catch (NumberFormatException err) {
+                logd("getBooleanSubscriptionProperty NumberFormat exception");
+            }
+        }
+        return defValue;
+    }
+
+    /**
+     * Returns the resources associated with Subscription.
+     * @param context Context object
+     * @param subId Subscription Id of Subscription who's resources are required
+     * @return Resources associated with Subscription.
+     * @hide
+     */
+    public static Resources getResourcesForSubId(Context context, int subId) {
+        final SubscriptionInfo subInfo =
+                SubscriptionManager.from(context).getActiveSubscriptionInfo(subId);
+
+        Configuration config = context.getResources().getConfiguration();
+        Configuration newConfig = new Configuration();
+        newConfig.setTo(config);
+        if (subInfo != null) {
+            newConfig.mcc = subInfo.getMcc();
+            newConfig.mnc = subInfo.getMnc();
+        }
+        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
+        DisplayMetrics newMetrics = new DisplayMetrics();
+        newMetrics.setTo(metrics);
+        return new Resources(context.getResources().getAssets(), newMetrics, newConfig);
+    }
+
+    /**
      * @return true if the sub ID is active. i.e. The sub ID corresponds to a known subscription
      * and the SIM providing the subscription is present in a slot and in "LOADED" state.
      * @hide
diff --git a/telephony/java/com/android/internal/telephony/ISub.aidl b/telephony/java/com/android/internal/telephony/ISub.aidl
index 0555121..f6aef08 100755
--- a/telephony/java/com/android/internal/telephony/ISub.aidl
+++ b/telephony/java/com/android/internal/telephony/ISub.aidl
@@ -172,6 +172,10 @@
 
     int[] getActiveSubIdList();
 
+    void setSubscriptionProperty(int subId, String propKey, String propValue);
+
+    String getSubscriptionProperty(int subId, String propKey, String callingPackage);
+
     /**
      * Get the SIM state for the slot idx
      * @return SIM state as the ordinal of IccCardConstants.State
diff --git a/tests/AccessibilityEventsLogger/Android.mk b/tests/AccessibilityEventsLogger/Android.mk
new file mode 100644
index 0000000..52bc579
--- /dev/null
+++ b/tests/AccessibilityEventsLogger/Android.mk
@@ -0,0 +1,13 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_PACKAGE_NAME := AccessibilityEventsLogger
+LOCAL_CERTIFICATE := platform
+
+LOCAL_PROGUARD_ENABLED := disabled
+
+include $(BUILD_PACKAGE)
diff --git a/tests/AccessibilityEventsLogger/AndroidManifest.xml b/tests/AccessibilityEventsLogger/AndroidManifest.xml
new file mode 100644
index 0000000..d86769f
--- /dev/null
+++ b/tests/AccessibilityEventsLogger/AndroidManifest.xml
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2015 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    package="com.android.tests.accessibilityeventlogger"
+    android:versionCode="1"
+    android:versionName="0.0" >
+
+    <uses-sdk
+        android:minSdkVersion="18"
+        android:targetSdkVersion="18" />
+
+    <application
+        android:allowBackup="true"
+        android:enabled="true"
+        android:label="@string/app_name" >
+
+        <service
+            android:name=".AELogger"
+            android:enabled="true"
+            android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
+            android:configChanges="locale" >
+            <intent-filter>
+                <action android:name="android.accessibilityservice.AccessibilityService"/>
+
+                <category android:name="android.accessibilityservice.category.FEEDBACK_GENERIC"/>
+                <category android:name="android.accessibilityservice.category.FEEDBACK_VISUAL"/>
+                <category android:name="android.accessibilityservice.category.FEEDBACK_AUDIBLE"/>
+            </intent-filter>
+
+            <meta-data
+                android:name="android.accessibilityservice"
+                android:resource="@xml/accessibilityservice" />
+        </service>
+    </application>
+</manifest>
diff --git a/tests/AccessibilityEventsLogger/res/values/strings.xml b/tests/AccessibilityEventsLogger/res/values/strings.xml
new file mode 100644
index 0000000..353f912
--- /dev/null
+++ b/tests/AccessibilityEventsLogger/res/values/strings.xml
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2015 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.
+-->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+    <!-- CHAR LIMIT=none -->
+    <string name="app_name">
+        Accessibility Event Logger
+    </string>
+
+    <!-- CHAR LIMIT=none -->
+    <string name="service_description">
+        Debugging service
+    </string>
+</resources>
diff --git a/tests/AccessibilityEventsLogger/res/xml/accessibilityservice.xml b/tests/AccessibilityEventsLogger/res/xml/accessibilityservice.xml
new file mode 100644
index 0000000..69ecd61
--- /dev/null
+++ b/tests/AccessibilityEventsLogger/res/xml/accessibilityservice.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2015 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.
+-->
+
+<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
+    android:accessibilityEventTypes="typeAllMask"
+    android:accessibilityFeedbackType="feedbackGeneric|feedbackVisual|feedbackAudible"
+    android:canRetrieveWindowContent="true"
+    android:accessibilityFlags="flagDefault"
+    android:description="@string/service_description"
+    android:notificationTimeout="0" />
diff --git a/tests/AccessibilityEventsLogger/src/com/android/tests/accessibilityeventslogger/AELogger.java b/tests/AccessibilityEventsLogger/src/com/android/tests/accessibilityeventslogger/AELogger.java
new file mode 100644
index 0000000..27d8eb9
--- /dev/null
+++ b/tests/AccessibilityEventsLogger/src/com/android/tests/accessibilityeventslogger/AELogger.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.tests.accessibilityeventslogger;
+
+import android.accessibilityservice.AccessibilityService;
+import android.accessibilityservice.AccessibilityServiceInfo;
+import android.util.Log;
+import android.view.accessibility.AccessibilityEvent;
+import android.widget.Toast;
+
+import java.util.Locale;
+
+public class AELogger extends AccessibilityService {
+    private static final String TAG = AELogger.class.getCanonicalName();
+
+    private static final int TOAST_EVENT_TYPES =
+            AccessibilityEvent.TYPE_VIEW_CLICKED | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED;
+
+    @Override
+    public void onServiceConnected() {
+      super.onServiceConnected();
+      Log.v(TAG, "Service connected.");
+    }
+
+
+    @Override
+    public void onInterrupt() {
+        // Do nothing
+    }
+
+    @Override
+    public void onAccessibilityEvent(AccessibilityEvent event) {
+        final String eventClass = event.getClassName().toString();
+        final String eventText = String.valueOf(event.getText()).toLowerCase(Locale.getDefault());
+        final String eventType = AccessibilityEvent.eventTypeToString(event.getEventType());
+
+        Log.d(TAG, String.format(
+                    "typ=%s cls=%s pkg=%s txt=%s dsc=%s",
+                    eventType,
+                    eventClass,
+                    event.getPackageName(),
+                    eventText,
+                    event.getContentDescription()
+                    ));
+
+        // Show selected event types
+        if (0 != (TOAST_EVENT_TYPES & event.getEventType())) {
+            final Toast toast = Toast.makeText(this,
+                    eventType + ": " + eventClass, Toast.LENGTH_SHORT);
+            toast.show();
+        }
+    }
+}
diff --git a/tests/Assist/src/com/android/test/assist/AssistInteractionSession.java b/tests/Assist/src/com/android/test/assist/AssistInteractionSession.java
index 43f1e32..851bda9 100644
--- a/tests/Assist/src/com/android/test/assist/AssistInteractionSession.java
+++ b/tests/Assist/src/com/android/test/assist/AssistInteractionSession.java
@@ -24,6 +24,7 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.service.voice.VoiceInteractionSession;
+import android.util.Log;
 import android.view.View;
 import android.view.ViewAnimationUtils;
 import android.view.ViewTreeObserver;
@@ -69,6 +70,7 @@
 
     @Override
     public void onCreate() {
+        super.onCreate();
         // Simulate slowness of Assist app
         try {
             Thread.sleep(1000);
@@ -105,6 +107,12 @@
         }
     }
 
+    @Override
+    public void onLockscreenShown() {
+        super.onLockscreenShown();
+        Log.i("Assistant", "Lockscreen was shown");
+    }
+
     private void playAssistAnimation() {
         Interpolator linearOutSlowIn = AnimationUtils.loadInterpolator(mBackground.getContext(),
                 android.R.interpolator.linear_out_slow_in);
diff --git a/tests/VectorDrawableTest/src/com/android/test/dynamic/ScaleDrawableTests.java b/tests/VectorDrawableTest/src/com/android/test/dynamic/ScaleDrawableTests.java
index 3787843..c5be6c4 100644
--- a/tests/VectorDrawableTest/src/com/android/test/dynamic/ScaleDrawableTests.java
+++ b/tests/VectorDrawableTest/src/com/android/test/dynamic/ScaleDrawableTests.java
@@ -37,8 +37,8 @@
     };
 
     protected int icon = R.drawable.bitmap_drawable01;
-
     protected int vector_icon = R.drawable.vector_drawable16;
+    protected int animated_vector_icon = R.drawable.ic_hourglass_animation;
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
@@ -46,12 +46,12 @@
         ScrollView scrollView = new ScrollView(this);
         GridLayout container = new GridLayout(this);
         scrollView.addView(container);
-        container.setColumnCount(3);
+        container.setColumnCount(4);
         container.setBackgroundColor(0xFF888888);
 
         LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
-        params.width = 400;
-        params.height = 300;
+        params.width = 300;
+        params.height = 200;
 
         for (int i = 0; i < scaleTypes.length; i++) {
             TextView t = new TextView(this);
@@ -71,6 +71,13 @@
             view.setScaleType(scaleType);
             view.setImageResource(vector_icon);
             container.addView(view);
+
+            ImageView avd_view = new ImageView(this);
+            avd_view.setLayoutParams(params);
+            avd_view.setScaleType(scaleType);
+            avd_view.setImageResource(animated_vector_icon);
+            container.addView(avd_view);
+
         }
 
         setContentView(scrollView);
diff --git a/tests/VoiceInteraction/res/layout/voice_interaction_session.xml b/tests/VoiceInteraction/res/layout/voice_interaction_session.xml
index 610f30b..b106437 100644
--- a/tests/VoiceInteraction/res/layout/voice_interaction_session.xml
+++ b/tests/VoiceInteraction/res/layout/voice_interaction_session.xml
@@ -31,33 +31,62 @@
         android:layout_height="match_parent"
         android:fitsSystemWindows="true">
 
-        <LinearLayout android:id="@+id/top_content"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:layout_gravity="top"
-            android:orientation="horizontal"
-            android:background="#ffffffff"
-            android:elevation="8dp"
-            >
-            <ImageView android:id="@+id/screenshot"
-                android:layout_width="wrap_content"
-                android:layout_height="46dp"
-                android:adjustViewBounds="true" />
-            <View android:layout_width="0dp"
-                android:layout_height="0dp"
-                android:layout_weight="1" />
-            <Button android:id="@+id/do_tree"
-                android:layout_width="wrap_content"
+        <LinearLayout
+                android:layout_width="match_parent"
                 android:layout_height="wrap_content"
-                android:text="@string/tree" />
-            <Button android:id="@+id/do_text"
-                android:layout_width="wrap_content"
+                android:layout_gravity="top"
+                android:orientation="vertical"
+                android:background="#ffffffff"
+                android:elevation="8dp"
+                >
+            <LinearLayout android:id="@+id/top_content"
+                android:layout_width="match_parent"
                 android:layout_height="wrap_content"
-                android:text="@string/text" />
-            <Button android:id="@+id/start"
-                android:layout_width="wrap_content"
+                android:orientation="horizontal"
+                >
+                <ImageView android:id="@+id/screenshot"
+                    android:layout_width="wrap_content"
+                    android:layout_height="46dp"
+                    android:adjustViewBounds="true" />
+                <View android:layout_width="0dp"
+                    android:layout_height="0dp"
+                    android:layout_weight="1" />
+                <CheckBox android:id="@+id/show_options"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content" />
+                <Button android:id="@+id/do_tree"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:text="@string/tree" />
+                <Button android:id="@+id/do_text"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:text="@string/text" />
+                <Button android:id="@+id/start"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:text="@string/start" />
+            </LinearLayout>
+            <LinearLayout android:id="@+id/options"
+                android:layout_width="match_parent"
                 android:layout_height="wrap_content"
-                android:text="@string/start" />
+                android:orientation="vertical"
+                >
+                <CheckBox android:id="@+id/disallow_structure"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:text="Disallow context" />
+                <CheckBox android:id="@+id/disallow_screenshot"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:text="Disallow screenshot" />
+                <TextView android:id="@+id/options_text"
+                    android:layout_width="match_parent"
+                    android:layout_height="wrap_content"
+                    android:layout_marginTop="16dp"
+                    android:layout_marginBottom="16dp"
+                    android:textAppearance="?android:attr/textAppearanceMedium" />
+            </LinearLayout>
         </LinearLayout>
 
         <LinearLayout android:id="@+id/bottom_content"
diff --git a/tests/VoiceInteraction/src/com/android/test/voiceinteraction/MainInteractionService.java b/tests/VoiceInteraction/src/com/android/test/voiceinteraction/MainInteractionService.java
index 8381aa1..f1dd1de 100644
--- a/tests/VoiceInteraction/src/com/android/test/voiceinteraction/MainInteractionService.java
+++ b/tests/VoiceInteraction/src/com/android/test/voiceinteraction/MainInteractionService.java
@@ -74,21 +74,6 @@
                 "Hello There", Locale.forLanguageTag("en-US"), mHotwordCallback);
     }
 
-    @Override
-    public int onStartCommand(Intent intent, int flags, int startId) {
-        if (isActiveService(this, new ComponentName(this, getClass()))) {
-            Bundle args = new Bundle();
-            args.putParcelable("intent", new Intent(this, TestInteractionActivity.class));
-            args.putBundle("assist", intent.getExtras());
-            showSession(args, VoiceInteractionSession.SHOW_WITH_ASSIST
-                    | VoiceInteractionSession.SHOW_WITH_SCREENSHOT);
-        } else {
-            Log.w(TAG, "Not starting -- not current voice interaction service");
-        }
-        stopSelf(startId);
-        return START_NOT_STICKY;
-    }
-
     private void hotwordAvailabilityChangeHelper(int availability) {
         Log.i(TAG, "Hotword availability = " + availability);
         switch (availability) {
diff --git a/tests/VoiceInteraction/src/com/android/test/voiceinteraction/MainInteractionSession.java b/tests/VoiceInteraction/src/com/android/test/voiceinteraction/MainInteractionSession.java
index a6585ba..c0a67c1 100644
--- a/tests/VoiceInteraction/src/com/android/test/voiceinteraction/MainInteractionSession.java
+++ b/tests/VoiceInteraction/src/com/android/test/voiceinteraction/MainInteractionSession.java
@@ -29,6 +29,7 @@
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
+import android.widget.CheckBox;
 import android.widget.ImageView;
 import android.widget.TextView;
 
@@ -45,6 +46,11 @@
     Button mTreeButton;
     Button mTextButton;
     Button mStartButton;
+    CheckBox mOptionsCheck;
+    View mOptionsContainer;
+    CheckBox mDisallowAssist;
+    CheckBox mDisallowScreenshot;
+    TextView mOptionsText;
     ImageView mScreenshot;
     ImageView mFullScreenshot;
     Button mConfirmButton;
@@ -81,8 +87,9 @@
     @Override
     public void onShow(Bundle args, int showFlags) {
         super.onShow(args, showFlags);
+        Log.i(TAG, "onShow: flags=0x" + Integer.toHexString(showFlags) + " args=" + args);
         mState = STATE_IDLE;
-        mStartIntent = args.getParcelable("intent");
+        mStartIntent = args != null ? (Intent)args.getParcelable("intent") : null;
         if (mStartIntent == null) {
             mStartIntent = new Intent(getContext(), TestInteractionActivity.class);
         }
@@ -91,6 +98,7 @@
         }
         onHandleScreenshot(null);
         updateState();
+        refreshOptions();
     }
 
     @Override
@@ -122,15 +130,39 @@
         mScreenshot = (ImageView)mContentView.findViewById(R.id.screenshot);
         mScreenshot.setOnClickListener(this);
         mFullScreenshot = (ImageView)mContentView.findViewById(R.id.full_screenshot);
+        mOptionsCheck = (CheckBox)mContentView.findViewById(R.id.show_options);
+        mOptionsCheck.setOnClickListener(this);
+        mOptionsContainer = mContentView.findViewById(R.id.options);
+        mDisallowAssist = (CheckBox)mContentView.findViewById(R.id.disallow_structure);
+        mDisallowAssist.setOnClickListener(this);
+        mDisallowScreenshot = (CheckBox)mContentView.findViewById(R.id.disallow_screenshot);
+        mDisallowScreenshot.setOnClickListener(this);
+        mOptionsText = (TextView)mContentView.findViewById(R.id.options_text);
         mConfirmButton = (Button)mContentView.findViewById(R.id.confirm);
         mConfirmButton.setOnClickListener(this);
         mCompleteButton = (Button)mContentView.findViewById(R.id.complete);
         mCompleteButton.setOnClickListener(this);
         mAbortButton = (Button)mContentView.findViewById(R.id.abort);
         mAbortButton.setOnClickListener(this);
+        refreshOptions();
         return mContentView;
     }
 
+    void refreshOptions() {
+        if (mOptionsContainer != null) {
+            if (mOptionsCheck.isChecked()) {
+                mOptionsContainer.setVisibility(View.VISIBLE);
+                int flags = getDisabledShowContext();
+                mDisallowAssist.setChecked((flags & SHOW_WITH_ASSIST) != 0);
+                mDisallowScreenshot.setChecked((flags & SHOW_WITH_SCREENSHOT) != 0);
+                int disabled = getUserDisabledShowContext();
+                mOptionsText.setText("Disabled: 0x" + Integer.toHexString(disabled));
+            } else {
+                mOptionsContainer.setVisibility(View.GONE);
+            }
+        }
+    }
+
     public void onHandleAssist(Bundle assistBundle) {
     }
 
@@ -202,6 +234,24 @@
             if (mAssistVisualizer != null) {
                 mAssistVisualizer.logText();
             }
+        } else if (v == mOptionsCheck) {
+            refreshOptions();
+        } else if (v == mDisallowAssist) {
+            int flags = getDisabledShowContext();
+            if (mDisallowAssist.isChecked()) {
+                flags |= SHOW_WITH_ASSIST;
+            } else {
+                flags &= ~SHOW_WITH_ASSIST;
+            }
+            setDisabledShowContext(flags);
+        } else if (v == mDisallowScreenshot) {
+            int flags = getDisabledShowContext();
+            if (mDisallowScreenshot.isChecked()) {
+                flags |= SHOW_WITH_SCREENSHOT;
+            } else {
+                flags &= ~SHOW_WITH_SCREENSHOT;
+            }
+            setDisabledShowContext(flags);
         } else if (v == mStartButton) {
             mState = STATE_LAUNCHING;
             updateState();
diff --git a/tests/VoiceInteraction/src/com/android/test/voiceinteraction/TestInteractionActivity.java b/tests/VoiceInteraction/src/com/android/test/voiceinteraction/TestInteractionActivity.java
index 2487e1ca..e10d89f 100644
--- a/tests/VoiceInteraction/src/com/android/test/voiceinteraction/TestInteractionActivity.java
+++ b/tests/VoiceInteraction/src/com/android/test/voiceinteraction/TestInteractionActivity.java
@@ -16,7 +16,6 @@
 
 package com.android.test.voiceinteraction;
 
-import android.annotation.Nullable;
 import android.app.Activity;
 import android.app.VoiceInteractor;
 import android.content.ComponentName;
@@ -103,6 +102,14 @@
                 }
             };
             mInteractor.submitRequest(mCurrentRequest, REQUEST_CONFIRM);
+            String[] cmds = new String[] {
+                    "com.android.test.voiceinteraction.COMMAND",
+                    "com.example.foo.bar"
+            };
+            boolean sup[] = mInteractor.supportsCommands(cmds);
+            for (int i=0; i<cmds.length; i++) {
+                mLog.append(cmds[i] + ": " + (sup[i] ? "SUPPORTED" : "NOT SUPPORTED") + "\n");
+            }
         } else {
             Log.i(TAG, "Restarting with active confirmation: " + mCurrentRequest);
         }
diff --git a/tests/VoiceInteraction/src/com/android/test/voiceinteraction/VoiceInteractionMain.java b/tests/VoiceInteraction/src/com/android/test/voiceinteraction/VoiceInteractionMain.java
index a7636c3..ee75f28 100644
--- a/tests/VoiceInteraction/src/com/android/test/voiceinteraction/VoiceInteractionMain.java
+++ b/tests/VoiceInteraction/src/com/android/test/voiceinteraction/VoiceInteractionMain.java
@@ -49,7 +49,7 @@
 
     View.OnClickListener mStartListener = new View.OnClickListener() {
         public void onClick(View v) {
-            startService(new Intent(VoiceInteractionMain.this, MainInteractionService.class));
+            showAssist(null);
         }
     };
 }
diff --git a/tools/layoutlib/bridge/src/android/view/BridgeInflater.java b/tools/layoutlib/bridge/src/android/view/BridgeInflater.java
index 20b6e41..1e33e3a 100644
--- a/tools/layoutlib/bridge/src/android/view/BridgeInflater.java
+++ b/tools/layoutlib/bridge/src/android/view/BridgeInflater.java
@@ -25,6 +25,7 @@
 import com.android.layoutlib.bridge.BridgeConstants;
 import com.android.layoutlib.bridge.android.BridgeContext;
 import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
+import com.android.layoutlib.bridge.android.support.DrawerLayoutUtil;
 import com.android.layoutlib.bridge.android.support.RecyclerViewUtil;
 import com.android.layoutlib.bridge.impl.ParserFactory;
 import com.android.layoutlib.bridge.util.ReflectionUtils;
@@ -33,10 +34,13 @@
 
 import org.xmlpull.v1.XmlPullParser;
 
+import android.annotation.NonNull;
 import android.content.Context;
 import android.util.AttributeSet;
 
 import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
 
 import static com.android.layoutlib.bridge.android.BridgeContext.getBaseContext;
 
@@ -48,6 +52,7 @@
     private final LayoutlibCallback mLayoutlibCallback;
     private boolean mIsInMerge = false;
     private ResourceReference mResourceReference;
+    private Map<View, String> mOpenDrawerLayouts;
 
     /**
      * List of class prefixes which are tried first by default.
@@ -256,7 +261,14 @@
                     resourceId = 0;
                 }
                 RecyclerViewUtil.setAdapter(view, bc, mLayoutlibCallback, resourceId);
+            } else if (ReflectionUtils.isInstanceOf(view, DrawerLayoutUtil.CN_DRAWER_LAYOUT)) {
+                String attrVal = attrs.getAttributeValue(BridgeConstants.NS_TOOLS_URI,
+                        BridgeConstants.ATTR_OPEN_DRAWER);
+                if (attrVal != null) {
+                    getDrawerLayoutMap().put(view, attrVal);
+                }
             }
+
         }
     }
 
@@ -312,4 +324,28 @@
 
         return viewKey;
     }
+
+    public void postInflateProcess(View view) {
+        if (mOpenDrawerLayouts != null) {
+            String gravity = mOpenDrawerLayouts.get(view);
+            if (gravity != null) {
+                DrawerLayoutUtil.openDrawer(view, gravity);
+            }
+            mOpenDrawerLayouts.remove(view);
+        }
+    }
+
+    @NonNull
+    private Map<View, String> getDrawerLayoutMap() {
+        if (mOpenDrawerLayouts == null) {
+            mOpenDrawerLayouts = new HashMap<View, String>(4);
+        }
+        return mOpenDrawerLayouts;
+    }
+
+    public void onDoneInflation() {
+        if (mOpenDrawerLayouts != null) {
+            mOpenDrawerLayouts.clear();
+        }
+    }
 }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java
index 661c08b..6228766 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java
@@ -50,6 +50,9 @@
     public final static String FILL_PARENT = "fill_parent";
     public final static String WRAP_CONTENT = "wrap_content";
 
+    // Should be kept in sync with LayoutMetadata.KEY_LV_ITEM in tools/adt/idea
     /** Attribute in the tools namespace used to specify layout manager for RecyclerView. */
-    public static final String ATTR_LIST_ITEM = "list_item";
+    @SuppressWarnings("SpellCheckingInspection")
+    public static final String ATTR_LIST_ITEM = "listitem";
+    public static final String ATTR_OPEN_DRAWER = "openDrawer";
 }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/support/DrawerLayoutUtil.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/support/DrawerLayoutUtil.java
new file mode 100644
index 0000000..40d3811
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/support/DrawerLayoutUtil.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.layoutlib.bridge.android.support;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.util.ReflectionUtils.ReflectionException;
+
+import android.annotation.Nullable;
+import android.view.View;
+
+import static android.view.Gravity.END;
+import static android.view.Gravity.LEFT;
+import static android.view.Gravity.RIGHT;
+import static android.view.Gravity.START;
+import static com.android.layoutlib.bridge.util.ReflectionUtils.getCause;
+import static com.android.layoutlib.bridge.util.ReflectionUtils.getMethod;
+import static com.android.layoutlib.bridge.util.ReflectionUtils.invoke;
+
+public class DrawerLayoutUtil {
+
+    public static final String CN_DRAWER_LAYOUT = "android.support.v4.widget.DrawerLayout";
+
+    public static void openDrawer(View drawerLayout, @Nullable String drawerGravity) {
+        int gravity = -1;
+        if ("left".equals(drawerGravity)) {
+            gravity = LEFT;
+        } else if ("right".equals(drawerGravity)) {
+            gravity = RIGHT;
+        } else if ("start".equals(drawerGravity)) {
+            gravity = START;
+        } else if ("end".equals(drawerGravity)) {
+            gravity = END;
+        }
+        if (gravity > 0) {
+            openDrawer(drawerLayout, gravity);
+        }
+    }
+
+    private static void openDrawer(View drawerLayout, int gravity) {
+        try {
+            invoke(getMethod(drawerLayout.getClass(), "openDrawer", int.class), drawerLayout,
+                    gravity);
+        } catch (ReflectionException e) {
+            Bridge.getLog().error(LayoutLog.TAG_BROKEN, "Unable to open navigation drawer",
+                    getCause(e), null);
+        }
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/support/RecyclerViewUtil.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/support/RecyclerViewUtil.java
index 4182cd9..d14c80b 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/support/RecyclerViewUtil.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/support/RecyclerViewUtil.java
@@ -21,6 +21,7 @@
 import com.android.layoutlib.bridge.Bridge;
 import com.android.layoutlib.bridge.android.BridgeContext;
 import com.android.layoutlib.bridge.android.RenderParamsFlags;
+import com.android.layoutlib.bridge.util.ReflectionUtils;
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -30,6 +31,7 @@
 import java.lang.reflect.Method;
 
 import static com.android.layoutlib.bridge.util.ReflectionUtils.ReflectionException;
+import static com.android.layoutlib.bridge.util.ReflectionUtils.getCause;
 import static com.android.layoutlib.bridge.util.ReflectionUtils.getMethod;
 import static com.android.layoutlib.bridge.util.ReflectionUtils.invoke;
 
@@ -70,11 +72,6 @@
         }
     }
 
-    private static Throwable getCause(Throwable throwable) {
-        Throwable cause = throwable.getCause();
-        return cause == null ? throwable : cause;
-    }
-
     private static void setLayoutManager(@NonNull View recyclerView, @NonNull BridgeContext context,
             @NonNull LayoutlibCallback callback) throws ReflectionException {
         if (getLayoutManager(recyclerView) == null) {
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java
index 72e97ad..6a9d5dd6 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java
@@ -423,6 +423,7 @@
 
             // post-inflate process. For now this supports TabHost/TabWidget
             postInflateProcess(view, params.getLayoutlibCallback(), isPreference ? view : null);
+            mInflater.onDoneInflation();
 
             setActiveToolbar(view, context, params);
 
@@ -525,6 +526,11 @@
                         if (neededWidth > measuredWidth) {
                             mMeasuredScreenWidth += neededWidth - measuredWidth;
                         }
+                        if (mMeasuredScreenWidth < measuredWidth) {
+                            // If the screen width is less than the exact measured width,
+                            // expand to match.
+                            mMeasuredScreenWidth = measuredWidth;
+                        }
                     }
 
                     if (renderingMode.isVertExpand()) {
@@ -533,6 +539,11 @@
                         if (neededHeight > measuredHeight) {
                             mMeasuredScreenHeight += neededHeight - measuredHeight;
                         }
+                        if (mMeasuredScreenHeight < measuredHeight) {
+                            // If the screen height is less than the exact measured height,
+                            // expand to match.
+                            mMeasuredScreenHeight = measuredHeight;
+                        }
                     }
                 }
             }
@@ -1342,6 +1353,7 @@
                 }
             }
         } else if (view instanceof ViewGroup) {
+            mInflater.postInflateProcess(view);
             ViewGroup group = (ViewGroup) view;
             final int count = group.getChildCount();
             for (int c = 0; c < count; c++) {
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/util/ReflectionUtils.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/util/ReflectionUtils.java
index b78b613..7ce27b6 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/util/ReflectionUtils.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/util/ReflectionUtils.java
@@ -27,7 +27,7 @@
  */
 public class ReflectionUtils {
 
-    @Nullable
+    @NonNull
     public static Method getMethod(@NonNull Class<?> clazz, @NonNull String name,
             @Nullable Class<?>... params) throws ReflectionException {
         try {
@@ -67,6 +67,12 @@
         return false;
     }
 
+    @NonNull
+    public static Throwable getCause(@NonNull Throwable throwable) {
+        Throwable cause = throwable.getCause();
+        return cause == null ? throwable : cause;
+    }
+
     /**
      * Wraps all reflection related exceptions. Created since ReflectiveOperationException was
      * introduced in 1.7 and we are still on 1.6
diff --git a/tools/layoutlib/bridge/tests/res/testApp/MyApplication/build/intermediates/classes/debug/com/android/layoutlib/test/myapplication/R$layout.class b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/build/intermediates/classes/debug/com/android/layoutlib/test/myapplication/R$layout.class
index e172b2d..6c351da 100644
--- a/tools/layoutlib/bridge/tests/res/testApp/MyApplication/build/intermediates/classes/debug/com/android/layoutlib/test/myapplication/R$layout.class
+++ b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/build/intermediates/classes/debug/com/android/layoutlib/test/myapplication/R$layout.class
Binary files differ
diff --git a/tools/layoutlib/bridge/tests/res/testApp/MyApplication/build/intermediates/classes/debug/com/android/layoutlib/test/myapplication/R.class b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/build/intermediates/classes/debug/com/android/layoutlib/test/myapplication/R.class
index d5b81c4..6d7c719 100644
--- a/tools/layoutlib/bridge/tests/res/testApp/MyApplication/build/intermediates/classes/debug/com/android/layoutlib/test/myapplication/R.class
+++ b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/build/intermediates/classes/debug/com/android/layoutlib/test/myapplication/R.class
Binary files differ
diff --git a/tools/layoutlib/bridge/tests/res/testApp/MyApplication/golden/expand_horz_layout.png b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/golden/expand_horz_layout.png
new file mode 100644
index 0000000..92eb3e1
--- /dev/null
+++ b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/golden/expand_horz_layout.png
Binary files differ
diff --git a/tools/layoutlib/bridge/tests/res/testApp/MyApplication/golden/expand_vert_layout.png b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/golden/expand_vert_layout.png
new file mode 100644
index 0000000..81755ce
--- /dev/null
+++ b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/golden/expand_vert_layout.png
Binary files differ
diff --git a/tools/layoutlib/bridge/tests/res/testApp/MyApplication/src/main/res/layout/expand_horz_layout.xml b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/src/main/res/layout/expand_horz_layout.xml
new file mode 100644
index 0000000..2c66b7f
--- /dev/null
+++ b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/src/main/res/layout/expand_horz_layout.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:padding="16dp"
+              android:orientation="horizontal"
+              android:background="#AAAAAA"
+              android:layout_width="wrap_content"
+              android:layout_height="wrap_content">
+
+    <include layout="@layout/expand_layout"
+             android:layout_height="wrap_content"
+             android:layout_width="wrap_content" />
+
+</LinearLayout>
+
diff --git a/tools/layoutlib/bridge/tests/res/testApp/MyApplication/src/main/res/layout/expand_layout.xml b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/src/main/res/layout/expand_layout.xml
new file mode 100644
index 0000000..a255da7
--- /dev/null
+++ b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/src/main/res/layout/expand_layout.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<merge xmlns:android="http://schemas.android.com/apk/res/android">
+    <TextView
+        android:background="#FF0000"
+        android:textSize="200sp"
+        android:layout_width="200dp"
+        android:layout_height="200dp" />
+    <TextView
+        android:background="#00FF00"
+        android:textSize="200sp"
+        android:layout_width="200dp"
+        android:layout_height="200dp" />
+    <TextView
+        android:background="#0000FF"
+        android:textSize="200sp"
+        android:layout_width="200dp"
+        android:layout_height="200dp" />
+    <TextView
+        android:background="#FF00FF"
+        android:textSize="200sp"
+        android:layout_width="200dp"
+        android:layout_height="200dp" />
+    <TextView
+        android:background="#00FFFF"
+        android:textSize="200sp"
+        android:layout_width="200dp"
+        android:layout_height="200dp" />
+</merge>
diff --git a/tools/layoutlib/bridge/tests/res/testApp/MyApplication/src/main/res/layout/expand_vert_layout.xml b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/src/main/res/layout/expand_vert_layout.xml
new file mode 100644
index 0000000..5319654
--- /dev/null
+++ b/tools/layoutlib/bridge/tests/res/testApp/MyApplication/src/main/res/layout/expand_vert_layout.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              android:padding="16dp"
+              android:orientation="vertical"
+              android:background="#AAAAAA"
+              android:layout_width="wrap_content"
+              android:layout_height="wrap_content">
+
+    <include layout="@layout/expand_layout"
+             android:layout_height="wrap_content"
+             android:layout_width="wrap_content" />
+
+</LinearLayout>
+
diff --git a/tools/layoutlib/bridge/tests/src/com/android/layoutlib/bridge/intensive/Main.java b/tools/layoutlib/bridge/tests/src/com/android/layoutlib/bridge/intensive/Main.java
index 272a2b8..b2909c9 100644
--- a/tools/layoutlib/bridge/tests/src/com/android/layoutlib/bridge/intensive/Main.java
+++ b/tools/layoutlib/bridge/tests/src/com/android/layoutlib/bridge/intensive/Main.java
@@ -31,6 +31,8 @@
 import com.android.layoutlib.bridge.intensive.setup.ConfigGenerator;
 import com.android.layoutlib.bridge.intensive.setup.LayoutLibTestCallback;
 import com.android.layoutlib.bridge.intensive.setup.LayoutPullParser;
+import com.android.resources.Density;
+import com.android.resources.Navigation;
 import com.android.utils.ILogger;
 
 import org.junit.AfterClass;
@@ -310,21 +312,52 @@
         sBridge = null;
     }
 
+    /** Test expand_layout.xml */
+    @Test
+    public void testExpand() throws ClassNotFoundException {
+        // Create the layout pull parser.
+        LayoutPullParser parser = new LayoutPullParser(APP_TEST_RES + "/layout/" +
+                "expand_vert_layout.xml");
+        // Create LayoutLibCallback.
+        LayoutLibTestCallback layoutLibCallback = new LayoutLibTestCallback(getLogger());
+        layoutLibCallback.initResources();
+
+        ConfigGenerator customConfigGenerator = new ConfigGenerator()
+                .setScreenWidth(300)
+                .setScreenHeight(20)
+                .setDensity(Density.XHIGH)
+                .setNavigation(Navigation.NONAV);
+
+        SessionParams params = getSessionParams(parser, customConfigGenerator,
+                layoutLibCallback, "Theme.Material.NoActionBar.Fullscreen", RenderingMode.V_SCROLL,
+                22);
+
+        renderAndVerify(params, "expand_vert_layout.png");
+
+        customConfigGenerator = new ConfigGenerator()
+                .setScreenWidth(20)
+                .setScreenHeight(300)
+                .setDensity(Density.XHIGH)
+                .setNavigation(Navigation.NONAV);
+        parser = new LayoutPullParser(APP_TEST_RES + "/layout/" +
+                "expand_horz_layout.xml");
+        params = getSessionParams(parser, customConfigGenerator,
+                layoutLibCallback, "Theme.Material.NoActionBar.Fullscreen", RenderingMode
+                        .H_SCROLL, 22);
+
+        renderAndVerify(params, "expand_horz_layout.png");
+    }
+
     /**
      * Create a new rendering session and test that rendering given layout on nexus 5
      * doesn't throw any exceptions and matches the provided image.
      */
-    private void renderAndVerify(String layoutFileName, String goldenFileName)
+    private void renderAndVerify(SessionParams params, String goldenFileName)
             throws ClassNotFoundException {
-        // Create the layout pull parser.
-        LayoutPullParser parser = new LayoutPullParser(APP_TEST_RES + "/layout/" + layoutFileName);
-        // Create LayoutLibCallback.
-        LayoutLibTestCallback layoutLibCallback = new LayoutLibTestCallback(getLogger());
-        layoutLibCallback.initResources();
         // TODO: Set up action bar handler properly to test menu rendering.
         // Create session params.
-        SessionParams params = getSessionParams(parser, ConfigGenerator.NEXUS_5, layoutLibCallback);
         RenderSession session = sBridge.createSession(params);
+
         if (!session.getResult().isSuccess()) {
             getLogger().error(session.getResult().getException(),
                     session.getResult().getErrorMessage());
@@ -344,25 +377,44 @@
     }
 
     /**
+     * Create a new rendering session and test that rendering given layout on nexus 5
+     * doesn't throw any exceptions and matches the provided image.
+     */
+    private void renderAndVerify(String layoutFileName, String goldenFileName)
+            throws ClassNotFoundException {
+        // Create the layout pull parser.
+        LayoutPullParser parser = new LayoutPullParser(APP_TEST_RES + "/layout/" + layoutFileName);
+        // Create LayoutLibCallback.
+        LayoutLibTestCallback layoutLibCallback = new LayoutLibTestCallback(getLogger());
+        layoutLibCallback.initResources();
+        // TODO: Set up action bar handler properly to test menu rendering.
+        // Create session params.
+        SessionParams params = getSessionParams(parser, ConfigGenerator.NEXUS_5,
+                layoutLibCallback, "Theme.Material.Light.DarkActionBar", RenderingMode.NORMAL, 22);
+        renderAndVerify(params, goldenFileName);
+    }
+
+    /**
      * Uses Theme.Material and Target sdk version as 22.
      */
     private SessionParams getSessionParams(LayoutPullParser layoutParser,
-            ConfigGenerator configGenerator, LayoutLibTestCallback layoutLibCallback) {
+            ConfigGenerator configGenerator, LayoutLibTestCallback layoutLibCallback,
+            String themeName, RenderingMode renderingMode, int targetSdk) {
         FolderConfiguration config = configGenerator.getFolderConfig();
         ResourceResolver resourceResolver =
                 ResourceResolver.create(sProjectResources.getConfiguredResources(config),
                         sFrameworkRepo.getConfiguredResources(config),
-                        "AppTheme", true);
+                        themeName, true);
 
         return new SessionParams(
                 layoutParser,
-                RenderingMode.NORMAL,
+                renderingMode,
                 null /*used for caching*/,
                 configGenerator.getHardwareConfig(),
                 resourceResolver,
                 layoutLibCallback,
                 0,
-                22, // TODO: Make it more configurable to run tests for various versions.
+                targetSdk,
                 getLayoutLog());
     }
 
diff --git a/wifi/java/android/net/wifi/IWifiManager.aidl b/wifi/java/android/net/wifi/IWifiManager.aidl
index b2af044..0d95b38 100644
--- a/wifi/java/android/net/wifi/IWifiManager.aidl
+++ b/wifi/java/android/net/wifi/IWifiManager.aidl
@@ -158,15 +158,12 @@
     void setAllowScansWithTraffic(int enabled);
     int getAllowScansWithTraffic();
 
-    void setAllowScansWhileAssociated(int enabled);
-    int getAllowScansWhileAssociated();
-
-    void setAllowNetworkSwitchingWhileAssociated(int enabled);
-    int getAllowNetworkSwitchingWhileAssociated();
-
     void setHalBasedAutojoinOffload(int enabled);
     int getHalBasedAutojoinOffload();
 
+    boolean enableAutoJoinWhenAssociated(boolean enabled);
+    boolean getEnableAutoJoinWhenAssociated();
+
     WifiConnectionStatistics getConnectionStatistics();
 
     void disableEphemeralNetwork(String SSID);
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index f91e0e2..f390075 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -2807,30 +2807,6 @@
     }
 
     /**
-     * Set setting for allowing Scans when infrastructure is associated
-     * @hide
-     */
-    public void setAllowScansWhileAssociated(int enabled) {
-        try {
-            mService.setAllowScansWhileAssociated(enabled);
-        } catch (RemoteException e) {
-
-        }
-    }
-
-    /**
-     * Get setting for allowing Scans when infrastructure is associated
-     * @hide
-     */
-    public int getAllowScansWhileAssociated() {
-        try {
-            return mService.getAllowScansWhileAssociated();
-        } catch (RemoteException e) {
-        }
-        return 0;
-    }
-
-    /**
      * Resets all wifi manager settings back to factory defaults.
      *
      * @hide
@@ -2856,6 +2832,31 @@
     }
 
     /**
+     * Framework layer autojoin enable/disable when device is associated
+     * this will enable/disable autojoin scan and switch network when connected
+     * @return true -- if set successful false -- if set failed
+     * @hide
+     */
+    public boolean enableAutoJoinWhenAssociated(boolean enabled) {
+        try {
+            return mService.enableAutoJoinWhenAssociated(enabled);
+        } catch (RemoteException e) {
+            return false;
+        }
+    }
+
+    /**
+     * Get setting for Framework layer autojoin enable status
+     * @hide
+     */
+    public boolean getEnableAutoJoinWhenAssociated() {
+        try {
+            return mService.getEnableAutoJoinWhenAssociated();
+        } catch (RemoteException e) {
+            return false;
+        }
+    }
+    /**
      * Set setting for enabling autojoin Offload thru Wifi HAL layer
      * @hide
      */
@@ -2878,28 +2879,4 @@
         }
         return 0;
     }
-
-    /**
-     * Set setting for enabling network switching while wifi is associated
-     * @hide
-     */
-    public void setAllowNetworkSwitchingWhileAssociated(int enabled) {
-        try {
-            mService.setAllowNetworkSwitchingWhileAssociated(enabled);
-        } catch (RemoteException e) {
-
-        }
-    }
-
-    /**
-     * Get setting for enabling network switching while wifi is associated
-     * @hide
-     */
-    public int getAllowNetworkSwitchingWhileAssociated() {
-        try {
-            return mService.getAllowNetworkSwitchingWhileAssociated();
-        } catch (RemoteException e) {
-        }
-        return 0;
-    }
 }