Merge "UICC : discard language setting of SIM" into mnc-dev
diff --git a/Android.mk b/Android.mk
index 121bc8e..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 \
diff --git a/api/current.txt b/api/current.txt
index 4a7dc82..462ca0a 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -66,6 +66,7 @@
     field public static final java.lang.String FACTORY_TEST = "android.permission.FACTORY_TEST";
     field public static final java.lang.String FLASHLIGHT = "android.permission.FLASHLIGHT";
     field public static final java.lang.String GET_ACCOUNTS = "android.permission.GET_ACCOUNTS";
+    field public static final java.lang.String GET_ACCOUNTS_PRIVILEGED = "android.permission.GET_ACCOUNTS_PRIVILEGED";
     field public static final java.lang.String GET_PACKAGE_SIZE = "android.permission.GET_PACKAGE_SIZE";
     field public static final deprecated java.lang.String GET_TASKS = "android.permission.GET_TASKS";
     field public static final java.lang.String GLOBAL_SEARCH = "android.permission.GLOBAL_SEARCH";
@@ -3466,6 +3467,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 +3865,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 {
@@ -9442,6 +9446,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
@@ -28806,6 +28811,7 @@
     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);
@@ -28821,6 +28827,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);
@@ -28841,6 +28848,7 @@
     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
@@ -28893,6 +28901,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 e83f8c6..d6e3c03 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -95,6 +95,7 @@
     field public static final java.lang.String FORCE_BACK = "android.permission.FORCE_BACK";
     field public static final java.lang.String FORCE_STOP_PACKAGES = "android.permission.FORCE_STOP_PACKAGES";
     field public static final java.lang.String GET_ACCOUNTS = "android.permission.GET_ACCOUNTS";
+    field public static final java.lang.String GET_ACCOUNTS_PRIVILEGED = "android.permission.GET_ACCOUNTS_PRIVILEGED";
     field public static final java.lang.String GET_APP_OPS_STATS = "android.permission.GET_APP_OPS_STATS";
     field public static final java.lang.String GET_PACKAGE_IMPORTANCE = "android.permission.GET_PACKAGE_IMPORTANCE";
     field public static final java.lang.String GET_PACKAGE_SIZE = "android.permission.GET_PACKAGE_SIZE";
@@ -3569,6 +3570,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();
@@ -3975,12 +3977,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 {
@@ -9780,6 +9784,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
@@ -30958,6 +30963,7 @@
     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);
@@ -30973,6 +30979,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);
@@ -30993,6 +31000,7 @@
     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
@@ -31045,6 +31053,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/cmds/wm/src/com/android/commands/wm/Wm.java b/cmds/wm/src/com/android/commands/wm/Wm.java
index fb050e5..f7f7c88 100644
--- a/cmds/wm/src/com/android/commands/wm/Wm.java
+++ b/cmds/wm/src/com/android/commands/wm/Wm.java
@@ -65,7 +65,10 @@
                 "\n" +
                 "wm scaling: set display scaling mode.\n" +
                 "\n" +
-                "wm screen-capture: enable/disable screen capture.\n"
+                "wm screen-capture: enable/disable screen capture.\n" +
+                "\n" +
+                "wm dismiss-keyguard: dismiss the keyguard, prompting the user for auth if " +
+                "necessary.\n"
                 );
     }
 
@@ -90,6 +93,8 @@
             runDisplayScaling();
         } else if (op.equals("screen-capture")) {
             runSetScreenCapture();
+        } else if (op.equals("dismiss-keyguard")) {
+            runDismissKeyguard();
         } else {
             showError("Error: unknown command '" + op + "'");
             return;
@@ -240,6 +245,10 @@
         }
     }
 
+    private void runDismissKeyguard() throws Exception {
+        mWm.dismissKeyguard();
+    }
+
     private int parseDimension(String s) throws NumberFormatException {
         if (s.endsWith("px")) {
             return Integer.parseInt(s.substring(0, s.length() - 2));
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index e782fb8..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.
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 bfb92c4..b758a7a 100644
--- a/core/java/android/app/ActivityManagerNative.java
+++ b/core/java/android/app/ActivityManagerNative.java
@@ -2193,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;
         }
 
@@ -2225,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;
@@ -5377,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,
@@ -5429,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);
@@ -5441,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 08e1696..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,
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/IActivityManager.java b/core/java/android/app/IActivityManager.java
index 5eb3961..9ebbb9b 100644
--- a/core/java/android/app/IActivityManager.java
+++ b/core/java/android/app/IActivityManager.java
@@ -434,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;
@@ -443,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;
 
@@ -858,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/IUiAutomationConnection.aidl b/core/java/android/app/IUiAutomationConnection.aidl
index 8ab9ac3..474154b 100644
--- a/core/java/android/app/IUiAutomationConnection.aidl
+++ b/core/java/android/app/IUiAutomationConnection.aidl
@@ -38,10 +38,12 @@
     boolean injectInputEvent(in InputEvent event, boolean sync);
     boolean setRotation(int rotation);
     Bitmap takeScreenshot(int width, int height);
-    void shutdown();
     boolean clearWindowContentFrameStats(int windowId);
     WindowContentFrameStats getWindowContentFrameStats(int windowId);
     void clearWindowAnimationFrameStats();
     WindowAnimationFrameStats getWindowAnimationFrameStats();
     void executeShellCommand(String command, in ParcelFileDescriptor fd);
+
+    // Called from the system process.
+    oneway void shutdown();
 }
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 40126d6..ee0fc91 100644
--- a/core/java/android/app/assist/AssistStructure.java
+++ b/core/java/android/app/assist/AssistStructure.java
@@ -4,6 +4,7 @@
 import android.content.ComponentName;
 import android.graphics.Matrix;
 import android.graphics.Rect;
+import android.os.BadParcelableException;
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.IBinder;
@@ -31,8 +32,12 @@
     static final String TAG = "AssistStructure";
 
     static final boolean DEBUG_PARCEL = false;
+    static final boolean DEBUG_PARCEL_CHILDREN = false;
     static final boolean DEBUG_PARCEL_TREE = false;
 
+    static final int VALIDATE_WINDOW_TOKEN = 0x11111111;
+    static final int VALIDATE_VIEW_TOKEN = 0x22222222;
+
     boolean mHaveData;
 
     ComponentName mActivityComponent;
@@ -173,6 +178,26 @@
             mCurViewStackEntry = entry;
         }
 
+        void writeView(ViewNode child, Parcel out, PooledStringWriter pwriter, int levelAdj) {
+            if (DEBUG_PARCEL) Log.d(TAG, "write view: at " + out.dataPosition()
+                    + ", windows=" + mNumWrittenWindows
+                    + ", views=" + mNumWrittenViews
+                    + ", level=" + (mCurViewStackPos+levelAdj));
+            out.writeInt(VALIDATE_VIEW_TOKEN);
+            int flags = child.writeSelfToParcel(out, pwriter, mTmpMatrix);
+            mNumWrittenViews++;
+            // If the child has children, push it on the stack to write them next.
+            if ((flags&ViewNode.FLAGS_HAS_CHILDREN) != 0) {
+                if (DEBUG_PARCEL_TREE || DEBUG_PARCEL_CHILDREN) Log.d(TAG,
+                        "Preparing to write " + child.mChildren.length
+                                + " children: @ #" + mNumWrittenViews
+                                + ", level " + (mCurViewStackPos+levelAdj));
+                out.writeInt(child.mChildren.length);
+                int pos = ++mCurViewStackPos;
+                pushViewStackEntry(child, pos);
+            }
+        }
+
         boolean writeNextEntryToParcel(AssistStructure as, Parcel out, PooledStringWriter pwriter) {
             // Write next view node if appropriate.
             if (mCurViewStackEntry != null) {
@@ -182,20 +207,7 @@
                             + mCurViewStackEntry.curChild + " in " + mCurViewStackEntry.node);
                     ViewNode child = mCurViewStackEntry.node.mChildren[mCurViewStackEntry.curChild];
                     mCurViewStackEntry.curChild++;
-                    if (DEBUG_PARCEL) Log.d(TAG, "write view: at " + out.dataPosition()
-                            + ", windows=" + mNumWrittenWindows
-                            + ", views=" + mNumWrittenViews);
-                    out.writeInt(1);
-                    int flags = child.writeSelfToParcel(out, pwriter, mTmpMatrix);
-                    mNumWrittenViews++;
-                    // If the child has children, push it on the stack to write them next.
-                    if ((flags&ViewNode.FLAGS_HAS_CHILDREN) != 0) {
-                        if (DEBUG_PARCEL_TREE) Log.d(TAG, "Preparing to write "
-                                + child.mChildren.length + " children under " + child);
-                        out.writeInt(child.mChildren.length);
-                        int pos = ++mCurViewStackPos;
-                        pushViewStackEntry(child, pos);
-                    }
+                    writeView(child, out, pwriter, 1);
                     return true;
                 }
 
@@ -223,13 +235,13 @@
                 if (DEBUG_PARCEL) Log.d(TAG, "write window #" + pos + ": at " + out.dataPosition()
                         + ", windows=" + mNumWrittenWindows
                         + ", views=" + mNumWrittenViews);
-                out.writeInt(1);
+                out.writeInt(VALIDATE_WINDOW_TOKEN);
                 win.writeSelfToParcel(out, pwriter, mTmpMatrix);
                 mNumWrittenWindows++;
                 ViewNode root = win.mRoot;
                 mCurViewStackPos = 0;
-                if (DEBUG_PARCEL_TREE) Log.d(TAG, "Pushing initial root view " + root);
-                pushViewStackEntry(root, 0);
+                if (DEBUG_PARCEL_TREE) Log.d(TAG, "Writing initial root view " + root);
+                writeView(root, out, pwriter, 0);
                 return true;
             }
 
@@ -271,11 +283,16 @@
                     + ", views=" + mNumReadViews);
         }
 
-        Parcel readParcel() {
+        Parcel readParcel(int validateToken, int level) {
             if (DEBUG_PARCEL) Log.d(TAG, "readParcel: at " + mCurParcel.dataPosition()
                     + ", avail=" + mCurParcel.dataAvail() + ", windows=" + mNumReadWindows
-                    + ", views=" + mNumReadViews);
-            if (mCurParcel.readInt() != 0) {
+                    + ", views=" + mNumReadViews + ", level=" + level);
+            int token = mCurParcel.readInt();
+            if (token != 0) {
+                if (token != validateToken) {
+                    throw new BadParcelableException("Got token " + Integer.toHexString(token)
+                            + ", expected token " + Integer.toHexString(validateToken));
+                }
                 return mCurParcel;
             }
             // We have run out of partial data, need to read another batch.
@@ -406,7 +423,7 @@
         }
 
         WindowNode(ParcelTransferReader reader) {
-            Parcel in = reader.readParcel();
+            Parcel in = reader.readParcel(VALIDATE_WINDOW_TOKEN, 0);
             reader.mNumReadWindows++;
             mX = in.readInt();
             mY = in.readInt();
@@ -414,7 +431,7 @@
             mHeight = in.readInt();
             mTitle = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
             mDisplayId = in.readInt();
-            mRoot = new ViewNode(reader);
+            mRoot = new ViewNode(reader, 0);
         }
 
         void writeSelfToParcel(Parcel out, PooledStringWriter pwriter, float[] tmpMatrix) {
@@ -548,8 +565,8 @@
         ViewNode() {
         }
 
-        ViewNode(ParcelTransferReader reader) {
-            final Parcel in = reader.readParcel();
+        ViewNode(ParcelTransferReader reader, int nestingLevel) {
+            final Parcel in = reader.readParcel(VALIDATE_VIEW_TOKEN, nestingLevel);
             reader.mNumReadViews++;
             final PooledStringReader preader = reader.mStringReader;
             mClassName = preader.readString();
@@ -604,9 +621,13 @@
             }
             if ((flags&FLAGS_HAS_CHILDREN) != 0) {
                 final int NCHILDREN = in.readInt();
+                if (DEBUG_PARCEL_TREE || DEBUG_PARCEL_CHILDREN) Log.d(TAG,
+                        "Preparing to read " + NCHILDREN
+                                + " children: @ #" + reader.mNumReadViews
+                                + ", level " + nestingLevel);
                 mChildren = new ViewNode[NCHILDREN];
                 for (int i=0; i<NCHILDREN; i++) {
-                    mChildren[i] = new ViewNode(reader);
+                    mChildren[i] = new ViewNode(reader, nestingLevel + 1);
                 }
             }
         }
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/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index ceb610a..bc24d67 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -253,7 +253,7 @@
 
     List<PackageInfo> getPreferredPackages(int flags);
 
-    void resetPreferredActivities(int userId);
+    void resetApplicationPreferences(int userId);
 
     ResolveInfo getLastChosenActivity(in Intent intent,
             String resolvedType, int flags);
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/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/provider/Settings.java b/core/java/android/provider/Settings.java
index fff355b4..a79970c 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -7578,14 +7578,6 @@
         public static final String WFC_IMS_ROAMING_ENABLED = "wfc_ims_roaming_enabled";
 
         /**
-         * Global override to disable VoLTE (independent of user setting)
-         * <p>
-         * Type: int (1 for disable VoLTE, 0 to use user configuration)
-         * @hide
-         */
-        public static final String VOLTE_FEATURE_DISABLED = "volte_feature_disabled";
-
-        /**
          * Whether user can enable/disable LTE as a preferred network. A carrier might control
          * this via gservices, OMA-DM, carrier app, etc.
          * <p>
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/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/VoiceInteractionSession.java b/core/java/android/service/voice/VoiceInteractionSession.java
index 95f96e8..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,6 +679,7 @@
     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
@@ -724,6 +758,10 @@
                     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();
@@ -814,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) {
@@ -936,6 +982,23 @@
     }
 
     /**
+     * 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}.
@@ -1179,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) {
@@ -1233,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/view/inputmethod/InputMethodManagerInternal.java b/core/java/android/view/inputmethod/InputMethodManagerInternal.java
new file mode 100644
index 0000000..c22127b
--- /dev/null
+++ b/core/java/android/view/inputmethod/InputMethodManagerInternal.java
@@ -0,0 +1,30 @@
+/*
+ * 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 android.view.inputmethod;
+
+/**
+ * Input method manager local system service interface.
+ *
+ * @hide Only for use within the system server.
+ */
+public interface InputMethodManagerInternal {
+    /**
+     * Called by the power manager to tell the input method manager whether it
+     * should start watching for wake events.
+     */
+    public void setInteractive(boolean interactive);
+}
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/AppSecurityPermissions.java b/core/java/android/widget/AppSecurityPermissions.java
index e3ce6f2e..a12b15e 100644
--- a/core/java/android/widget/AppSecurityPermissions.java
+++ b/core/java/android/widget/AppSecurityPermissions.java
@@ -533,6 +533,12 @@
             int existingReqFlags) {
         final int base = pInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
         final boolean isNormal = (base == PermissionInfo.PROTECTION_NORMAL);
+
+        // We do not show normal permissions in the UI.
+        if (isNormal) {
+            return false;
+        }
+
         final boolean isDangerous = (base == PermissionInfo.PROTECTION_DANGEROUS)
                 || ((pInfo.protectionLevel&PermissionInfo.PROTECTION_FLAG_PRE23) != 0);
         final boolean isRequired =
@@ -546,7 +552,7 @@
 
         // Dangerous and normal permissions are always shown to the user if the permission
         // is required, or it was previously granted
-        if ((isNormal || isDangerous) && (isRequired || wasGranted || isGranted)) {
+        if (isDangerous && (isRequired || wasGranted || isGranted)) {
             return true;
         }
 
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/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/IVoiceInteractionManagerService.aidl b/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
index 73ad981..1a963f3 100644
--- a/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
+++ b/core/java/com/android/internal/app/IVoiceInteractionManagerService.aidl
@@ -39,6 +39,7 @@
     void finish(IBinder token);
     void setDisabledShowContext(int flags);
     int getDisabledShowContext();
+    int getUserDisabledShowContext();
 
     /**
      * Gets the registered Sound model for keyphrase detection for the current user.
@@ -96,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.
@@ -128,4 +131,9 @@
      * from the lockscreen.
      */
     boolean activeServiceSupportsLaunchFromKeyguard();
+
+    /**
+     * Called when the lockscreen got shown.
+     */
+    void onLockscreenShown();
 }
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/BatteryStatsHelper.java b/core/java/com/android/internal/os/BatteryStatsHelper.java
index 264b8c1..9caf78a 100644
--- a/core/java/com/android/internal/os/BatteryStatsHelper.java
+++ b/core/java/com/android/internal/os/BatteryStatsHelper.java
@@ -47,6 +47,7 @@
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
+import java.util.Locale;
 
 /**
  * A helper class for retrieving the power usage information for all applications and services.
@@ -267,15 +268,20 @@
 
     public static String makemAh(double power) {
         if (power == 0) return "0";
-        else if (power < .00001) return String.format("%.8f", power);
-        else if (power < .0001) return String.format("%.7f", power);
-        else if (power < .001) return String.format("%.6f", power);
-        else if (power < .01) return String.format("%.5f", power);
-        else if (power < .1) return String.format("%.4f", power);
-        else if (power < 1) return String.format("%.3f", power);
-        else if (power < 10) return String.format("%.2f", power);
-        else if (power < 100) return String.format("%.1f", power);
-        else return String.format("%.0f", power);
+
+        final String format;
+        if (power < .00001) format = "%.8f";
+        else if (power < .0001) format = "%.7f";
+        else if (power < .001) format = "%.6f";
+        else if (power < .01) format = "%.5f";
+        else if (power < .1) format = "%.4f";
+        else if (power < 1) format = "%.3f";
+        else if (power < 10) format = "%.2f";
+        else if (power < 100) format = "%.1f";
+        else format = "%.0f";
+
+        // Use English locale because this is never used in UI (only in checkin and dump).
+        return String.format(Locale.ENGLISH, format, power);
     }
 
     /**
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 60f47d6..e7c58f4 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -2560,14 +2560,24 @@
         addHistoryEventLocked(elapsedRealtime, uptime, code, name, uid);
     }
 
+    boolean ensureStartClockTime(final long currentTime) {
+        final long ABOUT_ONE_YEAR = 365*24*60*60*1000L;
+        if (currentTime > ABOUT_ONE_YEAR && mStartClockTime < (currentTime-ABOUT_ONE_YEAR)) {
+            // If the start clock time has changed by more than a year, then presumably
+            // the previous time was completely bogus.  So we are going to figure out a
+            // new time based on how much time has elapsed since we started counting.
+            mStartClockTime = currentTime - (SystemClock.elapsedRealtime()-(mRealtimeStart/1000));
+            return true;
+        }
+        return false;
+    }
+
     public void noteCurrentTimeChangedLocked() {
         final long currentTime = System.currentTimeMillis();
         final long elapsedRealtime = SystemClock.elapsedRealtime();
         final long uptime = SystemClock.uptimeMillis();
         recordCurrentTimeChangeLocked(currentTime, elapsedRealtime, uptime);
-        if (isStartClockTimeValid()) {
-            mStartClockTime = currentTime;
-        }
+        ensureStartClockTime(currentTime);
     }
 
     public void noteProcessStartLocked(String name, int uid) {
@@ -4306,19 +4316,11 @@
         }
     }
 
-    boolean isStartClockTimeValid() {
-        return mStartClockTime > 365*24*60*60*1000L;
-    }
-
     @Override public long getStartClockTime() {
-        if (!isStartClockTimeValid()) {
-            // If the last clock time we got was very small, then we hadn't had a real
-            // time yet, so try to get it again.
-            mStartClockTime = System.currentTimeMillis();
-            if (isStartClockTimeValid()) {
-                recordCurrentTimeChangeLocked(mStartClockTime, SystemClock.elapsedRealtime(),
-                        SystemClock.uptimeMillis());
-            }
+        final long currentTime = System.currentTimeMillis();
+        if (ensureStartClockTime(currentTime)) {
+            recordCurrentTimeChangeLocked(currentTime, SystemClock.elapsedRealtime(),
+                    SystemClock.uptimeMillis());
         }
         return mStartClockTime;
     }
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/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/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 0c0ba7f..3e22e09 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"
@@ -1746,6 +1749,10 @@
     <!-- ==================================== -->
     <eat-comment />
 
+    <!-- @SystemApi Allows access to the list of accounts in the Accounts Service. -->
+    <permission android:name="android.permission.GET_ACCOUNTS_PRIVILEGED"
+        android:protectionLevel="signature|privileged" />
+
     <!-- @SystemApi Allows applications to RW to diagnostic resources.
     <p>Not for use by third-party applications. -->
     <permission android:name="android.permission.DIAGNOSTIC"
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/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-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-es/strings.xml b/core/res/res/values-es/strings.xml
index be2b962..0533317 100644
--- a/core/res/res/values-es/strings.xml
+++ b/core/res/res/values-es/strings.xml
@@ -1001,7 +1001,7 @@
     <string name="sms_short_code_remember_undo_instruction" msgid="4960944133052287484">"Puedes cambiar esta opción más tarde en Ajustes &gt; Aplicaciones."</string>
     <string name="sms_short_code_confirm_always_allow" msgid="3241181154869493368">"Permitir siempre"</string>
     <string name="sms_short_code_confirm_never_allow" msgid="446992765774269673">"No permitir nunca"</string>
-    <string name="sim_removed_title" msgid="6227712319223226185">"Tarjeta SIM eliminada"</string>
+    <string name="sim_removed_title" msgid="6227712319223226185">"Tarjeta SIM retirada"</string>
     <string name="sim_removed_message" msgid="5450336489923274918">"La red móvil no estará disponible hasta que reinicies el dispositivo con una tarjeta SIM válida insertada."</string>
     <string name="sim_done_button" msgid="827949989369963775">"Listo"</string>
     <string name="sim_added_title" msgid="3719670512889674693">"Tarjeta SIM añadida"</string>
diff --git a/core/res/res/values-eu-rES/strings.xml b/core/res/res/values-eu-rES/strings.xml
index 960bc56..93f7523 100644
--- a/core/res/res/values-eu-rES/strings.xml
+++ b/core/res/res/values-eu-rES/strings.xml
@@ -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-pt-rBR/strings.xml b/core/res/res/values-mcc310-mnc260-pt-rBR/strings.xml
new file mode 100644
index 0000000..bad49c3
--- /dev/null
+++ b/core/res/res/values-mcc310-mnc260-pt-rBR/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">"Para fazer chamadas e enviar mensagens por Wi-Fi, primeiro peça à sua operadora para configurar esse serviço. Depois ative novamente as chamadas por Wi-Fi nas configurações."</item>
+  </string-array>
+  <string-array name="wfcOperatorErrorNotificationMessages">
+    <item msgid="483847327467331298">"Faça registro na sua operadora"</item>
+  </string-array>
+    <string name="wfcSpnFormat" msgid="4982938551498609442">"%s chamada Wi-Fi"</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-mn-rMN/strings.xml b/core/res/res/values-mn-rMN/strings.xml
index be72354..df9f2805 100644
--- a/core/res/res/values-mn-rMN/strings.xml
+++ b/core/res/res/values-mn-rMN/strings.xml
@@ -1042,7 +1042,7 @@
     <string name="usb_accessory_notification_title" msgid="7848236974087653666">"USB төхөөрөмжид холбогдов"</string>
     <string name="usb_notification_message" msgid="7347368030849048437">"Нэмэлт сонголтыг харахын тулд дарна."</string>
     <string name="adb_active_notification_title" msgid="6729044778949189918">"USB дебаг холбогдсон"</string>
-    <string name="adb_active_notification_message" msgid="1016654627626476142">"USB дебаг хийхийг идэвхгүй болгох бол хүрнэ үү."</string>
+    <string name="adb_active_notification_message" msgid="1016654627626476142">"USB дебагийг идэвхгүй болгох бол хүрнэ үү."</string>
     <string name="select_input_method" msgid="8547250819326693584">"Гарыг өөрчлөх"</string>
     <string name="configure_input_methods" msgid="4769971288371946846">"Гар сонгох"</string>
     <string name="show_ime" msgid="9157568568695230830">"Оруулах аргыг харуулах"</string>
diff --git a/core/res/res/values-pt-rBR-watch/strings.xml b/core/res/res/values-pt-rBR-watch/strings.xml
new file mode 100644
index 0000000..120e4a5
--- /dev/null
+++ b/core/res/res/values-pt-rBR-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">"App <xliff:g id="NUMBER_0">%1$d</xliff:g> de <xliff:g id="NUMBER_1">%2$d</xliff:g>."</string>
+</resources>
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 9e8bb892..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-sq-rAL/strings.xml b/core/res/res/values-sq-rAL/strings.xml
index 549c5ef7..2bde626 100644
--- a/core/res/res/values-sq-rAL/strings.xml
+++ b/core/res/res/values-sq-rAL/strings.xml
@@ -21,7 +21,7 @@
 <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">"kilobajt"</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">"terabajt"</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 a855f2f..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>
 
@@ -2261,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 3695cf6..8070986 100755
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -337,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" />
 
@@ -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/training/articles/keystore.jd b/docs/html/training/articles/keystore.jd
index 52cb13e..aa1ed0a 100644
--- a/docs/html/training/articles/keystore.jd
+++ b/docs/html/training/articles/keystore.jd
@@ -7,14 +7,15 @@
     <ol>
       <li><a href="#SecurityFeatures">Security Features</a></li>
       <li><a href="#WhichShouldIUse">Choosing Between a Keychain or the Android Keystore Provider</a></li>
-      <li><a href="#UsingAndroidKeyStore">Using Android Keystore Provider
-      </a></li>
+      <li><a href="#UsingAndroidKeyStore">Using Android Keystore Provider</a>
       <ol>
         <li><a href="#GeneratingANewPrivateKey">Generating a New Private Key</a></li>
         <li><a href="#WorkingWithKeyStoreEntries">Working with Keystore Entries</a></li>
         <li><a href="#ListingEntries">Listing Entries</a></li>
         <li><a href="#SigningAndVerifyingData">Signing and Verifying Data</a></li>
       </ol>
+      </li>
+      <li><a href="#SupportedAlgorithms">Supported Algorithms</a></li>
     </ol>
 
     <h2>Blog articles</h2>
@@ -27,6 +28,14 @@
   </div>
 </div>
 
+<style type="text/css">
+  tr.deprecated {
+    background-color: #ccc;
+    color: #999;
+    font-style: italic;
+  }
+</style>
+
 <p>The Android Keystore system lets you store cryptographic keys in a container
   to make it more difficult to extract from the device. Once keys are in the
   keystore, they can be used for cryptographic operations with the key material
@@ -213,4 +222,456 @@
   {@link android.hardware.fingerprint.FingerprintManager#hasEnrolledFingerprints() FingerprintManager.hasEnrolledFingerprints}).
   These keys become permanently invalidated once a new fingerprint is enrolled or all fingerprints
   are unenrolled.</li>
-</ul>
\ No newline at end of file
+</ul>
+
+<h2 id="SupportedAlgorithms">Supported Algorithms</h2>
+
+<ul>
+  <li><a href="#SupportedCiphers">{@code Cipher}</a></li>
+  <li><a href="#SupportedKeyGenerators">{@code KeyGenerator}</a></li>
+  <li><a href="#SupportedKeyFactories">{@code KeyFactory}</a></li>
+  <li><a href="#SupportedKeyPairGenerators">{@code KeyPairGenerator}</a></li>
+  <li><a href="#SupportedMacs">{@code Mac}</a></li>
+  <li><a href="#SupportedSignatures">{@code Signature}</a></li>
+  <li><a href="#SupportedSecretKeyFactories">{@code SecretKeyFactory}</a></li>
+</ul>
+
+<h3 id="SupportedCiphers">Cipher</h3>
+<table>
+  <thead>
+    <tr>
+      <th>Algorithm</th>
+      <th>Supported (API Levels)</th>
+      <th>Notes</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>AES/CBC/NoPadding</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>AES/CBC/PKCS7Padding</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>AES/CTR/NoPadding</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>AES/ECB/NoPadding</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>AES/ECB/PKCS7Padding</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>AES/GCM/NoPadding</td>
+      <td>23+</td>
+      <td>Only 12-byte long IVs supported.</td>
+    </tr>
+    <tr>
+      <td>RSA/ECB/NoPadding</td>
+      <td>18+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>RSA/ECB/PKCS1Padding</td>
+      <td>18+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>RSA/ECB/OAEPWithSHA-1AndMGF1Padding</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>RSA/ECB/OAEPWithSHA-224AndMGF1Padding</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>RSA/ECB/OAEPWithSHA-256AndMGF1Padding</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>RSA/ECB/OAEPWithSHA-384AndMGF1Padding</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>RSA/ECB/OAEPWithSHA-512AndMGF1Padding</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>RSA/ECB/OAEPPadding</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+  </tbody>
+</table>
+
+<h3 id="SupportedKeyGenerators">KeyGenerator</h3>
+<table>
+  <thead>
+    <tr>
+      <th>Algorithm</th>
+      <th>Supported (API Levels)</th>
+      <th>Notes</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>AES</td>
+      <td>23+</td>
+      <td>Supported sizes: 128, 192, 256</td>
+    </tr>
+    <tr>
+      <td>HmacSHA1</td>
+      <td>23+</td>
+      <td>
+        <ul>
+          <li>Supported sizes: 8--1024 (inclusive), must be multiple of 8</li>
+          <li>Default size: 160</li>
+        <ul>
+      </td>
+    </tr>
+    <tr>
+      <td>HmacSHA224</td>
+      <td>23+</td>
+      <td>
+        <ul>
+          <li>Supported sizes: 8--1024 (inclusive), must be multiple of 8</li>
+          <li>Default size: 224</li>
+        <ul>
+      </td>
+    </tr>
+    <tr>
+      <td>HmacSHA256</td>
+      <td>23+</td>
+      <td>
+        <ul>
+          <li>Supported sizes: 8--1024 (inclusive), must be multiple of 8</li>
+          <li>Default size: 256</li>
+        <ul>
+      </td>
+    </tr>
+    <tr>
+      <td>HmacSHA384</td>
+      <td>23+</td>
+      <td>
+        <ul>
+          <li>Supported sizes: 8--1024 (inclusive), must be multiple of 8</li>
+          <li>Default size: 384</li>
+        <ul>
+      </td>
+    </tr>
+    <tr>
+      <td>HmacSHA512</td>
+      <td>23+</td>
+      <td>
+        <ul>
+          <li>Supported sizes: 8--1024 (inclusive), must be multiple of 8</li>
+          <li>Default size: 512</li>
+        <ul>
+      </td>
+    </tr>
+  </tbody>
+</table>
+
+<h3 id="SupportedKeyFactories">KeyFactory</h3>
+<table>
+  <thead>
+    <tr>
+      <th>Algorithm</th>
+      <th>Supported (API Levels)</th>
+      <th>Notes</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>EC</td>
+      <td>23+</td>
+      <td>Supported key specs: {@link android.security.keystore.KeyInfo} (private key only),
+        {@link java.security.spec.ECPublicKeySpec} (public key only),
+        {@link java.security.spec.X509EncodedKeySpec} (public key only)
+      </td>
+    </tr>
+    <tr>
+      <td>RSA</td>
+      <td>23+</td>
+      <td>Supported key specs: {@link android.security.keystore.KeyInfo} (private key only),
+        {@link java.security.spec.RSAPublicKeySpec} (public key only),
+        {@link java.security.spec.X509EncodedKeySpec} (public key only)
+      </td>
+    </tr>
+  </tbody>
+</table>
+
+<h3 id="SupportedKeyStoreKeys">KeyStore</h3>
+KeyStore supports the same key types as
+<a href="#SupportedKeyPairGenerators">{@code KeyPairGenerator}</a> and
+<a href="#SupportedKeyGenerators">{@code KeyGenerator}</a>.
+
+<h3 id="SupportedKeyPairGenerators">KeyPairGenerator</h3>
+<table>
+  <thead>
+    <tr>
+      <th>Algorithm</th>
+      <th>Supported (API Levels)</th>
+      <th>Notes</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr class="deprecated">
+      <td>DSA</td>
+      <td>19&ndash;22</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>EC</td>
+      <td>23+</td>
+      <td>
+        <ul>
+          <li>Supported sizes: 224, 256, 384, 521</li>
+          <li>Supported named curves: P-224 (secp256r1), P-256 (aka secp256r1 and prime256v1), P-384
+            (aka secp384r1), P-521 (aka secp521r1)</li>
+        </ul>
+
+        <p>Prior to API Level 23, EC keys can be generated using KeyPairGenerator of algorithm "RSA"
+        initialized {@link android.security.KeyPairGeneratorSpec} whose key type is set to "EC"
+        using {@link android.security.KeyPairGeneratorSpec.Builder#setKeyType(String)}. EC curve
+        name cannot be specified using this method -- a NIST P-curve is automatically chosen based
+        on the requested key size.
+      </td>
+    </tr>
+    <tr>
+      <td>RSA</td>
+      <td>18+</td>
+      <td>
+        <ul>
+          <li>Supported sizes: 512, 768, 1024, 2048, 3072, 4096</li>
+          <li>Supported public exponents: 3, 65537</li>
+          <li>Default public exponent: 65537</li>
+        </ul>
+      </td>
+    </tr>
+  </tbody>
+</table>
+
+<h3 id="SupportedMacs">Mac</h3>
+<table>
+  <thead>
+    <tr>
+      <th>Algorithm</th>
+      <th>Supported (API Levels)</th>
+      <th>Notes</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>HmacSHA1</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>HmacSHA224</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>HmacSHA256</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>HmacSHA384</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>HmacSHA512</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+  </tbody>
+</table>
+
+<h3 id="SupportedSignatures">Signature</h3>
+<table>
+  <thead>
+    <tr>
+      <th>Algorithm</th>
+      <th>Supported (API Levels)</th>
+      <th>Notes</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>MD5withRSA</td>
+      <td>18+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>NONEwithECDSA</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>NONEwithRSA</td>
+      <td>18+</td>
+      <td></td>
+    </tr>
+    <tr class="deprecated">
+      <td>SHA1withDSA</td>
+      <td>19&ndash;22</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA1withECDSA</td>
+      <td>19+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA1withRSA</td>
+      <td>18+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA1withRSA/PSS</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr class="deprecated">
+      <td>SHA224withDSA</td>
+      <td>20&ndash;22</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA224withECDSA</td>
+      <td>20+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA224withRSA</td>
+      <td>20+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA224withRSA/PSS</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr class="deprecated">
+      <td>SHA256withDSA</td>
+      <td>19&ndash;22</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA256withECDSA</td>
+      <td>19+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA256withRSA</td>
+      <td>18+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA256withRSA/PSS</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr class="deprecated">
+      <td>SHA384withDSA</td>
+      <td>19&ndash;22</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA384withECDSA</td>
+      <td>19+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA384withRSA</td>
+      <td>18+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA384withRSA/PSS</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+    <tr class="deprecated">
+      <td>SHA512withDSA</td>
+      <td>19&ndash;22</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA512withECDSA</td>
+      <td>19+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA512withRSA</td>
+      <td>18+</td>
+      <td></td>
+    </tr>
+    <tr>
+      <td>SHA512withRSA/PSS</td>
+      <td>23+</td>
+      <td></td>
+    </tr>
+  </tbody>
+</table>
+
+<h3 id="SupportedSecretKeyFactories">SecretKeyFactory</h3>
+<table>
+  <thead>
+    <tr>
+      <th>Algorithm</th>
+      <th>Supported (API Levels)</th>
+      <th>Notes</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>AES</td>
+      <td>23+</td>
+      <td>Supported key specs: {@link android.security.keystore.KeyInfo}</td>
+    </tr>
+    <tr>
+      <td>HmacSHA1</td>
+      <td>23+</td>
+      <td>Supported key specs: {@link android.security.keystore.KeyInfo}</td>
+    </tr>
+    <tr>
+      <td>HmacSHA224</td>
+      <td>23+</td>
+      <td>Supported key specs: {@link android.security.keystore.KeyInfo}</td>
+    </tr>
+    <tr>
+      <td>HmacSHA256</td>
+      <td>23+</td>
+      <td>Supported key specs: {@link android.security.keystore.KeyInfo}</td>
+    </tr>
+    <tr>
+      <td>HmacSHA384</td>
+      <td>23+</td>
+      <td>Supported key specs: {@link android.security.keystore.KeyInfo}</td>
+    </tr>
+    <tr>
+      <td>HmacSHA512</td>
+      <td>23+</td>
+      <td>Supported key specs: {@link android.security.keystore.KeyInfo}</td>
+    </tr>
+  </tbody>
+</table>
\ No newline at end of file
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 fd014eb..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 {
@@ -272,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 88858de..915d86f 100644
--- a/keystore/java/android/security/keystore/AndroidKeyStoreSpi.java
+++ b/keystore/java/android/security/keystore/AndroidKeyStoreSpi.java
@@ -672,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/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/AnimatorManager.cpp b/libs/hwui/AnimatorManager.cpp
index 966959a..0dababd 100644
--- a/libs/hwui/AnimatorManager.cpp
+++ b/libs/hwui/AnimatorManager.cpp
@@ -117,7 +117,6 @@
 
     uint32_t dirty = animateCommon(info);
 
-    mParent.mProperties.updateMatrix();
     info.damageAccumulator->pushTransform(&mParent);
     mParent.damageSelf(info);
 
@@ -136,6 +135,7 @@
     newEnd = std::remove_if(mAnimators.begin(), mAnimators.end(), functor);
     mAnimators.erase(newEnd, mAnimators.end());
     mAnimationHandle->notifyAnimationsRan();
+    mParent.mProperties.updateMatrix();
     return functor.dirtyMask;
 }
 
diff --git a/libs/hwui/Caches.cpp b/libs/hwui/Caches.cpp
index 1030451..aa73d44 100644
--- a/libs/hwui/Caches.cpp
+++ b/libs/hwui/Caches.cpp
@@ -248,11 +248,6 @@
 void Caches::flush(FlushMode mode) {
     FLUSH_LOGD("Flushing caches (mode %d)", mode);
 
-    // We must stop tasks before clearing caches
-    if (mode > kFlushMode_Layers) {
-        tasks.stop();
-    }
-
     switch (mode) {
         case kFlushMode_Full:
             textureCache.clear();
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/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 2a90087..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;
+        }
     }
 }
 
@@ -189,10 +191,10 @@
     return texture;
 }
 
-bool TextureCache::prefetchAndMarkInUse(const SkBitmap* 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;
 }
diff --git a/libs/hwui/TextureCache.h b/libs/hwui/TextureCache.h
index 83c6e91..7a7ee5a 100644
--- a/libs/hwui/TextureCache.h
+++ b/libs/hwui/TextureCache.h
@@ -66,14 +66,14 @@
     /**
      * 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 from either within the cache, or
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 09f93b8..e472e93 100644
--- a/libs/hwui/renderthread/CanvasContext.cpp
+++ b/libs/hwui/renderthread/CanvasContext.cpp
@@ -178,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);
@@ -369,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/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/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/RingtoneManager.java b/media/java/android/media/RingtoneManager.java
index a1b8a3b..025029e 100644
--- a/media/java/android/media/RingtoneManager.java
+++ b/media/java/android/media/RingtoneManager.java
@@ -23,9 +23,11 @@
 import android.app.Activity;
 import android.content.ContentUris;
 import android.content.Context;
+import android.content.pm.PackageManager;
 import android.database.Cursor;
 import android.net.Uri;
 import android.os.Environment;
+import android.os.Process;
 import android.provider.MediaStore;
 import android.provider.Settings;
 import android.provider.Settings.System;
@@ -359,7 +361,10 @@
      * If {@link RingtoneManager#RingtoneManager(Activity)} was not used, the
      * caller should manage the returned cursor through its activity's life
      * cycle to prevent leaking the cursor.
-     * 
+     * <p>
+     * Note that the list of ringtones available will differ depending on whether the caller
+     * has the {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} permission.
+     *
      * @return A {@link Cursor} of all the ringtones available.
      * @see #ID_COLUMN_INDEX
      * @see #TITLE_COLUMN_INDEX
@@ -455,8 +460,10 @@
 
     /**
      * Returns a valid ringtone URI. No guarantees on which it returns. If it
-     * cannot find one, returns null.
-     * 
+     * cannot find one, returns null. If it can only find one on external storage and the caller
+     * doesn't have the {@link android.Manifest.permission#READ_EXTERNAL_STORAGE} permission,
+     * returns null.
+     *
      * @param context The context to use for querying.
      * @return A ringtone URI, or null if one cannot be found.
      */
@@ -495,6 +502,12 @@
     }
 
     private Cursor getMediaRingtones() {
+        if (PackageManager.PERMISSION_GRANTED != mContext.checkPermission(
+                android.Manifest.permission.READ_EXTERNAL_STORAGE,
+                Process.myPid(), Process.myUid())) {
+            Log.w(TAG, "No READ_EXTERNAL_STORAGE permission, ignoring ringtones on ext storage");
+            return null;
+        }
          // Get the external media cursor. First check to see if it is mounted.
         final String status = Environment.getExternalStorageState();
         
diff --git a/media/java/android/media/tv/TvInputService.java b/media/java/android/media/tv/TvInputService.java
index 35037bb..053d43b6 100644
--- a/media/java/android/media/tv/TvInputService.java
+++ b/media/java/android/media/tv/TvInputService.java
@@ -20,6 +20,7 @@
 import android.annotation.Nullable;
 import android.annotation.SuppressLint;
 import android.annotation.SystemApi;
+import android.app.ActivityManager;
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
@@ -385,13 +386,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);
@@ -1199,12 +1201,15 @@
             // We make the overlay view non-focusable and non-touchable so that
             // the application that owns the window token can decide whether to consume or
             // dispatch the input events.
-            int flag = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
-                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
-                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
+            int flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
+                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
+                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
+            if (ActivityManager.isHighEndGfx()) {
+                flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
+            }
             mWindowParams = new WindowManager.LayoutParams(
                     frame.right - frame.left, frame.bottom - frame.top,
-                    frame.left, frame.top, type, flag, PixelFormat.TRANSPARENT);
+                    frame.left, frame.top, type, flags, PixelFormat.TRANSPARENT);
             mWindowParams.privateFlags |=
                     WindowManager.LayoutParams.PRIVATE_FLAG_NO_MOVE_ANIMATION;
             mWindowParams.gravity = Gravity.START | Gravity.TOP;
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/KeyguardUpdateMonitor.java b/packages/Keyguard/src/com/android/keyguard/KeyguardUpdateMonitor.java
index 9e5644e..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);
         }
@@ -555,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
@@ -741,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...
@@ -819,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/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/keyguard_bottom_area.xml b/packages/SystemUI/res/layout/keyguard_bottom_area.xml
index 1488ad6..444f0f0 100644
--- a/packages/SystemUI/res/layout/keyguard_bottom_area.xml
+++ b/packages/SystemUI/res/layout/keyguard_bottom_area.xml
@@ -26,7 +26,7 @@
 
     <com.android.systemui.statusbar.phone.KeyguardIndicationTextView
         android:id="@+id/keyguard_indication_text"
-        android:layout_width="wrap_content"
+        android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_marginBottom="@dimen/keyguard_indication_margin_bottom"
         android:layout_gravity="bottom|center_horizontal"
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_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 3210a24..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>
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/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/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/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/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/KeyguardAffordanceView.java b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java
index 58fb2b1..164c496 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/KeyguardAffordanceView.java
@@ -69,7 +69,7 @@
     private float mCircleStartValue;
     private boolean mCircleWillBeHidden;
     private int[] mTempPoint = new int[2];
-    private float mImageScale;
+    private float mImageScale = 1f;
     private int mCircleColor;
     private boolean mIsLeft;
     private View mPreviewView;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardAffordanceHelper.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardAffordanceHelper.java
index 6670ae0..10019f9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardAffordanceHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardAffordanceHelper.java
@@ -86,9 +86,9 @@
         mContext = context;
         mCallback = callback;
         initIcons();
-        updateIcon(mLeftIcon, 0.0f, mLeftIcon.getRestingAlpha(), false, false);
-        updateIcon(mCenterIcon, 0.0f, mCenterIcon.getRestingAlpha(), false, false);
-        updateIcon(mRightIcon, 0.0f, mRightIcon.getRestingAlpha(), false, false);
+        updateIcon(mLeftIcon, 0.0f, mLeftIcon.getRestingAlpha(), false, false, true);
+        updateIcon(mCenterIcon, 0.0f, mCenterIcon.getRestingAlpha(), false, false, true);
+        updateIcon(mRightIcon, 0.0f, mRightIcon.getRestingAlpha(), false, false, true);
         initDimens();
     }
 
@@ -387,15 +387,15 @@
             boolean slowAnimation = isReset && isBelowFalsingThreshold();
             if (!isReset) {
                 updateIcon(targetView, radius, alpha + fadeOutAlpha * targetView.getRestingAlpha(),
-                        false, false);
+                        false, false, false);
             } else {
                 updateIcon(targetView, 0.0f, fadeOutAlpha * targetView.getRestingAlpha(),
-                        animateIcons, slowAnimation);
+                        animateIcons, slowAnimation, false);
             }
             updateIcon(otherView, 0.0f, fadeOutAlpha * otherView.getRestingAlpha(),
-                    animateIcons, slowAnimation);
+                    animateIcons, slowAnimation, false);
             updateIcon(mCenterIcon, 0.0f, fadeOutAlpha * mCenterIcon.getRestingAlpha(),
-                    animateIcons, slowAnimation);
+                    animateIcons, slowAnimation, false);
 
             mTranslation = translation;
         }
@@ -431,13 +431,13 @@
 
     public void animateHideLeftRightIcon() {
         cancelAnimation();
-        updateIcon(mRightIcon, 0f, 0f, true, false);
-        updateIcon(mLeftIcon, 0f, 0f, true, false);
+        updateIcon(mRightIcon, 0f, 0f, true, false, false);
+        updateIcon(mLeftIcon, 0f, 0f, true, false, false);
     }
 
     private void updateIcon(KeyguardAffordanceView view, float circleRadius, float alpha,
-            boolean animate, boolean slowRadiusAnimation) {
-        if (view.getVisibility() != View.VISIBLE) {
+            boolean animate, boolean slowRadiusAnimation, boolean force) {
+        if (view.getVisibility() != View.VISIBLE && !force) {
             return;
         }
         view.setCircleRadius(circleRadius, slowRadiusAnimation);
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 91adc460..4558288 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardBottomAreaView.java
@@ -106,6 +106,7 @@
     private PhoneStatusBar mPhoneStatusBar;
 
     private final Interpolator mLinearOutSlowInInterpolator;
+    private boolean mUserSetupComplete;
     private boolean mPrewarmBound;
     private Messenger mPrewarmMessenger;
     private final ServiceConnection mPrewarmConnection = new ServiceConnection() {
@@ -250,6 +251,12 @@
         updateCameraVisibility(); // in case onFinishInflate() was called too early
     }
 
+    public void setUserSetupComplete(boolean userSetupComplete) {
+        mUserSetupComplete = userSetupComplete;
+        updateCameraVisibility();
+        updateLeftAffordanceIcon();
+    }
+
     private Intent getCameraIntent() {
         KeyguardUpdateMonitor updateMonitor = KeyguardUpdateMonitor.getInstance(mContext);
         boolean canSkipBouncer = updateMonitor.getUserCanSkipBouncer(
@@ -267,7 +274,8 @@
                 PackageManager.MATCH_DEFAULT_ONLY,
                 KeyguardUpdateMonitor.getCurrentUser());
         boolean visible = !isCameraDisabledByDpm() && resolved != null
-                && getResources().getBoolean(R.bool.config_keyguardShowCameraAffordance);
+                && getResources().getBoolean(R.bool.config_keyguardShowCameraAffordance)
+                && mUserSetupComplete;
         mCameraImageView.setVisibility(visible ? View.VISIBLE : View.GONE);
     }
 
@@ -275,16 +283,16 @@
         mLeftIsVoiceAssist = canLaunchVoiceAssist();
         int drawableId;
         int contentDescription;
+        boolean visible = mUserSetupComplete;
         if (mLeftIsVoiceAssist) {
-            mLeftAffordanceView.setVisibility(View.VISIBLE);
             drawableId = R.drawable.ic_mic_26dp;
             contentDescription = R.string.accessibility_voice_assist_button;
         } else {
-            boolean visible = isPhoneVisible();
-            mLeftAffordanceView.setVisibility(visible ? View.VISIBLE : View.GONE);
+            visible &= isPhoneVisible();
             drawableId = R.drawable.ic_phone_24dp;
             contentDescription = R.string.accessibility_phone_button;
         }
+        mLeftAffordanceView.setVisibility(visible ? View.VISIBLE : View.GONE);
         mLeftAffordanceView.setImageDrawable(mContext.getDrawable(drawableId));
         mLeftAffordanceView.setContentDescription(mContext.getString(contentDescription));
     }
@@ -641,7 +649,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/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 10191ed..03bdf97 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
@@ -965,6 +965,7 @@
     private void onQsExpansionStarted(int overscrollAmount) {
         cancelQsAnimation();
         cancelHeightAnimator();
+        notifyExpandingFinished();
 
         // Reset scroll position and apply that position to the expanded height.
         float height = mQsExpansionHeight - mScrollView.getScrollY() - overscrollAmount;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
index 889160d..0d20d52 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
@@ -111,7 +111,7 @@
      */
     private float mNextCollapseSpeedUpFactor = 1.0f;
 
-    private boolean mExpanding;
+    protected boolean mExpanding;
     private boolean mGestureWaitForTouchSlop;
     private boolean mIgnoreXTouchSlop;
     private Runnable mPeekRunnable = new Runnable() {
@@ -137,7 +137,7 @@
         }
     }
 
-    private void notifyExpandingFinished() {
+    protected final void notifyExpandingFinished() {
         if (mExpanding) {
             mExpanding = false;
             onExpandingFinished();
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 f0927a8..a67e77a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -198,6 +198,8 @@
 
     public static final boolean SHOW_LOCKSCREEN_MEDIA_ARTWORK = true;
 
+    public static final String ACTION_FAKE_ARTWORK = "fake_artwork";
+
     private static final int MSG_OPEN_NOTIFICATION_PANEL = 1000;
     private static final int MSG_CLOSE_PANELS = 1001;
     private static final int MSG_OPEN_SETTINGS_PANEL = 1002;
@@ -364,6 +366,9 @@
                 mUserSetup = userSetup;
                 if (!mUserSetup && mStatusBarView != null)
                     animateCollapseQuickSettings();
+                if (mKeyguardBottomArea != null) {
+                    mKeyguardBottomArea.setUserSetupComplete(mUserSetup);
+                }
             }
             if (mIconPolicy != null) {
                 mIconPolicy.setCurrentUserSetup(mUserSetup);
@@ -434,6 +439,12 @@
         public void onPlaybackStateChanged(PlaybackState state) {
             super.onPlaybackStateChanged(state);
             if (DEBUG_MEDIA) Log.v(TAG, "DEBUG_MEDIA: onPlaybackStateChanged: " + state);
+            if (state != null) {
+                if (!isPlaybackActive(state.getState())) {
+                    clearCurrentMediaNotification();
+                    updateMediaMetaData(true);
+                }
+            }
         }
 
         @Override
@@ -834,6 +845,7 @@
         mFlashlightController = new FlashlightController(mContext);
         mKeyguardBottomArea.setFlashlightController(mFlashlightController);
         mKeyguardBottomArea.setPhoneStatusBar(this);
+        mKeyguardBottomArea.setUserSetupComplete(mUserSetup);
         mAccessibilityController = new AccessibilityController(mContext);
         mKeyguardBottomArea.setAccessibilityController(mAccessibilityController);
         mNextAlarmController = new NextAlarmController(mContext);
@@ -890,12 +902,16 @@
         filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
         filter.addAction(Intent.ACTION_SCREEN_OFF);
         filter.addAction(Intent.ACTION_SCREEN_ON);
-        if (DEBUG_MEDIA_FAKE_ARTWORK) {
-            filter.addAction("fake_artwork");
-        }
-        filter.addAction(ACTION_DEMO);
         context.registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter, null, null);
 
+        IntentFilter demoFilter = new IntentFilter();
+        if (DEBUG_MEDIA_FAKE_ARTWORK) {
+            demoFilter.addAction(ACTION_FAKE_ARTWORK);
+        }
+        demoFilter.addAction(ACTION_DEMO);
+        context.registerReceiverAsUser(mDemoReceiver, UserHandle.ALL, demoFilter,
+                android.Manifest.permission.DUMP, null);
+
         // listen for USER_SETUP_COMPLETE setting (per-user)
         resetUserSetupObserver();
 
@@ -1193,6 +1209,10 @@
         if (mHeadsUpManager.isHeadsUp(key)) {
             deferRemoval = !mHeadsUpManager.removeNotification(key);
         }
+        if (key.equals(mMediaNotificationKey)) {
+            clearCurrentMediaNotification();
+            updateMediaMetaData(true);
+        }
         if (deferRemoval) {
             mLatestRankingMap = ranking;
             mHeadsUpEntriesToRemoveOnSwitch.add(mHeadsUpManager.getEntry(key));
@@ -1486,23 +1506,31 @@
         synchronized (mNotificationData) {
             ArrayList<Entry> activeNotifications = mNotificationData.getActiveNotifications();
             final int N = activeNotifications.size();
+
+            // Promote the media notification with a controller in 'playing' state, if any.
             Entry mediaNotification = null;
             MediaController controller = null;
             for (int i = 0; i < N; i++) {
                 final Entry entry = activeNotifications.get(i);
                 if (isMediaNotification(entry)) {
-                    final MediaSession.Token token = entry.notification.getNotification().extras
+                    final MediaSession.Token token =
+                            entry.notification.getNotification().extras
                             .getParcelable(Notification.EXTRA_MEDIA_SESSION);
                     if (token != null) {
-                        controller = new MediaController(mContext, token);
-                        if (controller != null) {
-                            // we've got a live one, here
+                        MediaController aController = new MediaController(mContext, token);
+                        if (PlaybackState.STATE_PLAYING ==
+                                getMediaControllerPlaybackState(aController)) {
+                            if (DEBUG_MEDIA) {
+                                Log.v(TAG, "DEBUG_MEDIA: found mediastyle controller matching "
+                                        + entry.notification.getKey());
+                            }
                             mediaNotification = entry;
+                            controller = aController;
+                            break;
                         }
                     }
                 }
             }
-
             if (mediaNotification == null) {
                 // Still nothing? OK, let's just look for live media sessions and see if they match
                 // one of our notifications. This will catch apps that aren't (yet!) using media
@@ -1515,83 +1543,88 @@
                                     UserHandle.USER_ALL);
 
                     for (MediaController aController : sessions) {
-                        if (aController == null) continue;
-                        final PlaybackState state = aController.getPlaybackState();
-                        if (state == null) continue;
-                        switch (state.getState()) {
-                            case PlaybackState.STATE_STOPPED:
-                            case PlaybackState.STATE_ERROR:
-                                continue;
-                            default:
-                                // now to see if we have one like this
-                                final String pkg = aController.getPackageName();
+                        if (PlaybackState.STATE_PLAYING ==
+                                getMediaControllerPlaybackState(aController)) {
+                            // now to see if we have one like this
+                            final String pkg = aController.getPackageName();
 
-                                for (int i = 0; i < N; i++) {
-                                    final Entry entry = activeNotifications.get(i);
-                                    if (entry.notification.getPackageName().equals(pkg)) {
-                                        if (DEBUG_MEDIA) {
-                                            Log.v(TAG, "DEBUG_MEDIA: found controller matching "
-                                                + entry.notification.getKey());
-                                        }
-                                        controller = aController;
-                                        mediaNotification = entry;
-                                        break;
+                            for (int i = 0; i < N; i++) {
+                                final Entry entry = activeNotifications.get(i);
+                                if (entry.notification.getPackageName().equals(pkg)) {
+                                    if (DEBUG_MEDIA) {
+                                        Log.v(TAG, "DEBUG_MEDIA: found controller matching "
+                                            + entry.notification.getKey());
                                     }
+                                    controller = aController;
+                                    mediaNotification = entry;
+                                    break;
                                 }
+                            }
                         }
                     }
                 }
             }
 
-            if (!sameSessions(mMediaController, controller)) {
+            if (controller != null && !sameSessions(mMediaController, controller)) {
                 // We have a new media session
-
-                if (mMediaController != null) {
-                    // something old was playing
-                    Log.v(TAG, "DEBUG_MEDIA: Disconnecting from old controller: "
-                            + mMediaController);
-                    mMediaController.unregisterCallback(mMediaListener);
-                }
+                clearCurrentMediaNotification();
                 mMediaController = controller;
-
-                if (mMediaController != null) {
-                    mMediaController.registerCallback(mMediaListener);
-                    mMediaMetadata = mMediaController.getMetadata();
-                    if (DEBUG_MEDIA) {
-                        Log.v(TAG, "DEBUG_MEDIA: insert listener, receive metadata: "
-                                + mMediaMetadata);
-                    }
-
-                    final String notificationKey = mediaNotification == null
-                            ? null
-                            : mediaNotification.notification.getKey();
-
-                    if (notificationKey == null || !notificationKey.equals(mMediaNotificationKey)) {
-                        // we have a new notification!
-                        if (DEBUG_MEDIA) {
-                            Log.v(TAG, "DEBUG_MEDIA: Found new media notification: key="
-                                    + notificationKey + " controller=" + controller);
-                        }
-                        mMediaNotificationKey = notificationKey;
-                    }
-                } else {
-                    mMediaMetadata = null;
-                    mMediaNotificationKey = null;
-                }
-
-                metaDataChanged = true;
-            } else {
-                // Media session unchanged
-
+                mMediaController.registerCallback(mMediaListener);
+                mMediaMetadata = mMediaController.getMetadata();
                 if (DEBUG_MEDIA) {
-                    Log.v(TAG, "DEBUG_MEDIA: Continuing media notification: key=" + mMediaNotificationKey);
+                    Log.v(TAG, "DEBUG_MEDIA: insert listener, receive metadata: "
+                            + mMediaMetadata);
                 }
+
+                if (mediaNotification != null) {
+                    mMediaNotificationKey = mediaNotification.notification.getKey();
+                    if (DEBUG_MEDIA) {
+                        Log.v(TAG, "DEBUG_MEDIA: Found new media notification: key="
+                                + mMediaNotificationKey + " controller=" + mMediaController);
+                    }
+                }
+                metaDataChanged = true;
             }
         }
 
+        if (metaDataChanged) {
+            updateNotifications();
+        }
         updateMediaMetaData(metaDataChanged);
     }
 
+    private int getMediaControllerPlaybackState(MediaController controller) {
+        if (controller != null) {
+            final PlaybackState playbackState = controller.getPlaybackState();
+            if (playbackState != null) {
+                return playbackState.getState();
+            }
+        }
+        return PlaybackState.STATE_NONE;
+    }
+
+    private boolean isPlaybackActive(int state) {
+        if (state != PlaybackState.STATE_STOPPED
+                && state != PlaybackState.STATE_ERROR
+                && state != PlaybackState.STATE_NONE) {
+            return true;
+        }
+        return false;
+    }
+
+    private void clearCurrentMediaNotification() {
+        mMediaNotificationKey = null;
+        mMediaMetadata = null;
+        if (mMediaController != null) {
+            if (DEBUG_MEDIA) {
+                Log.v(TAG, "DEBUG_MEDIA: Disconnecting from old controller: "
+                        + mMediaController.getPackageName());
+            }
+            mMediaController.unregisterCallback(mMediaListener);
+        }
+        mMediaController = null;
+    }
+
     private boolean sameSessions(MediaController a, MediaController b) {
         if (a == b) return true;
         if (a == null) return false;
@@ -1730,7 +1763,7 @@
     }
 
     private int adjustDisableFlags(int state) {
-        if (!mLaunchTransitionFadingAway
+        if (!mLaunchTransitionFadingAway && !mKeyguardFadingAway
                 && (mExpandedVisible || mBouncerShowing || mWaitingForKeyguardExit)) {
             state |= StatusBarManager.DISABLE_NOTIFICATION_ICONS;
             state |= StatusBarManager.DISABLE_SYSTEM_INFO;
@@ -2677,6 +2710,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);
         }
@@ -2849,7 +2885,14 @@
                 mScreenOn = true;
                 notifyNavigationBarScreenOn(true);
             }
-            else if (ACTION_DEMO.equals(action)) {
+        }
+    };
+
+    private BroadcastReceiver mDemoReceiver = new BroadcastReceiver() {
+        public void onReceive(Context context, Intent intent) {
+            if (DEBUG) Log.v(TAG, "onReceive: " + intent);
+            String action = intent.getAction();
+            if (ACTION_DEMO.equals(action)) {
                 Bundle bundle = intent.getExtras();
                 if (bundle != null) {
                     String command = bundle.getString("command", "").trim().toLowerCase();
@@ -2861,7 +2904,7 @@
                         }
                     }
                 }
-            } else if ("fake_artwork".equals(action)) {
+            } else if (ACTION_FAKE_ARTWORK.equals(action)) {
                 if (DEBUG_MEDIA_FAKE_ARTWORK) {
                     updateMediaMetaData(true);
                 }
@@ -2910,7 +2953,7 @@
         updateRowStates();
         mIconController.updateResources();
         mScreenPinningRequest.onConfigurationChanged();
-        mNetworkController.handleConfigurationChanged();
+        mNetworkController.onConfigurationChanged();
     }
 
     @Override
@@ -3185,6 +3228,7 @@
             mHandlerThread = null;
         }
         mContext.unregisterReceiver(mBroadcastReceiver);
+        mContext.unregisterReceiver(mDemoReceiver);
         mAssistManager.destroy();
 
         final SignalClusterView signalCluster =
@@ -3208,7 +3252,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)) {
@@ -3308,6 +3352,7 @@
             mDraggedDownRow.notifyHeightChanged(false  /* needsAnimation */);
             mDraggedDownRow = null;
         }
+        mAssistManager.onLockscreenShown();
     }
 
     private void onLaunchTransitionFadingEnded() {
@@ -3457,7 +3502,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() {
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/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 6fc15a8..f31311d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/UnlockMethodCache.java
@@ -132,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/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/NetworkControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
index 81f2d532..57dfff5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
@@ -31,6 +31,7 @@
 import android.os.Handler;
 import android.os.Looper;
 import android.provider.Settings;
+import android.telephony.ServiceState;
 import android.telephony.SubscriptionInfo;
 import android.telephony.SubscriptionManager;
 import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
@@ -117,6 +118,9 @@
     // Handler that all callbacks are made on.
     private final CallbackHandler mCallbackHandler;
 
+    @VisibleForTesting
+    ServiceState mLastServiceState;
+
     /**
      * Construct this controller object and register for updates.
      */
@@ -194,10 +198,10 @@
         filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
         filter.addAction(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
         filter.addAction(TelephonyIntents.ACTION_DEFAULT_VOICE_SUBSCRIPTION_CHANGED);
+        filter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
         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;
@@ -260,6 +264,11 @@
     }
 
     public boolean isEmergencyOnly() {
+        if (mMobileSignalControllers.size() == 0) {
+            // When there are no active subscriptions, determine emengency state from last
+            // broadcast.
+            return mLastServiceState != null && mLastServiceState.isEmergencyOnly();
+        }
         int voiceSubId = mSubDefaults.getDefaultVoiceSubId();
         if (!SubscriptionManager.isValidSubscriptionId(voiceSubId)) {
             for (MobileSignalController mobileSignalController :
@@ -339,8 +348,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);
@@ -356,6 +363,13 @@
         } else if (action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) {
             // Might have different subscriptions now.
             updateMobileControllers();
+        } else if (action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) {
+            mLastServiceState = ServiceState.newFromBundle(intent.getExtras());
+            if (mMobileSignalControllers.size() == 0) {
+                // If none of the subscriptions are active, we might need to recalculate
+                // emergency state.
+                recalculateEmergency();
+            }
         } else {
             int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY,
                     SubscriptionManager.INVALID_SUBSCRIPTION_ID);
@@ -373,8 +387,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);
         }
@@ -580,6 +604,8 @@
         pw.println(mAirplaneMode);
         pw.print("  mLocale=");
         pw.println(mLocale);
+        pw.print("  mLastServiceState=");
+        pw.println(mLastServiceState);
 
         for (MobileSignalController mobileSignalController : mMobileSignalControllers.values()) {
             mobileSignalController.dump(pw);
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/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerSignalTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerSignalTest.java
index 52dea40..d9b9063 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerSignalTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/NetworkControllerSignalTest.java
@@ -21,6 +21,7 @@
 import android.net.ConnectivityManager;
 import android.net.NetworkCapabilities;
 import android.os.Looper;
+import android.telephony.ServiceState;
 import android.telephony.SignalStrength;
 import android.telephony.SubscriptionInfo;
 import android.telephony.TelephonyManager;
@@ -70,11 +71,20 @@
 
     public void testEmergencyOnlyNoSubscriptions() {
         setupDefaultSignal();
+        setSubscriptions();
+        mNetworkController.mLastServiceState = new ServiceState();
+        mNetworkController.mLastServiceState.setEmergencyOnly(true);
+        mNetworkController.recalculateEmergency();
+        verifyEmergencyOnly(true);
+    }
+
+    public void testNoEmengencyNoSubscriptions() {
+        setupDefaultSignal();
+        setSubscriptions();
+        mNetworkController.mLastServiceState = new ServiceState();
+        mNetworkController.mLastServiceState.setEmergencyOnly(false);
         mNetworkController.recalculateEmergency();
         verifyEmergencyOnly(false);
-
-        setSubscriptions();
-        verifyEmergencyOnly(true);
     }
 
     public void testNoSimlessIconWithoutMobile() {
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/AssetAtlasService.java b/services/core/java/com/android/server/AssetAtlasService.java
index ebc810f..4569dae 100644
--- a/services/core/java/com/android/server/AssetAtlasService.java
+++ b/services/core/java/com/android/server/AssetAtlasService.java
@@ -93,7 +93,7 @@
     // Defines the number of int fields used to represent a single entry
     // in the atlas map. This number defines the size of the array returned
     // by the getMap(). See the mAtlasMap field for more information
-    private static final int ATLAS_MAP_ENTRY_FIELD_COUNT = 4;
+    private static final int ATLAS_MAP_ENTRY_FIELD_COUNT = 3;
 
     // Specifies how our GraphicBuffer will be used. To get proper swizzling
     // the buffer will be written to using OpenGL (from JNI) so we can leave
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/InputMethodManagerService.java b/services/core/java/com/android/server/InputMethodManagerService.java
index dbe8781..64ee5f1 100644
--- a/services/core/java/com/android/server/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/InputMethodManagerService.java
@@ -114,6 +114,7 @@
 import android.view.inputmethod.InputMethod;
 import android.view.inputmethod.InputMethodInfo;
 import android.view.inputmethod.InputMethodManager;
+import android.view.inputmethod.InputMethodManagerInternal;
 import android.view.inputmethod.InputMethodSubtype;
 import android.view.inputmethod.InputMethodSubtype.InputMethodSubtypeBuilder;
 import android.widget.ArrayAdapter;
@@ -166,6 +167,7 @@
     static final int MSG_UNBIND_METHOD = 3000;
     static final int MSG_BIND_METHOD = 3010;
     static final int MSG_SET_ACTIVE = 3020;
+    static final int MSG_SET_INTERACTIVE = 3030;
     static final int MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER = 3040;
 
     static final int MSG_HARD_KEYBOARD_SWITCH_CHANGED = 4000;
@@ -394,9 +396,9 @@
     SessionState mEnabledSession;
 
     /**
-     * True if the screen is on.  The value is true initially.
+     * True if the device is currently interactive with user.  The value is true initially.
      */
-    boolean mScreenOn = true;
+    boolean mIsInteractive = true;
 
     int mCurUserActionNotificationSequenceNumber = 0;
 
@@ -492,30 +494,12 @@
     }
 
     class ImmsBroadcastReceiver extends android.content.BroadcastReceiver {
-        private void updateActive() {
-            // Inform the current client of the change in active status
-            if (mCurClient != null && mCurClient.client != null) {
-                executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
-                        MSG_SET_ACTIVE, mScreenOn ? 1 : 0, mCurClient));
-            }
-        }
-
         @Override
         public void onReceive(Context context, Intent intent) {
             final String action = intent.getAction();
-            if (Intent.ACTION_SCREEN_ON.equals(action)) {
-                mScreenOn = true;
-                updateSystemUi(mCurToken, mImeWindowVis, mBackDisposition);
-                updateActive();
-                return;
-            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
-                mScreenOn = false;
-                updateSystemUi(mCurToken, 0 /* vis */, mBackDisposition);
-                updateActive();
-                return;
-            } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
+            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                 hideInputMethodMenu();
-                // No need to updateActive
+                // No need to update mIsInteractive
                 return;
             } else if (Intent.ACTION_USER_ADDED.equals(action)
                     || Intent.ACTION_USER_REMOVED.equals(action)) {
@@ -817,8 +801,6 @@
         mShowOngoingImeSwitcherForPhones = false;
 
         final IntentFilter broadcastFilter = new IntentFilter();
-        broadcastFilter.addAction(Intent.ACTION_SCREEN_ON);
-        broadcastFilter.addAction(Intent.ACTION_SCREEN_OFF);
         broadcastFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
         broadcastFilter.addAction(Intent.ACTION_USER_ADDED);
         broadcastFilter.addAction(Intent.ACTION_USER_REMOVED);
@@ -938,6 +920,7 @@
                         }
                     }
                 }, filter);
+        LocalServices.addService(InputMethodManagerInternal.class, new LocalServiceImpl(mHandler));
     }
 
     private void resetDefaultImeLocked(Context context) {
@@ -1379,9 +1362,9 @@
                     + cs.client.asBinder() + " keyguard=" + mCurClientInKeyguard);
 
             // If the screen is on, inform the new client it is active
-            if (mScreenOn) {
+            if (mIsInteractive) {
                 executeOrSendMessage(cs.client, mCaller.obtainMessageIO(
-                        MSG_SET_ACTIVE, mScreenOn ? 1 : 0, cs));
+                        MSG_SET_ACTIVE, mIsInteractive ? 1 : 0, cs));
             }
         }
 
@@ -2851,6 +2834,9 @@
                             + ((ClientState)msg.obj).uid);
                 }
                 return true;
+            case MSG_SET_INTERACTIVE:
+                handleSetInteractive(msg.arg1 != 0);
+                return true;
             case MSG_SET_USER_ACTION_NOTIFICATION_SEQUENCE_NUMBER: {
                 final int sequenceNumber = msg.arg1;
                 final ClientState clientState = (ClientState)msg.obj;
@@ -2874,6 +2860,19 @@
         return false;
     }
 
+    private void handleSetInteractive(final boolean interactive) {
+        synchronized (mMethodMap) {
+            mIsInteractive = interactive;
+            updateSystemUiLocked(mCurToken, interactive ? mImeWindowVis : 0, mBackDisposition);
+
+            // Inform the current client of the change in active status
+            if (mCurClient != null && mCurClient.client != null) {
+                executeOrSendMessage(mCurClient.client, mCaller.obtainMessageIO(
+                        MSG_SET_ACTIVE, mIsInteractive ? 1 : 0, mCurClient));
+            }
+        }
+    }
+
     private boolean chooseNewDefaultIMELocked() {
         final InputMethodInfo imi = InputMethodUtils.getMostApplicableDefaultIME(
                 mSettings.getEnabledInputMethodListLocked());
@@ -3734,6 +3733,22 @@
         }
     }
 
+    private static final class LocalServiceImpl implements InputMethodManagerInternal {
+        @NonNull
+        private final Handler mHandler;
+
+        LocalServiceImpl(@NonNull final Handler handler) {
+            mHandler = handler;
+        }
+
+        @Override
+        public void setInteractive(boolean interactive) {
+            // Do everything in handler so as not to block the caller.
+            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_INTERACTIVE,
+                    interactive ? 1 : 0, 0));
+        }
+    }
+
     @Override
     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
@@ -3784,7 +3799,7 @@
                     + " mInputShown=" + mInputShown);
             p.println("  mCurUserActionNotificationSequenceNumber="
                     + mCurUserActionNotificationSequenceNumber);
-            p.println("  mSystemReady=" + mSystemReady + " mInteractive=" + mScreenOn);
+            p.println("  mSystemReady=" + mSystemReady + " mInteractive=" + mIsInteractive);
             p.println("  mSettingsObserver=" + mSettingsObserver);
             p.println("  mSwitchingController:");
             mSwitchingController.dump(p);
diff --git a/services/core/java/com/android/server/MountService.java b/services/core/java/com/android/server/MountService.java
index 92b98a7..ed136e9 100644
--- a/services/core/java/com/android/server/MountService.java
+++ b/services/core/java/com/android/server/MountService.java
@@ -3431,6 +3431,11 @@
         }
 
         public boolean hasExternalStorage(int uid, String packageName) {
+            // No need to check for system uid. This avoids a deadlock between
+            // PackageManagerService and AppOpsService.
+            if (uid == Process.SYSTEM_UID) {
+                return true;
+            }
             // No locking - CopyOnWriteArrayList
             for (ExternalStorageMountPolicy policy : mPolicies) {
                 final boolean policyHasStorage = policy.hasExternalStorage(uid, packageName);
diff --git a/services/core/java/com/android/server/accounts/AccountManagerService.java b/services/core/java/com/android/server/accounts/AccountManagerService.java
index a270974..32fd56a 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.
      */
@@ -3764,7 +3799,8 @@
          * access accounts of the specified account.
          */
         boolean isPermitted =
-                isPermitted(callingUid, Manifest.permission.GET_ACCOUNTS);
+                isPermitted(callingUid, Manifest.permission.GET_ACCOUNTS,
+                        Manifest.permission.GET_ACCOUNTS_PRIVILEGED);
         boolean isAccountManagedByCaller = isAccountManagedByCaller(accountType, callingUid);
         Log.w(TAG, String.format(
                 "isReadAccountPermitted: isPermitted: %s, isAM: %s",
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 3bf6fde..4d9695d 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -65,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;
@@ -73,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;
@@ -1353,6 +1355,7 @@
     static final int DISPATCH_UIDS_CHANGED_MSG = 54;
     static final int REPORT_TIME_TRACKER_MSG = 55;
     static final int REPORT_USER_SWITCH_COMPLETE_MSG = 56;
+    static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 57;
 
     static final int FIRST_ACTIVITY_STACK_MSG = 100;
     static final int FIRST_BROADCAST_QUEUE_MSG = 200;
@@ -2017,6 +2020,17 @@
             case REPORT_USER_SWITCH_COMPLETE_MSG: {
                 dispatchUserSwitchComplete(msg.arg1);
             } break;
+            case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: {
+                IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj;
+                try {
+                    connection.shutdown();
+                } catch (RemoteException e) {
+                    Slog.w(TAG, "Error shutting down UiAutomationConnection");
+                }
+                // Only a UiAutomation can set this flag and now that
+                // it is finished we make sure it is reset to its default.
+                mUserIsMonkey = false;
+            } break;
             }
         }
     };
@@ -10686,7 +10700,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;
         }
@@ -10707,7 +10721,7 @@
     }
 
     @Override
-    public boolean isScreenCaptureAllowedOnCurrentActivity() {
+    public boolean isAssistDataAllowedOnCurrentActivity() {
         int userId = mCurrentUserId;
         synchronized (this) {
             ActivityRecord activity = getFocusedStack().topActivity();
@@ -10722,13 +10736,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) {
@@ -10741,9 +10783,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();
@@ -10854,7 +10900,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;
     }
 
@@ -17068,16 +17114,11 @@
             } catch (RemoteException e) {
             }
         }
-        if (app.instrumentationUiAutomationConnection != null) {
-            try {
-                app.instrumentationUiAutomationConnection.shutdown();
-            } catch (RemoteException re) {
-                /* ignore */
-            }
-            // Only a UiAutomation can set this flag and now that
-            // it is finished we make sure it is reset to its default.
-            mUserIsMonkey = false;
-        }
+
+        // Can't call out of the system process with a lock held, so post a message.
+        mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG,
+                app.instrumentationUiAutomationConnection).sendToTarget();
+
         app.instrumentationWatcher = null;
         app.instrumentationUiAutomationConnection = null;
         app.instrumentationClass = null;
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/am/ActivityStack.java
index e57e3ff..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;
                 }
             }
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 8871e64..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;
@@ -124,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;
@@ -156,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)) {
@@ -577,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;
         }
 
@@ -727,7 +728,6 @@
             mHandler.post(new Runnable() {
                 @Override
                 public void run() {
-                    mIsKeyguard = KEYGUARD_PACKAGE.equals(opPackageName);
                     startAuthentication(token, opId, groupId, receiver, flags, restricted);
                 }
             });
@@ -821,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 f04790e..0d1d1ea 100644
--- a/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java
@@ -495,6 +495,16 @@
                 }
             }
 
+            // Voice recognition
+            Intent voiceRecoIntent = new Intent("android.speech.RecognitionService");
+            voiceRecoIntent.addCategory(Intent.CATEGORY_DEFAULT);
+            PackageParser.Package voiceRecoPackage = getDefaultSystemHandlerServicePackageLPr(
+                    voiceRecoIntent, userId);
+            if (voiceRecoPackage != null
+                    && doesPackageSupportRuntimePermissions(voiceRecoPackage)) {
+                grantRuntimePermissionsLPw(voiceRecoPackage, MICROPHONE_PERMISSIONS, userId);
+            }
+
             // Location
             if (locationPackageNames != null) {
                 for (String packageName : locationPackageNames) {
@@ -627,6 +637,26 @@
         return null;
     }
 
+    private PackageParser.Package getDefaultSystemHandlerServicePackageLPr(
+            Intent intent, int userId) {
+        List<ResolveInfo> handlers = mService.queryIntentServices(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);
+            PackageParser.Package handlerPackage = getSystemPackageLPr(
+                    handler.serviceInfo.packageName);
+            if (handlerPackage != null) {
+                return handlerPackage;
+            }
+        }
+        return null;
+    }
+
     private List<PackageParser.Package> getHeadlessSyncAdapterPackagesLPr(
             String[] syncAdapterPackageNames, int userId) {
         List<PackageParser.Package> syncAdapterPackages = new ArrayList<>();
diff --git a/services/core/java/com/android/server/pm/PackageInstallerService.java b/services/core/java/com/android/server/pm/PackageInstallerService.java
index 07de6f5..0366fff 100644
--- a/services/core/java/com/android/server/pm/PackageInstallerService.java
+++ b/services/core/java/com/android/server/pm/PackageInstallerService.java
@@ -91,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;
@@ -106,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;
@@ -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
@@ -1091,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 c763315..61ed1a7 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -3555,7 +3555,7 @@
                         continue;
                     }
                     PackageSetting ps = (PackageSetting) pkg.mExtras;
-                    resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
+                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
                 }
             }
         }
@@ -3605,10 +3605,14 @@
         enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
                 "updatePermissionFlags");
 
-        // Only the system can change system fixed flags.
+        // Only the system can change these flags and nothing else.
         if (getCallingUid() != Process.SYSTEM_UID) {
             flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
             flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
+            flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
+            flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED;
+            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
+            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
         }
 
         synchronized (mPackages) {
@@ -7321,6 +7325,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
@@ -7350,6 +7357,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;
@@ -7375,6 +7383,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);
@@ -12275,6 +12284,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;
@@ -12904,10 +12927,6 @@
         synchronized (mPackages) {
             PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
 
-            // Propagate the permissions state as we do want to drop on the floor
-            // runtime permissions. The update permissions method below will take
-            // care of removing obsolete permissions and grant install permissions.
-            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
             updatePermissionsLPw(newPkg.packageName, newPkg,
                     UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
 
@@ -12921,6 +12940,8 @@
                                 + " => " + perUserInstalled[i]);
                     }
                     ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
+
+                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
                 }
                 // Regardless of writeSettings we need to ensure that this restriction
                 // state propagation is persisted
@@ -13071,7 +13092,7 @@
                 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
                     scheduleWritePackageRestrictionsLocked(removeUser);
                 }
-                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
+                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
             }
             return true;
         }
@@ -13232,7 +13253,7 @@
             }
 
             PackageSetting ps = (PackageSetting) pkg.mExtras;
-            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
+            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
         }
 
         // Always delete data directories for package, even if we found no other
@@ -13264,12 +13285,27 @@
     }
 
     /**
+     * Reverts user permission state changes (permissions and flags) in
+     * all packages for a given user.
+     *
+     * @param userId The device user for which to do a reset.
+     */
+    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
+        final int packageCount = mPackages.size();
+        for (int i = 0; i < packageCount; i++) {
+            PackageParser.Package pkg = mPackages.valueAt(i);
+            PackageSetting ps = (PackageSetting) pkg.mExtras;
+            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
+        }
+    }
+
+    /**
      * Reverts user permission state changes (permissions and flags).
      *
      * @param ps The package for which to reset.
      * @param userId The device user for which to do a reset.
      */
-    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
+    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
             final PackageSetting ps, final int userId) {
         if (ps.pkg == null) {
             return;
@@ -13769,6 +13805,15 @@
     }
 
     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
+    private void clearIntentFilterVerificationsLPw(int userId) {
+        final int packageCount = mPackages.size();
+        for (int i = 0; i < packageCount; i++) {
+            PackageParser.Package pkg = mPackages.valueAt(i);
+            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
+        }
+    }
+
+    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
     void clearIntentFilterVerificationsLPw(String packageName, int userId) {
         if (userId == UserHandle.USER_ALL) {
             if (mSettings.removeIntentFilterVerificationLPw(packageName,
@@ -13784,7 +13829,6 @@
         }
     }
 
-
     void clearDefaultBrowserIfNeeded(String packageName) {
         for (int oneUserId : sUserManager.getUserIds()) {
             String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
@@ -13796,17 +13840,27 @@
     }
 
     @Override
-    public void resetPreferredActivities(int userId) {
+    public void resetApplicationPreferences(int userId) {
         mContext.enforceCallingOrSelfPermission(
                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
         // writer
         synchronized (mPackages) {
-            clearPackagePreferredActivitiesLPw(null, userId);
-            mSettings.applyDefaultPreferredAppsLPw(this, userId);
-            applyFactoryDefaultBrowserLPw(userId);
-            primeDomainVerificationsLPw(userId);
-
-            scheduleWritePackageRestrictionsLocked(userId);
+            final long identity = Binder.clearCallingIdentity();
+            try {
+                clearPackagePreferredActivitiesLPw(null, userId);
+                mSettings.applyDefaultPreferredAppsLPw(this, userId);
+                // TODO: We have to reset the default SMS and Phone. This requires
+                // significant refactoring to keep all default apps in the package
+                // manager (cleaner but more work) or have the services provide
+                // callbacks to the package manager to request a default app reset.
+                applyFactoryDefaultBrowserLPw(userId);
+                clearIntentFilterVerificationsLPw(userId);
+                primeDomainVerificationsLPw(userId);
+                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
+                scheduleWritePackageRestrictionsLocked(userId);
+            } finally {
+                Binder.restoreCallingIdentity(identity);
+            }
         }
     }
 
@@ -14674,12 +14728,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;
@@ -15586,12 +15640,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;
 
@@ -15647,12 +15697,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());
@@ -15783,7 +15829,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);
diff --git a/services/core/java/com/android/server/pm/Settings.java b/services/core/java/com/android/server/pm/Settings.java
index 96ec5aa..736b153 100644
--- a/services/core/java/com/android/server/pm/Settings.java
+++ b/services/core/java/com/android/server/pm/Settings.java
@@ -1078,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) {
@@ -4126,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);
@@ -4161,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);
                     }
                 }
             }
@@ -4273,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=");
@@ -4378,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,
@@ -4409,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 28cbaab..dc3e2d6 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -119,7 +119,7 @@
 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;
@@ -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);
         }
     };
@@ -5496,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();
         }
     }
 
@@ -5539,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.
@@ -5570,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() {
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 1406789..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,7 +35,7 @@
     private final Context mContext;
     private final View mScrim; // shown if keyguard crashes
     private final KeyguardState mKeyguardState = new KeyguardState();
-    private ShowListener mShowListenerWhenConnect;
+    private DrawnListener mDrawnListenerWhenConnect;
 
     private static final class KeyguardState {
         KeyguardState() {
@@ -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();
         }
@@ -141,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();
@@ -221,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();
         }
     }
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/power/Notifier.java b/services/core/java/com/android/server/power/Notifier.java
index c5ad7fe..7108f4a 100644
--- a/services/core/java/com/android/server/power/Notifier.java
+++ b/services/core/java/com/android/server/power/Notifier.java
@@ -48,6 +48,7 @@
 import android.util.EventLog;
 import android.util.Slog;
 import android.view.WindowManagerPolicy;
+import android.view.inputmethod.InputMethodManagerInternal;
 
 /**
  * Sends broadcasts about important power state changes.
@@ -89,6 +90,7 @@
     private final WindowManagerPolicy mPolicy;
     private final ActivityManagerInternal mActivityManagerInternal;
     private final InputManagerInternal mInputManagerInternal;
+    private final InputMethodManagerInternal mInputMethodManagerInternal;
 
     private final NotifierHandler mHandler;
     private final Intent mScreenOnIntent;
@@ -133,6 +135,7 @@
         mPolicy = policy;
         mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
         mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
+        mInputMethodManagerInternal = LocalServices.getService(InputMethodManagerInternal.class);
 
         mHandler = new NotifierHandler(looper);
         mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
@@ -314,6 +317,7 @@
 
             // Start input as soon as we start waking up or going to sleep.
             mInputManagerInternal.setInteractive(interactive);
+            mInputMethodManagerInternal.setInteractive(interactive);
 
             // Notify battery stats.
             try {
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 c776e8f..d9828cc 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -10015,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();
@@ -10029,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);
                                 }
                             }
                         }
@@ -10050,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/core/jni/com_android_server_input_InputManagerService.cpp b/services/core/jni/com_android_server_input_InputManagerService.cpp
index f3edbd1..e29d0a9 100644
--- a/services/core/jni/com_android_server_input_InputManagerService.cpp
+++ b/services/core/jni/com_android_server_input_InputManagerService.cpp
@@ -27,6 +27,8 @@
 
 #include "JNIHelp.h"
 #include "jni.h"
+#include <atomic>
+#include <cinttypes>
 #include <limits.h>
 #include <android_runtime/AndroidRuntime.h>
 #include <android_runtime/Log.h>
@@ -56,6 +58,8 @@
 #include "com_android_server_input_InputApplicationHandle.h"
 #include "com_android_server_input_InputWindowHandle.h"
 
+#define INDENT "  "
+
 namespace android {
 
 // The exponent used to calculate the pointer speed scaling factor.
@@ -126,6 +130,10 @@
     return a > b ? a : b;
 }
 
+static inline const char* toString(bool value) {
+    return value ? "true" : "false";
+}
+
 static jobject getInputApplicationHandleObjLocalRef(JNIEnv* env,
         const sp<InputApplicationHandle>& inputApplicationHandle) {
     if (inputApplicationHandle == NULL) {
@@ -262,7 +270,7 @@
         wp<PointerController> pointerController;
     } mLocked;
 
-    volatile bool mInteractive;
+    std::atomic<bool> mInteractive;
 
     void updateInactivityTimeoutLocked(const sp<PointerController>& controller);
     void handleInterceptActions(jint wmActions, nsecs_t when, uint32_t& policyFlags);
@@ -292,6 +300,7 @@
         mLocked.pointerGesturesEnabled = true;
         mLocked.showTouches = false;
     }
+    mInteractive = true;
 
     sp<EventHub> eventHub = new EventHub();
     mInputManager = new InputManager(eventHub, this, this);
@@ -305,6 +314,21 @@
 }
 
 void NativeInputManager::dump(String8& dump) {
+    dump.append("Input Manager State:\n");
+    {
+        dump.appendFormat(INDENT "Interactive: %s\n", toString(mInteractive.load()));
+    }
+    {
+        AutoMutex _l(mLock);
+        dump.appendFormat(INDENT "System UI Visibility: 0x%0" PRIx32 "\n",
+                mLocked.systemUiVisibility);
+        dump.appendFormat(INDENT "Pointer Speed: %" PRId32 "\n", mLocked.pointerSpeed);
+        dump.appendFormat(INDENT "Pointer Gestures Enabled: %s\n",
+                toString(mLocked.pointerGesturesEnabled));
+        dump.appendFormat(INDENT "Show Touches: %s\n", toString(mLocked.showTouches));
+    }
+    dump.append("\n");
+
     mInputManager->getReader()->dump(dump);
     dump.append("\n");
 
@@ -830,7 +854,8 @@
     // - Ignore untrusted events and pass them along.
     // - Ask the window manager what to do with normal events and trusted injected events.
     // - For normal events wake and brighten the screen if currently off or dim.
-    if (mInteractive) {
+    bool interactive = mInteractive.load();
+    if (interactive) {
         policyFlags |= POLICY_FLAG_INTERACTIVE;
     }
     if ((policyFlags & POLICY_FLAG_TRUSTED)) {
@@ -854,7 +879,7 @@
 
         handleInterceptActions(wmActions, when, /*byref*/ policyFlags);
     } else {
-        if (mInteractive) {
+        if (interactive) {
             policyFlags |= POLICY_FLAG_PASS_TO_USER;
         }
     }
@@ -866,7 +891,8 @@
     // - No special filtering for injected events required at this time.
     // - Filter normal events based on screen state.
     // - For normal events brighten (but do not wake) the screen if currently dim.
-    if (mInteractive) {
+    bool interactive = mInteractive.load();
+    if (interactive) {
         policyFlags |= POLICY_FLAG_INTERACTIVE;
     }
     if ((policyFlags & POLICY_FLAG_TRUSTED) && !(policyFlags & POLICY_FLAG_INJECTED)) {
@@ -885,7 +911,7 @@
             handleInterceptActions(wmActions, when, /*byref*/ policyFlags);
         }
     } else {
-        if (mInteractive) {
+        if (interactive) {
             policyFlags |= POLICY_FLAG_PASS_TO_USER;
         }
     }
diff --git a/services/usage/java/com/android/server/usage/UsageStatsDatabase.java b/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
index 4498b84..f8ae03f 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsDatabase.java
@@ -21,6 +21,7 @@
 import android.os.Build;
 import android.util.AtomicFile;
 import android.util.Slog;
+import android.util.TimeUtils;
 
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
@@ -191,7 +192,11 @@
 
                 for (File f : files) {
                     final AtomicFile af = new AtomicFile(f);
-                    mSortedStatFiles[i].put(UsageStatsXml.parseBeginTime(af), af);
+                    try {
+                        mSortedStatFiles[i].put(UsageStatsXml.parseBeginTime(af), af);
+                    } catch (IOException e) {
+                        Slog.e(TAG, "failed to index file: " + f, e);
+                    }
                 }
             }
         }
@@ -273,14 +278,21 @@
 
     public void onTimeChanged(long timeDiffMillis) {
         synchronized (mLock) {
+            StringBuilder logBuilder = new StringBuilder();
+            logBuilder.append("Time changed by ");
+            TimeUtils.formatDuration(timeDiffMillis, logBuilder);
+            logBuilder.append(".");
+
+            int filesDeleted = 0;
+            int filesMoved = 0;
+
             for (TimeSparseArray<AtomicFile> files : mSortedStatFiles) {
                 final int fileCount = files.size();
                 for (int i = 0; i < fileCount; i++) {
                     final AtomicFile file = files.valueAt(i);
                     final long newTime = files.keyAt(i) + timeDiffMillis;
                     if (newTime < 0) {
-                        Slog.i(TAG, "Deleting file " + file.getBaseFile().getAbsolutePath()
-                                + " for it is in the future now.");
+                        filesDeleted++;
                         file.delete();
                     } else {
                         try {
@@ -295,14 +307,17 @@
                         }
 
                         final File newFile = new File(file.getBaseFile().getParentFile(), newName);
-                        Slog.i(TAG, "Moving file " + file.getBaseFile().getAbsolutePath() + " to "
-                                + newFile.getAbsolutePath());
+                        filesMoved++;
                         file.getBaseFile().renameTo(newFile);
                     }
                 }
                 files.clear();
             }
 
+            logBuilder.append(" files deleted: ").append(filesDeleted);
+            logBuilder.append(" files moved: ").append(filesMoved);
+            Slog.i(TAG, logBuilder.toString());
+
             // Now re-index the new files.
             indexFilesLocked();
         }
@@ -506,7 +521,14 @@
                 if (path.endsWith(BAK_SUFFIX)) {
                     f = new File(path.substring(0, path.length() - BAK_SUFFIX.length()));
                 }
-                long beginTime = UsageStatsXml.parseBeginTime(f);
+
+                long beginTime;
+                try {
+                    beginTime = UsageStatsXml.parseBeginTime(f);
+                } catch (IOException e) {
+                    beginTime = 0;
+                }
+
                 if (beginTime < expiryTime) {
                     new AtomicFile(f).delete();
                 }
diff --git a/services/usage/java/com/android/server/usage/UsageStatsService.java b/services/usage/java/com/android/server/usage/UsageStatsService.java
index b0a14c8..a433ec45 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsService.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsService.java
@@ -42,6 +42,7 @@
 import android.content.res.Configuration;
 import android.database.ContentObserver;
 import android.hardware.display.DisplayManager;
+import android.net.NetworkScoreManager;
 import android.os.BatteryManager;
 import android.os.BatteryStats;
 import android.os.Binder;
@@ -812,6 +813,10 @@
             return false;
         }
 
+        if (isActiveNetworkScorer(packageName)) {
+            return false;
+        }
+
         if (mAppWidgetManager != null
                 && mAppWidgetManager.isBoundWidgetPackage(packageName, userId)) {
             return false;
@@ -847,6 +852,12 @@
                     == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
     }
 
+    private boolean isActiveNetworkScorer(String packageName) {
+        NetworkScoreManager nsm = (NetworkScoreManager) getContext().getSystemService(
+                Context.NETWORK_SCORE_SERVICE);
+        return packageName != null && packageName.equals(nsm.getActiveScorerPackage());
+    }
+
     void informListeners(String packageName, int userId, boolean isIdle) {
         for (AppIdleStateChangeListener listener : mPackageAccessListeners) {
             listener.onAppIdleStateChanged(packageName, userId, isIdle);
diff --git a/services/usage/java/com/android/server/usage/UsageStatsXml.java b/services/usage/java/com/android/server/usage/UsageStatsXml.java
index 186813e..543f361 100644
--- a/services/usage/java/com/android/server/usage/UsageStatsXml.java
+++ b/services/usage/java/com/android/server/usage/UsageStatsXml.java
@@ -33,11 +33,11 @@
     private static final String VERSION_ATTR = "version";
     static final String CHECKED_IN_SUFFIX = "-c";
 
-    public static long parseBeginTime(AtomicFile file) {
+    public static long parseBeginTime(AtomicFile file) throws IOException {
         return parseBeginTime(file.getBaseFile());
     }
 
-    public static long parseBeginTime(File file) {
+    public static long parseBeginTime(File file) throws IOException {
         String name = file.getName();
 
         // Eat as many occurrences of -c as possible. This is due to a bug where -c
@@ -47,7 +47,12 @@
         while (name.endsWith(CHECKED_IN_SUFFIX)) {
             name = name.substring(0, name.length() - CHECKED_IN_SUFFIX.length());
         }
-        return Long.parseLong(name);
+
+        try {
+            return Long.parseLong(name);
+        } catch (NumberFormatException e) {
+            throw new IOException(e);
+        }
     }
 
     public static void read(AtomicFile file, IntervalStats statsOut) throws IOException {
diff --git a/services/usb/java/com/android/server/usb/UsbDeviceManager.java b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
index 653cbd8..1787b91 100644
--- a/services/usb/java/com/android/server/usb/UsbDeviceManager.java
+++ b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
@@ -122,6 +122,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 +470,7 @@
                 functions = getDefaultFunctions();
             }
             functions = applyAdbFunction(functions);
+            functions = applyOemOverrideFunction(functions);
             functions = applyUserRestrictions(functions);
 
             if (!mCurrentFunctions.equals(functions) || !mCurrentFunctionsApplied
@@ -888,6 +891,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 42f879c..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);
                 }
@@ -585,16 +578,14 @@
                     Slog.w(TAG, "setDisabledShowContext without running voice interaction service");
                     return;
                 }
-                final int callingPid = Binder.getCallingPid();
                 final int callingUid = Binder.getCallingUid();
                 final long caller = Binder.clearCallingIdentity();
                 try {
-                    mImpl.setDisabledShowContextLocked(callingPid, callingUid, flags);
+                    mImpl.setDisabledShowContextLocked(callingUid, flags);
                 } finally {
                     Binder.restoreCallingIdentity(caller);
                 }
             }
-
         }
 
         @Override
@@ -604,16 +595,32 @@
                     Slog.w(TAG, "getDisabledShowContext without running voice interaction service");
                     return 0;
                 }
-                final int callingPid = Binder.getCallingPid();
                 final int callingUid = Binder.getCallingUid();
                 final long caller = Binder.clearCallingIdentity();
                 try {
-                    return mImpl.getDisabledShowContextLocked(callingPid, callingUid);
+                    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 --------------------------------//
@@ -799,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);
                 }
@@ -887,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) {
@@ -908,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 7409f99..a4facc1 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionManagerServiceImpl.java
@@ -142,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, mDisabledShowContext, showCallback);
+        return mActiveSession.showLocked(args, flags, mDisabledShowContext, showCallback,
+                activityToken);
     }
 
     public boolean hideSessionLocked() {
@@ -157,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");
@@ -189,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");
@@ -202,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");
@@ -223,7 +223,7 @@
         mActiveSession = null;
     }
 
-    public void setDisabledShowContextLocked(int callingPid, int callingUid, int flags) {
+    public void setDisabledShowContextLocked(int callingUid, int flags) {
         int activeUid = mInfo.getServiceInfo().applicationInfo.uid;
         if (callingUid != activeUid) {
             throw new SecurityException("Calling uid " + callingUid
@@ -232,7 +232,7 @@
         mDisabledShowContext = flags;
     }
 
-    public int getDisabledShowContextLocked(int callingPid, int callingUid) {
+    public int getDisabledShowContextLocked(int callingUid) {
         int activeUid = mInfo.getServiceInfo().applicationInfo.uid;
         if (callingUid != activeUid) {
             throw new SecurityException("Calling uid " + callingUid
@@ -241,6 +241,15 @@
         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: ");
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java
index dfdd639..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 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) {
+            IVoiceInteractionSessionShowCallback showCallback, IBinder activityToken) {
         if (mBound) {
             if (!mFullyBound) {
                 mFullyBound = mContext.bindServiceAsUser(mBindIntent, mFullConnection,
@@ -193,18 +206,15 @@
                         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
+            disabledContext |= getUserDisabledShowContextLocked();
+            boolean structureEnabled = isAssistDataAllowed
                     && (disabledContext&VoiceInteractionSession.SHOW_WITH_ASSIST) == 0;
-            boolean screenshotEnabled = Settings.Secure.getIntForUser(mContext.getContentResolver(),
-                    Settings.Secure.ASSIST_SCREENSHOT_ENABLED, 1, mUser) != 0
-                    && isScreenCaptureAllowed
+            boolean screenshotEnabled = isAssistDataAllowed
                     && (disabledContext&VoiceInteractionSession.SHOW_WITH_SCREENSHOT) == 0;
             mShowArgs = args;
             mShowFlags = flags;
@@ -215,9 +225,15 @@
                         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 {
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index e861668..e9c41a1 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -273,6 +273,14 @@
      */
     public static final String KEY_DEFAULT_SIM_CALL_MANAGER_STRING = "default_sim_call_manager_string";
 
+    /**
+     * The default flag specifying whether ETWS/CMAS test setting is forcibly disabled in
+     * Settings->More->Emergency broadcasts menu even though developer options is turned on.
+     * @hide
+     */
+    public static final String KEY_CARRIER_FORCE_DISABLE_ETWS_CMAS_TEST_BOOL =
+            "carrier_force_disable_etws_cmas_test_bool";
+
     /* The following 3 fields are related to carrier visual voicemail. */
 
     /**
@@ -381,6 +389,7 @@
         sDefaults.putBoolean(KEY_CARRIER_VOLTE_AVAILABLE_BOOL, false);
         sDefaults.putBoolean(KEY_CARRIER_VT_AVAILABLE_BOOL, false);
         sDefaults.putBoolean(KEY_CARRIER_WFC_IMS_AVAILABLE_BOOL, false);
+        sDefaults.putBoolean(KEY_CARRIER_FORCE_DISABLE_ETWS_CMAS_TEST_BOOL, false);
         sDefaults.putBoolean(KEY_CARRIER_VOLTE_PROVISIONING_REQUIRED_BOOL, false);
         sDefaults.putBoolean(KEY_CARRIER_VOLTE_TTY_SUPPORTED_BOOL, true);
         sDefaults.putBoolean(KEY_CARRIER_ALLOW_TURNOFF_IMS_BOOL, true);
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/VoiceInteraction/res/layout/voice_interaction_session.xml b/tests/VoiceInteraction/res/layout/voice_interaction_session.xml
index dc4e31b..b106437 100644
--- a/tests/VoiceInteraction/res/layout/voice_interaction_session.xml
+++ b/tests/VoiceInteraction/res/layout/voice_interaction_session.xml
@@ -80,6 +80,12 @@
                     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>
 
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 8796c9f..c0a67c1 100644
--- a/tests/VoiceInteraction/src/com/android/test/voiceinteraction/MainInteractionSession.java
+++ b/tests/VoiceInteraction/src/com/android/test/voiceinteraction/MainInteractionSession.java
@@ -50,6 +50,7 @@
     View mOptionsContainer;
     CheckBox mDisallowAssist;
     CheckBox mDisallowScreenshot;
+    TextView mOptionsText;
     ImageView mScreenshot;
     ImageView mFullScreenshot;
     Button mConfirmButton;
@@ -86,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);
         }
@@ -96,6 +98,7 @@
         }
         onHandleScreenshot(null);
         updateState();
+        refreshOptions();
     }
 
     @Override
@@ -134,6 +137,7 @@
         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);
@@ -145,13 +149,17 @@
     }
 
     void refreshOptions() {
-        if (mOptionsCheck.isChecked()) {
-            mOptionsContainer.setVisibility(View.VISIBLE);
-            int flags = getDisabledShowContext();
-            mDisallowAssist.setChecked((flags & SHOW_WITH_ASSIST) != 0);
-            mDisallowScreenshot.setChecked((flags & SHOW_WITH_SCREENSHOT) != 0);
-        } else {
-            mOptionsContainer.setVisibility(View.GONE);
+        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);
+            }
         }
     }
 
diff --git a/tests/VoiceInteraction/src/com/android/test/voiceinteraction/TestInteractionActivity.java b/tests/VoiceInteraction/src/com/android/test/voiceinteraction/TestInteractionActivity.java
index b0d6b39..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;
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/com/android/layoutlib/bridge/Bridge.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
index 3ae10f2..48ca7d8 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
@@ -50,6 +50,7 @@
 import java.lang.reflect.Field;
 import java.lang.reflect.Modifier;
 import java.util.Arrays;
+import java.util.Comparator;
 import java.util.EnumMap;
 import java.util.EnumSet;
 import java.util.HashMap;
@@ -93,7 +94,7 @@
     /**
      * Same as sRMap except for int[] instead of int resources. This is for android.R only.
      */
-    private final static Map<IntArray, String> sRArrayMap = new HashMap<IntArray, String>();
+    private final static Map<IntArray, String> sRArrayMap = new HashMap<IntArray, String>(384);
     /**
      * Reverse map compared to sRMap, resource type -> (resource name -> id).
      * This is for com.android.internal.R.
@@ -182,7 +183,7 @@
      */
     private static LayoutLog sCurrentLog = sDefaultLog;
 
-    private static final int LAST_SUPPORTED_FEATURE = Features.RENDER_ALL_DRAWABLE_STATES;
+    private static final int LAST_SUPPORTED_FEATURE = Features.RECYCLER_VIEW_ADAPTER;
 
     @Override
     public int getApiLevel() {
@@ -249,37 +250,56 @@
         // the internal version), and put the content in the maps.
         try {
             Class<?> r = com.android.internal.R.class;
+            // Parse the styleable class first, since it may contribute to attr values.
+            parseStyleable();
 
             for (Class<?> inner : r.getDeclaredClasses()) {
+                if (inner == com.android.internal.R.styleable.class) {
+                    // Already handled the styleable case. Not skipping attr, as there may be attrs
+                    // that are not referenced from styleables.
+                    continue;
+                }
                 String resTypeName = inner.getSimpleName();
                 ResourceType resType = ResourceType.getEnum(resTypeName);
                 if (resType != null) {
-                    Map<String, Integer> fullMap = new HashMap<String, Integer>();
-                    sRevRMap.put(resType, fullMap);
+                    Map<String, Integer> fullMap = null;
+                    switch (resType) {
+                        case ATTR:
+                            fullMap = sRevRMap.get(ResourceType.ATTR);
+                            break;
+                        case STRING:
+                        case STYLE:
+                            // Slightly less than thousand entries in each.
+                            fullMap = new HashMap<String, Integer>(1280);
+                            // no break.
+                        default:
+                            if (fullMap == null) {
+                                fullMap = new HashMap<String, Integer>();
+                            }
+                            sRevRMap.put(resType, fullMap);
+                    }
 
                     for (Field f : inner.getDeclaredFields()) {
                         // only process static final fields. Since the final attribute may have
                         // been altered by layoutlib_create, we only check static
-                        int modifiers = f.getModifiers();
-                        if (Modifier.isStatic(modifiers)) {
-                            Class<?> type = f.getType();
-                            if (type.isArray() && type.getComponentType() == int.class) {
-                                // if the object is an int[] we put it in sRArrayMap using an IntArray
-                                // wrapper that properly implements equals and hashcode for the array
-                                // objects, as required by the map contract.
-                                sRArrayMap.put(new IntArray((int[]) f.get(null)), f.getName());
-                            } else if (type == int.class) {
-                                Integer value = (Integer) f.get(null);
-                                sRMap.put(value, Pair.of(resType, f.getName()));
-                                fullMap.put(f.getName(), value);
-                            } else {
-                                assert false;
-                            }
+                        if (!isValidRField(f)) {
+                            continue;
+                        }
+                        Class<?> type = f.getType();
+                        if (type.isArray()) {
+                            // if the object is an int[] we put it in sRArrayMap using an IntArray
+                            // wrapper that properly implements equals and hashcode for the array
+                            // objects, as required by the map contract.
+                            sRArrayMap.put(new IntArray((int[]) f.get(null)), f.getName());
+                        } else {
+                            Integer value = (Integer) f.get(null);
+                            sRMap.put(value, Pair.of(resType, f.getName()));
+                            fullMap.put(f.getName(), value);
                         }
                     }
                 }
             }
-        } catch (Throwable throwable) {
+        } catch (Exception throwable) {
             if (log != null) {
                 log.error(LayoutLog.TAG_BROKEN,
                         "Failed to load com.android.internal.R from the layout library jar",
@@ -291,6 +311,90 @@
         return true;
     }
 
+    /**
+     * Tests if the field is pubic, static and one of int or int[].
+     */
+    private static boolean isValidRField(Field field) {
+        int modifiers = field.getModifiers();
+        boolean isAcceptable = Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers);
+        Class<?> type = field.getType();
+        return isAcceptable && type == int.class ||
+                (type.isArray() && type.getComponentType() == int.class);
+
+    }
+
+    private static void parseStyleable() throws Exception {
+        // R.attr doesn't contain all the needed values. There are too many resources in the
+        // framework for all to be in the R class. Only the ones specified manually in
+        // res/values/symbols.xml are put in R class. Since, we need to create a map of all attr
+        // values, we try and find them from the styleables.
+
+        // There were 1500 elements in this map at M timeframe.
+        Map<String, Integer> revRAttrMap = new HashMap<String, Integer>(2048);
+        sRevRMap.put(ResourceType.ATTR, revRAttrMap);
+        // There were 2000 elements in this map at M timeframe.
+        Map<String, Integer> revRStyleableMap = new HashMap<String, Integer>(3072);
+        sRevRMap.put(ResourceType.STYLEABLE, revRStyleableMap);
+        Class<?> c = com.android.internal.R.styleable.class;
+        Field[] fields = c.getDeclaredFields();
+        // Sort the fields to bring all arrays to the beginning, so that indices into the array are
+        // able to refer back to the arrays (i.e. no forward references).
+        Arrays.sort(fields, new Comparator<Field>() {
+            @Override
+            public int compare(Field o1, Field o2) {
+                if (o1 == o2) {
+                    return 0;
+                }
+                Class<?> t1 = o1.getType();
+                Class<?> t2 = o2.getType();
+                if (t1.isArray() && !t2.isArray()) {
+                    return -1;
+                } else if (t2.isArray() && !t1.isArray()) {
+                    return 1;
+                }
+                return o1.getName().compareTo(o2.getName());
+            }
+        });
+        Map<String, int[]> styleables = new HashMap<String, int[]>();
+        for (Field field : fields) {
+            if (!isValidRField(field)) {
+                // Only consider public static fields that are int or int[].
+                // Don't check the final flag as it may have been modified by layoutlib_create.
+                continue;
+            }
+            String name = field.getName();
+            if (field.getType().isArray()) {
+                int[] styleableValue = (int[]) field.get(null);
+                sRArrayMap.put(new IntArray(styleableValue), name);
+                styleables.put(name, styleableValue);
+                continue;
+            }
+            // Not an array.
+            String arrayName = name;
+            int[] arrayValue = null;
+            int index;
+            while ((index = arrayName.lastIndexOf('_')) >= 0) {
+                // Find the name of the corresponding styleable.
+                // Search in reverse order so that attrs like LinearLayout_Layout_layout_gravity
+                // are mapped to LinearLayout_Layout and not to LinearLayout.
+                arrayName = arrayName.substring(0, index);
+                arrayValue = styleables.get(arrayName);
+                if (arrayValue != null) {
+                    break;
+                }
+            }
+            index = (Integer) field.get(null);
+            if (arrayValue != null) {
+                String attrName = name.substring(arrayName.length() + 1);
+                int attrValue = arrayValue[index];
+                sRMap.put(attrValue, Pair.of(ResourceType.ATTR, attrName));
+                revRAttrMap.put(attrName, attrValue);
+            }
+            sRMap.put(index, Pair.of(ResourceType.STYLEABLE, name));
+            revRStyleableMap.put(name, index);
+        }
+    }
+
     @Override
     public boolean dispose() {
         BridgeAssetManager.clearSystem();
@@ -490,9 +594,13 @@
 
     /**
      * Returns the integer id of a framework resource, from a given resource type and resource name.
+     * <p/>
+     * If no resource is found, it creates a dynamic id for the resource.
+     *
      * @param type the type of the resource
      * @param name the name of the resource.
-     * @return an {@link Integer} containing the resource id, or null if no resource were found.
+     *
+     * @return an {@link Integer} containing the resource id.
      */
     @NonNull
     public static Integer getResourceId(ResourceType type, String name) {
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/AppCompatActionBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/AppCompatActionBar.java
index 958b7aa..868c6d3 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/AppCompatActionBar.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/AppCompatActionBar.java
@@ -31,7 +31,6 @@
 import android.view.ContextThemeWrapper;
 import android.view.LayoutInflater;
 import android.view.View;
-import android.view.ViewGroup;
 import android.widget.FrameLayout;
 
 import java.lang.reflect.InvocationTargetException;
@@ -51,9 +50,8 @@
     /**
      * Inflate the action bar and attach it to {@code parentView}
      */
-    public AppCompatActionBar(@NonNull BridgeContext context, @NonNull SessionParams params,
-            @NonNull ViewGroup parentView) {
-        super(context, params, parentView);
+    public AppCompatActionBar(@NonNull BridgeContext context, @NonNull SessionParams params) {
+        super(context, params);
         int contentRootId = context.getProjectResourceValue(ResourceType.ID,
                 "action_bar_activity_content", 0);
         View contentView = getDecorContent().findViewById(contentRootId);
@@ -64,7 +62,9 @@
             // Something went wrong. Create a new FrameLayout in the enclosing layout.
             FrameLayout contentRoot = new FrameLayout(context);
             setMatchParent(contentRoot);
-            mEnclosingLayout.addView(contentRoot);
+            if (mEnclosingLayout != null) {
+                mEnclosingLayout.addView(contentRoot);
+            }
             setContentRoot(contentRoot);
         }
         try {
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/BridgeActionBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/BridgeActionBar.java
index a19b689f1..f900b45 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/BridgeActionBar.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/BridgeActionBar.java
@@ -24,6 +24,7 @@
 import com.android.layoutlib.bridge.android.BridgeContext;
 
 import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
@@ -39,7 +40,7 @@
     @NonNull protected final BridgeContext mBridgeContext;
     @NonNull protected final SessionParams mParams;
     // A Layout that contains the inflated action bar. The menu popup is added to this layout.
-    @NonNull protected final ViewGroup mEnclosingLayout;
+    @Nullable protected final ViewGroup mEnclosingLayout;
 
     private final View mDecorContent;
     private final ActionBarCallback mCallback;
@@ -47,8 +48,7 @@
     @SuppressWarnings("NullableProblems")  // Should be initialized by subclasses.
     @NonNull private FrameLayout mContentRoot;
 
-    public BridgeActionBar(@NonNull BridgeContext context, @NonNull SessionParams params,
-            @NonNull ViewGroup parentView) {
+    public BridgeActionBar(@NonNull BridgeContext context, @NonNull SessionParams params) {
         mBridgeContext = context;
         mParams = params;
         mCallback = params.getLayoutlibCallback().getActionBarCallback();
@@ -75,14 +75,13 @@
             // added.
             mEnclosingLayout = new RelativeLayout(mBridgeContext);
             setMatchParent(mEnclosingLayout);
-            parentView.addView(mEnclosingLayout);
         } else {
-            mEnclosingLayout = parentView;
+            mEnclosingLayout = null;
         }
 
         // Inflate action bar layout.
-        mDecorContent = getInflater(context).inflate(layoutId, mEnclosingLayout, true);
-
+        mDecorContent =
+                getInflater(context).inflate(layoutId, mEnclosingLayout, mEnclosingLayout != null);
     }
 
     /**
@@ -153,6 +152,13 @@
 
     public abstract void createMenuPopup();
 
+    /**
+     * The root view that represents the action bar and possibly the content included in it.
+     */
+    public View getRootView() {
+        return mEnclosingLayout == null ? mDecorContent : mEnclosingLayout;
+    }
+
     public ActionBarCallback getCallBack() {
         return mCallback;
     }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/CustomBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/CustomBar.java
index 90a1c75..145a03a 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/CustomBar.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/CustomBar.java
@@ -32,7 +32,6 @@
 import org.xmlpull.v1.XmlPullParserException;
 
 import android.annotation.NonNull;
-import android.content.Context;
 import android.content.res.ColorStateList;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap_Delegate;
@@ -68,7 +67,7 @@
     protected abstract TextView getStyleableTextView();
 
     protected CustomBar(BridgeContext context, int orientation, String layoutPath,
-            String name, int simulatedPlatformVersion) throws XmlPullParserException {
+            String name, int simulatedPlatformVersion) {
         super(context);
         mSimulatedPlatformVersion = simulatedPlatformVersion;
         setOrientation(orientation);
@@ -78,14 +77,18 @@
             setGravity(Gravity.CENTER_HORIZONTAL);
         }
 
-        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(
-                Context.LAYOUT_INFLATER_SERVICE);
+        LayoutInflater inflater = LayoutInflater.from(mContext);
 
-        XmlPullParser parser = ParserFactory.create(getClass().getResourceAsStream(layoutPath),
-                name);
+        XmlPullParser parser;
+        try {
+            parser = ParserFactory.create(getClass().getResourceAsStream(layoutPath), name);
+        } catch (XmlPullParserException e) {
+            // Should not happen as the resource is bundled with the jar, and  ParserFactory should
+            // have been initialized.
+            throw new AssertionError(e);
+        }
 
-        BridgeXmlBlockParser bridgeParser = new BridgeXmlBlockParser(
-                parser, (BridgeContext) context, false /*platformFile*/);
+        BridgeXmlBlockParser bridgeParser = new BridgeXmlBlockParser(parser, context, false);
 
         try {
             inflater.inflate(bridgeParser, this, true);
@@ -154,7 +157,7 @@
 
     protected void setStyle(String themeEntryName) {
 
-        BridgeContext bridgeContext = (BridgeContext) mContext;
+        BridgeContext bridgeContext = getContext();
         RenderResources res = bridgeContext.getRenderResources();
 
         ResourceValue value = res.findItemInTheme(themeEntryName, true /*isFrameworkAttr*/);
@@ -214,27 +217,47 @@
         }
     }
 
+    @Override
+    public BridgeContext getContext() {
+        return (BridgeContext) mContext;
+    }
+
     /**
-     * Given a theme attribute name, get the color referenced by it. The theme attribute may be
-     * used in a layout like "?attr/foo".
+     * Find the background color for this bar from the theme attributes. Only relevant to StatusBar
+     * and NavigationBar.
      * <p/>
      * Returns 0 if not found.
      *
+     * @param colorAttrName the attribute name for the background color
+     * @param translucentAttrName the attribute name for the translucency property of the bar.
+     *
      * @throws NumberFormatException if color resolved to an invalid string.
      */
-    protected int getThemeAttrColor(@NonNull String attrName, boolean isFramework) {
+    protected int getBarColor(@NonNull String colorAttrName, @NonNull String translucentAttrName) {
         if (!Config.isGreaterOrEqual(mSimulatedPlatformVersion, LOLLIPOP)) {
             return 0;
         }
-        assert mContext instanceof BridgeContext;
-        BridgeContext context = ((BridgeContext) mContext);
-        RenderResources renderResources = context.getRenderResources();
-        // From ?attr/foo to @color/bar. This is most likely an ItemResourceValue.
-        ResourceValue resource = renderResources.findItemInTheme(attrName, isFramework);
-        if (resource != null) {
-            // Form @color/bar to the #AARRGGBB
-            resource = renderResources.resolveResValue(resource);
+        RenderResources renderResources = getContext().getRenderResources();
+        // First check if the bar is translucent.
+        boolean translucent = ResourceHelper.getBooleanThemeValue(renderResources,
+                translucentAttrName, true, false);
+        if (translucent) {
+            // Keep in sync with R.color.system_bar_background_semi_transparent from system ui.
+            return 0x66000000;  // 40% black.
         }
+        boolean transparent = ResourceHelper.getBooleanThemeValue(renderResources,
+                "windowDrawsSystemBarBackgrounds", true, false);
+        if (transparent) {
+            return getColor(renderResources, colorAttrName);
+        }
+        return 0;
+    }
+
+    private static int getColor(RenderResources renderResources, String attr) {
+        // From ?attr/foo to @color/bar. This is most likely an ItemResourceValue.
+        ResourceValue resource = renderResources.findItemInTheme(attr, true);
+        // Form @color/bar to the #AARRGGBB
+        resource = renderResources.resolveResValue(resource);
         if (resource != null && ResourceType.COLOR.equals(resource.getResourceType())) {
             return ResourceHelper.getColor(resource.getValue());
         }
@@ -242,8 +265,7 @@
     }
 
     private ResourceValue getResourceValue(String reference) {
-        BridgeContext bridgeContext = (BridgeContext) mContext;
-        RenderResources res = bridgeContext.getRenderResources();
+        RenderResources res = getContext().getRenderResources();
 
         // find the resource
         ResourceValue value = res.findResValue(reference, false);
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/FrameworkActionBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/FrameworkActionBar.java
index bb3d13f..d2a5117 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/FrameworkActionBar.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/FrameworkActionBar.java
@@ -60,23 +60,24 @@
     /**
      * Inflate the action bar and attach it to {@code parentView}
      */
-    public FrameworkActionBar(@NonNull BridgeContext context, @NonNull SessionParams params,
-            @NonNull ViewGroup parentView) {
-        super(context, params, parentView);
+    public FrameworkActionBar(@NonNull BridgeContext context, @NonNull SessionParams params) {
+        super(context, params);
 
         View decorContent = getDecorContent();
 
         mActionBar = FrameworkActionBarWrapper.getActionBarWrapper(context, getCallBack(),
                 decorContent);
 
-        FrameLayout contentRoot = (FrameLayout) mEnclosingLayout.findViewById(android.R.id.content);
+        FrameLayout contentRoot = (FrameLayout) decorContent.findViewById(android.R.id.content);
 
         // If something went wrong and we were not able to initialize the content root,
         // just add a frame layout inside this and return.
         if (contentRoot == null) {
             contentRoot = new FrameLayout(context);
             setMatchParent(contentRoot);
-            mEnclosingLayout.addView(contentRoot);
+            if (mEnclosingLayout != null) {
+                mEnclosingLayout.addView(contentRoot);
+            }
             setContentRoot(contentRoot);
         } else {
             setContentRoot(contentRoot);
@@ -162,6 +163,7 @@
         listView.setDivider(a.getDrawable(R.attr.actionBarDivider));
         a.recycle();
         listView.setElevation(mActionBar.getMenuPopupElevation());
+        assert mEnclosingLayout != null : "Unable to find view to attach ActionMenuPopup.";
         mEnclosingLayout.addView(listView);
     }
 
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/FrameworkActionBarWrapper.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/FrameworkActionBarWrapper.java
index daad602..af6ba24 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/FrameworkActionBarWrapper.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/FrameworkActionBarWrapper.java
@@ -79,7 +79,7 @@
         }
     }
 
-    FrameworkActionBarWrapper(@NonNull BridgeContext context, ActionBarCallback callback,
+    FrameworkActionBarWrapper(@NonNull BridgeContext context, @NonNull ActionBarCallback callback,
             @NonNull ActionBar actionBar) {
         mActionBar = actionBar;
         mCallback = callback;
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/NavigationBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/NavigationBar.java
index dcf82a3..9c89bfe2 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/NavigationBar.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/NavigationBar.java
@@ -19,8 +19,6 @@
 import com.android.layoutlib.bridge.android.BridgeContext;
 import com.android.resources.Density;
 
-import org.xmlpull.v1.XmlPullParserException;
-
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.util.AttributeSet;
@@ -33,6 +31,8 @@
 
     /** Navigation bar background color attribute name. */
     private static final String ATTR_COLOR = "navigationBarColor";
+    /** Attribute for translucency property. */
+    public static final String ATTR_TRANSLUCENT = "windowTranslucentNavigation";
     // These correspond to @dimen/navigation_side_padding in the system ui code.
     private static final int PADDING_WIDTH_DEFAULT = 36;
     private static final int PADDING_WIDTH_SW360 = 40;
@@ -49,8 +49,8 @@
      * Constructor to be used when creating the {@link NavigationBar} as a regular control.
      * This is currently used by the theme editor.
      */
-    public NavigationBar(Context context, AttributeSet attrs)
-            throws XmlPullParserException {
+    @SuppressWarnings("unused")
+    public NavigationBar(Context context, AttributeSet attrs) {
         this((BridgeContext) context,
                 Density.getEnum(((BridgeContext) context).getMetrics().densityDpi),
                 LinearLayout.HORIZONTAL, // In this mode, it doesn't need to be render vertically
@@ -61,11 +61,11 @@
     }
 
     public NavigationBar(BridgeContext context, Density density, int orientation, boolean isRtl,
-            boolean rtlEnabled, int simulatedPlatformVersion) throws XmlPullParserException {
+            boolean rtlEnabled, int simulatedPlatformVersion) {
         super(context, orientation, getShortestWidth(context)>= 600 ? LAYOUT_600DP_XML : LAYOUT_XML,
                 "navigation_bar.xml", simulatedPlatformVersion);
 
-        int color = getThemeAttrColor(ATTR_COLOR, true);
+        int color = getBarColor(ATTR_COLOR, ATTR_TRANSLUCENT);
         setBackgroundColor(color == 0 ? 0xFF000000 : color);
 
         // Cannot access the inside items through id because no R.id values have been
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/StatusBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/StatusBar.java
index a0ed0e8..2dc7c65 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/StatusBar.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/StatusBar.java
@@ -26,6 +26,7 @@
 import org.xmlpull.v1.XmlPullParserException;
 
 import android.content.Context;
+import android.content.pm.ApplicationInfo;
 import android.graphics.drawable.Drawable;
 import android.util.AttributeSet;
 import android.view.Gravity;
@@ -42,22 +43,26 @@
     private final int mSimulatedPlatformVersion;
     /** Status bar background color attribute name. */
     private static final String ATTR_COLOR = "statusBarColor";
+    /** Attribute for translucency property. */
+    public static final String ATTR_TRANSLUCENT = "windowTranslucentStatus";
 
     /**
      * Constructor to be used when creating the {@link StatusBar} as a regular control. This
      * is currently used by the theme editor.
      */
-    public StatusBar(Context context, AttributeSet attrs) throws XmlPullParserException {
+    @SuppressWarnings("UnusedParameters")
+    public StatusBar(Context context, AttributeSet attrs) {
         this((BridgeContext) context,
                 Density.getEnum(((BridgeContext) context).getMetrics().densityDpi),
-                LinearLayout.HORIZONTAL, // In this mode, it doesn't need to be render vertically
                 ((BridgeContext) context).getConfiguration().getLayoutDirection() ==
                         View.LAYOUT_DIRECTION_RTL,
+                (context.getApplicationInfo().flags & ApplicationInfo.FLAG_SUPPORTS_RTL) != 0,
                 context.getApplicationInfo().targetSdkVersion);
     }
 
-    public StatusBar(BridgeContext context, Density density, int direction, boolean RtlEnabled,
-            int simulatedPlatformVersion) throws XmlPullParserException {
+    @SuppressWarnings("UnusedParameters")
+    public StatusBar(BridgeContext context, Density density, boolean isRtl, boolean rtlEnabled,
+            int simulatedPlatformVersion) {
         // FIXME: if direction is RTL but it's not enabled in application manifest, mirror this bar.
         super(context, LinearLayout.HORIZONTAL, "/bars/status_bar.xml", "status_bar.xml",
                 simulatedPlatformVersion);
@@ -66,7 +71,7 @@
         // FIXME: use FILL_H?
         setGravity(Gravity.START | Gravity.TOP | Gravity.RIGHT);
 
-        int color = getThemeAttrColor(ATTR_COLOR, true);
+        int color = getBarColor(ATTR_COLOR, ATTR_TRANSLUCENT);
         setBackgroundColor(color == 0 ? Config.getStatusBarColor(simulatedPlatformVersion) : color);
 
         // Cannot access the inside items through id because no R.id values have been
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TitleBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TitleBar.java
index c610601..4fe1001 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TitleBar.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TitleBar.java
@@ -27,8 +27,7 @@
 
     private TextView mTextView;
 
-    public TitleBar(BridgeContext context, String label, int simulatedPlatformVersion)
-            throws XmlPullParserException {
+    public TitleBar(BridgeContext context, String label, int simulatedPlatformVersion) {
         super(context, LinearLayout.HORIZONTAL, "/bars/title_bar.xml", "title_bar.xml",
                 simulatedPlatformVersion);
 
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/Layout.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/Layout.java
new file mode 100644
index 0000000..89d8319
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/Layout.java
@@ -0,0 +1,459 @@
+/*
+ * 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.impl;
+
+import com.android.ide.common.rendering.api.HardwareConfig;
+import com.android.ide.common.rendering.api.RenderResources;
+import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.ide.common.rendering.api.SessionParams;
+import com.android.ide.common.rendering.api.StyleResourceValue;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.android.BridgeContext;
+import com.android.layoutlib.bridge.bars.AppCompatActionBar;
+import com.android.layoutlib.bridge.bars.BridgeActionBar;
+import com.android.layoutlib.bridge.bars.Config;
+import com.android.layoutlib.bridge.bars.FrameworkActionBar;
+import com.android.layoutlib.bridge.bars.NavigationBar;
+import com.android.layoutlib.bridge.bars.StatusBar;
+import com.android.layoutlib.bridge.bars.TitleBar;
+import com.android.resources.Density;
+import com.android.resources.ResourceType;
+import com.android.resources.ScreenOrientation;
+
+import android.annotation.NonNull;
+import android.graphics.drawable.Drawable;
+import android.util.DisplayMetrics;
+import android.util.TypedValue;
+import android.view.View;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+import android.widget.RelativeLayout;
+
+import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
+import static android.widget.LinearLayout.VERTICAL;
+
+/**
+ * The Layout used to create the system decor.
+ *
+ * The layout inflated will contain a content frame where the user's layout can be inflated.
+ * <pre>
+ *  +-------------------------------------------------+---+
+ *  | Status bar                                      | N |
+ *  +-------------------------------------------------+ a |
+ *  | Title/Action bar (optional)                     | v |
+ *  +-------------------------------------------------+   |
+ *  | Content, vertical extending                     | b |
+ *  |                                                 | a |
+ *  |                                                 | r |
+ *  +-------------------------------------------------+---+
+ * </pre>
+ * or
+ * <pre>
+ *  +-------------------------------------+
+ *  | Status bar                          |
+ *  +-------------------------------------+
+ *  | Title/Action bar (optional)         |
+ *  +-------------------------------------+
+ *  | Content, vertical extending         |
+ *  |                                     |
+ *  |                                     |
+ *  +-------------------------------------+
+ *  | Nav bar                             |
+ *  +-------------------------------------+
+ * </pre>
+ *
+ */
+class Layout extends RelativeLayout {
+
+    // Theme attributes used for configuring appearance of the system decor.
+    private static final String ATTR_WINDOW_FLOATING = "windowIsFloating";
+    private static final String ATTR_WINDOW_BACKGROUND = "windowBackground";
+    private static final String ATTR_WINDOW_FULL_SCREEN = "windowFullScreen";
+    private static final String ATTR_NAV_BAR_HEIGHT = "navigation_bar_height";
+    private static final String ATTR_NAV_BAR_WIDTH = "navigation_bar_width";
+    private static final String ATTR_STATUS_BAR_HEIGHT = "status_bar_height";
+    private static final String ATTR_WINDOW_ACTION_BAR = "windowActionBar";
+    private static final String ATTR_ACTION_BAR_SIZE = "actionBarSize";
+    private static final String ATTR_WINDOW_NO_TITLE = "windowNoTitle";
+    private static final String ATTR_WINDOW_TITLE_SIZE = "windowTitleSize";
+    private static final String ATTR_WINDOW_TRANSLUCENT_STATUS = StatusBar.ATTR_TRANSLUCENT;
+    private static final String ATTR_WINDOW_TRANSLUCENT_NAV = NavigationBar.ATTR_TRANSLUCENT;
+    private static final String PREFIX_THEME_APPCOMPAT = "Theme.AppCompat";
+
+    // Default sizes
+    private static final int DEFAULT_STATUS_BAR_HEIGHT = 25;
+    private static final int DEFAULT_TITLE_BAR_HEIGHT = 25;
+    private static final int DEFAULT_NAV_BAR_SIZE = 48;
+
+    // Ids assigned to components created. This is so that we can refer to other components in
+    // layout params.
+    private static final String ID_NAV_BAR = "navBar";
+    private static final String ID_STATUS_BAR = "statusBar";
+    private static final String ID_TITLE_BAR = "titleBar";
+    // Prefix used with the above ids in order to make them unique in framework namespace.
+    private static final String ID_PREFIX = "android_layoutlib_";
+
+    /**
+     * Temporarily store the builder so that it doesn't have to be passed to all methods used
+     * during inflation.
+     */
+    private Builder mBuilder;
+
+    /**
+     * This holds user's layout.
+     */
+    private FrameLayout mContentRoot;
+
+    public Layout(@NonNull Builder builder) {
+        super(builder.mContext);
+        mBuilder = builder;
+        if (builder.mWindowBackground != null) {
+            Drawable d = ResourceHelper.getDrawable(builder.mWindowBackground, builder.mContext);
+            setBackground(d);
+        }
+
+        int simulatedPlatformVersion = getParams().getSimulatedPlatformVersion();
+        HardwareConfig hwConfig = getParams().getHardwareConfig();
+        Density density = hwConfig.getDensity();
+        boolean isRtl = Bridge.isLocaleRtl(getParams().getLocale());
+
+        NavigationBar navBar = null;
+        if (mBuilder.hasNavBar()) {
+            navBar = createNavBar(getContext(), density, isRtl, getParams().isRtlSupported(),
+                    simulatedPlatformVersion);
+        }
+
+        StatusBar statusBar = null;
+        if (builder.mStatusBarSize > 0) {
+            statusBar = createStatusBar(getContext(), density, isRtl, getParams().isRtlSupported(),
+                    simulatedPlatformVersion);
+        }
+
+        View actionBar = null;
+        TitleBar titleBar = null;
+        if (builder.mActionBarSize > 0) {
+            BridgeActionBar bar = createActionBar(getContext(), getParams());
+            mContentRoot = bar.getContentRoot();
+            actionBar = bar.getRootView();
+        } else if (mBuilder.mTitleBarSize > 0) {
+            titleBar = createTitleBar(getContext(), getParams().getAppLabel(),
+                    simulatedPlatformVersion);
+        }
+
+        addViews(titleBar, mContentRoot == null ? (mContentRoot = createContentFrame()) : actionBar,
+                statusBar, navBar);
+        // Done with the builder. Don't hold a reference to it.
+        mBuilder = null;
+     }
+
+    @NonNull
+    private FrameLayout createContentFrame() {
+        FrameLayout contentRoot = new FrameLayout(getContext());
+        LayoutParams params = createLayoutParams(MATCH_PARENT, MATCH_PARENT);
+        int rule = mBuilder.isNavBarVertical() ? START_OF : ABOVE;
+        if (mBuilder.solidBars()) {
+            params.addRule(rule, getId(ID_NAV_BAR));
+        }
+        int below = -1;
+        if (mBuilder.mActionBarSize <= 0 && mBuilder.mTitleBarSize > 0) {
+            below = getId(ID_TITLE_BAR);
+        } else if (mBuilder.solidBars()) {
+            below = getId(ID_STATUS_BAR);
+        }
+        if (below != -1) {
+            params.addRule(BELOW, below);
+        }
+        contentRoot.setLayoutParams(params);
+        return contentRoot;
+    }
+
+    @NonNull
+    private LayoutParams createLayoutParams(int width, int height) {
+        DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
+        if (width > 0) {
+            width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, metrics);
+        }
+        if (height > 0) {
+            height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, metrics);
+        }
+        return new LayoutParams(width, height);
+    }
+
+    @NonNull
+    public FrameLayout getContentRoot() {
+        return mContentRoot;
+    }
+
+    @NonNull
+    private SessionParams getParams() {
+        return mBuilder.mParams;
+    }
+
+    @NonNull
+    @Override
+    public BridgeContext getContext(){
+        return (BridgeContext) super.getContext();
+    }
+
+    /**
+     * @param isRtl    whether the current locale is an RTL locale.
+     * @param isRtlSupported    whether the applications supports RTL (i.e. has supportsRtl=true
+     * in the manifest and targetSdkVersion >= 17.
+     */
+    @NonNull
+    private StatusBar createStatusBar(BridgeContext context, Density density, boolean isRtl,
+            boolean isRtlSupported, int simulatedPlatformVersion) {
+        StatusBar statusBar =
+                new StatusBar(context, density, isRtl, isRtlSupported, simulatedPlatformVersion);
+        LayoutParams params = createLayoutParams(MATCH_PARENT, mBuilder.mStatusBarSize);
+        if (mBuilder.isNavBarVertical()) {
+            params.addRule(START_OF, getId(ID_NAV_BAR));
+        }
+        statusBar.setLayoutParams(params);
+        statusBar.setId(getId(ID_STATUS_BAR));
+        return statusBar;
+    }
+
+    private BridgeActionBar createActionBar(@NonNull BridgeContext context,
+            @NonNull SessionParams params) {
+        BridgeActionBar actionBar;
+        if (mBuilder.isThemeAppCompat()) {
+            actionBar = new AppCompatActionBar(context, params);
+        } else {
+            actionBar = new FrameworkActionBar(context, params);
+        }
+        LayoutParams layoutParams = createLayoutParams(MATCH_PARENT, MATCH_PARENT);
+        int rule = mBuilder.isNavBarVertical() ? START_OF : ABOVE;
+        if (mBuilder.solidBars()) {
+            layoutParams.addRule(rule, getId(ID_NAV_BAR));
+        }
+        if (mBuilder.solidBars()) {
+            layoutParams.addRule(BELOW, getId(ID_STATUS_BAR));
+        }
+        actionBar.getRootView().setLayoutParams(layoutParams);
+        actionBar.createMenuPopup();
+        return actionBar;
+    }
+
+    @NonNull
+    private TitleBar createTitleBar(BridgeContext context, String title,
+            int simulatedPlatformVersion) {
+        TitleBar titleBar = new TitleBar(context, title, simulatedPlatformVersion);
+        LayoutParams params = createLayoutParams(MATCH_PARENT, mBuilder.mTitleBarSize);
+        if (mBuilder.solidBars()) {
+            params.addRule(BELOW, getId(ID_STATUS_BAR));
+        }
+        if (mBuilder.isNavBarVertical() && mBuilder.solidBars()) {
+            params.addRule(START_OF, getId(ID_NAV_BAR));
+        }
+        titleBar.setLayoutParams(params);
+        titleBar.setId(getId(ID_TITLE_BAR));
+        return titleBar;
+    }
+
+    /**
+     * @param isRtl    whether the current locale is an RTL locale.
+     * @param isRtlSupported    whether the applications supports RTL (i.e. has supportsRtl=true
+     * in the manifest and targetSdkVersion >= 17.
+     */
+    @NonNull
+    private NavigationBar createNavBar(BridgeContext context, Density density, boolean isRtl,
+            boolean isRtlSupported, int simulatedPlatformVersion) {
+        int orientation = mBuilder.mNavBarOrientation;
+        int size = mBuilder.mNavBarSize;
+        NavigationBar navBar = new NavigationBar(context, density, orientation, isRtl,
+                isRtlSupported, simulatedPlatformVersion);
+        boolean isVertical = mBuilder.isNavBarVertical();
+        int w = isVertical ? size : MATCH_PARENT;
+        int h = isVertical ? MATCH_PARENT : size;
+        LayoutParams params = createLayoutParams(w, h);
+        params.addRule(isVertical ? ALIGN_PARENT_END : ALIGN_PARENT_BOTTOM);
+        navBar.setLayoutParams(params);
+        navBar.setId(getId(ID_NAV_BAR));
+        return navBar;
+    }
+
+    private void addViews(@NonNull View... views) {
+        for (View view : views) {
+            if (view != null) {
+                addView(view);
+            }
+        }
+    }
+
+    private int getId(String name) {
+        return Bridge.getResourceId(ResourceType.ID, ID_PREFIX + name);
+    }
+
+    /**
+     * A helper class to help initialize the Layout.
+     */
+    static class Builder {
+        @NonNull
+        private final SessionParams mParams;
+        @NonNull
+        private final BridgeContext mContext;
+        private final RenderResources mResources;
+        
+        private final boolean mWindowIsFloating;
+        private ResourceValue mWindowBackground;
+        private int mStatusBarSize;
+        private int mNavBarSize;
+        private int mNavBarOrientation;
+        private int mActionBarSize;
+        private int mTitleBarSize;
+        private boolean mTranslucentStatus;
+        private boolean mTranslucentNav;
+
+        private Boolean mIsThemeAppCompat;
+
+        public Builder(@NonNull SessionParams params, @NonNull BridgeContext context) {
+            mParams = params;
+            mContext = context;
+            mResources = mParams.getResources();
+            mWindowIsFloating = ResourceHelper.getBooleanThemeValue(mResources, ATTR_WINDOW_FLOATING, true, true);
+            
+            findBackground();
+            findStatusBar();
+            findActionBar();
+            findNavBar();
+        }
+
+        public boolean isNavBarVertical() {
+            return mNavBarOrientation == VERTICAL;
+        }
+
+        private void findBackground() {
+            if (!mParams.isBgColorOverridden()) {
+                mWindowBackground = mResources.findItemInTheme(ATTR_WINDOW_BACKGROUND, true);
+                mWindowBackground = mResources.resolveResValue(mWindowBackground);
+            }
+        }
+
+        private void findStatusBar() {
+            boolean windowFullScreen =
+                    ResourceHelper.getBooleanThemeValue(mResources, ATTR_WINDOW_FULL_SCREEN, true, false);
+            if (!windowFullScreen && !mWindowIsFloating) {
+                mStatusBarSize =
+                        getDimension(ATTR_STATUS_BAR_HEIGHT, true, DEFAULT_STATUS_BAR_HEIGHT);
+                mTranslucentStatus = ResourceHelper.getBooleanThemeValue(mResources,
+                        ATTR_WINDOW_TRANSLUCENT_STATUS, true, false);
+            }
+        }
+
+        private void  findActionBar() {
+            if (mWindowIsFloating) {
+                return;
+            }
+            // Check if an actionbar is needed
+            boolean windowActionBar = ResourceHelper.getBooleanThemeValue(mResources, ATTR_WINDOW_ACTION_BAR,
+                    !isThemeAppCompat(), true);
+            if (windowActionBar) {
+                mActionBarSize = getDimension(ATTR_ACTION_BAR_SIZE, true, DEFAULT_TITLE_BAR_HEIGHT);
+            } else {
+                // Maybe the gingerbread era title bar is needed
+                boolean windowNoTitle =
+                        ResourceHelper.getBooleanThemeValue(mResources, ATTR_WINDOW_NO_TITLE, true, false);
+                if (!windowNoTitle) {
+                    mTitleBarSize =
+                            getDimension(ATTR_WINDOW_TITLE_SIZE, true, DEFAULT_TITLE_BAR_HEIGHT);
+                }
+            }
+        }
+
+        private void findNavBar() {
+            if (hasSoftwareButtons() && !mWindowIsFloating) {
+
+                // get orientation
+                HardwareConfig hwConfig = mParams.getHardwareConfig();
+                boolean barOnBottom = true;
+
+                if (hwConfig.getOrientation() == ScreenOrientation.LANDSCAPE) {
+                    int shortSize = hwConfig.getScreenHeight();
+                    int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT /
+                            hwConfig.getDensity().getDpiValue();
+
+                    // 0-599dp: "phone" UI with bar on the side
+                    // 600+dp: "tablet" UI with bar on the bottom
+                    barOnBottom = shortSizeDp >= 600;
+                }
+
+                mNavBarOrientation = barOnBottom ? LinearLayout.HORIZONTAL : VERTICAL;
+                mNavBarSize = getDimension(barOnBottom ? ATTR_NAV_BAR_HEIGHT : ATTR_NAV_BAR_WIDTH,
+                        true, DEFAULT_NAV_BAR_SIZE);
+                mTranslucentNav = ResourceHelper.getBooleanThemeValue(mResources,
+                        ATTR_WINDOW_TRANSLUCENT_NAV, true, false);
+            }
+        }
+
+        private int getDimension(String attr, boolean isFramework, int defaultValue) {
+            ResourceValue value = mResources.findItemInTheme(attr, isFramework);
+            value = mResources.resolveResValue(value);
+            if (value != null) {
+                TypedValue typedValue = ResourceHelper.getValue(attr, value.getValue(), true);
+                if (typedValue != null) {
+                    return (int) typedValue.getDimension(mContext.getMetrics());
+                }
+            }
+            return defaultValue;
+        }
+
+        private boolean hasSoftwareButtons() {
+            return mParams.getHardwareConfig().hasSoftwareButtons();
+        }
+
+        private boolean isThemeAppCompat() {
+            // If a cached value exists, return it.
+            if (mIsThemeAppCompat != null) {
+                return mIsThemeAppCompat;
+            }
+            // Ideally, we should check if the corresponding activity extends
+            // android.support.v7.app.ActionBarActivity, and not care about the theme name at all.
+            StyleResourceValue defaultTheme = mResources.getDefaultTheme();
+            // We can't simply check for parent using resources.themeIsParentOf() since the
+            // inheritance structure isn't really what one would expect. The first common parent
+            // between Theme.AppCompat.Light and Theme.AppCompat is Theme.Material (for v21).
+            boolean isThemeAppCompat = false;
+            for (int i = 0; i < 50; i++) {
+                if (defaultTheme == null) {
+                    break;
+                }
+                // for loop ensures that we don't run into cyclic theme inheritance.
+                if (defaultTheme.getName().startsWith(PREFIX_THEME_APPCOMPAT)) {
+                    isThemeAppCompat = true;
+                    break;
+                }
+                defaultTheme = mResources.getParent(defaultTheme);
+            }
+            mIsThemeAppCompat = isThemeAppCompat;
+            return isThemeAppCompat;
+        }
+
+        /**
+         * Return if both status bar and nav bar are solid (content doesn't overlap with these
+         * bars).
+         */
+        private boolean solidBars() {
+            return hasNavBar() && !mTranslucentNav && !mTranslucentStatus && mStatusBarSize > 0;
+        }
+
+        private boolean hasNavBar() {
+            return Config.showOnScreenNavBar(mParams.getSimulatedPlatformVersion()) &&
+                    hasSoftwareButtons() && mNavBarSize > 0;
+        }
+    }
+}
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 23df3f1..ac7c409 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
@@ -29,10 +29,8 @@
 import com.android.ide.common.rendering.api.Result.Status;
 import com.android.ide.common.rendering.api.SessionParams;
 import com.android.ide.common.rendering.api.SessionParams.RenderingMode;
-import com.android.ide.common.rendering.api.StyleResourceValue;
 import com.android.ide.common.rendering.api.ViewInfo;
 import com.android.ide.common.rendering.api.ViewType;
-import com.android.internal.util.XmlUtils;
 import com.android.internal.view.menu.ActionMenuItemView;
 import com.android.internal.view.menu.BridgeMenuItemImpl;
 import com.android.internal.view.menu.IconMenuItemView;
@@ -45,22 +43,11 @@
 import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
 import com.android.layoutlib.bridge.android.RenderParamsFlags;
 import com.android.layoutlib.bridge.android.support.DesignLibUtil;
-import com.android.layoutlib.bridge.bars.AppCompatActionBar;
-import com.android.layoutlib.bridge.bars.BridgeActionBar;
-import com.android.layoutlib.bridge.bars.Config;
-import com.android.layoutlib.bridge.bars.FrameworkActionBar;
-import com.android.layoutlib.bridge.bars.NavigationBar;
-import com.android.layoutlib.bridge.bars.StatusBar;
-import com.android.layoutlib.bridge.bars.TitleBar;
 import com.android.layoutlib.bridge.impl.binding.FakeAdapter;
 import com.android.layoutlib.bridge.impl.binding.FakeExpandableAdapter;
-import com.android.resources.Density;
 import com.android.resources.ResourceType;
-import com.android.resources.ScreenOrientation;
 import com.android.util.Pair;
 
-import org.xmlpull.v1.XmlPullParserException;
-
 import android.animation.AnimationThread;
 import android.animation.Animator;
 import android.animation.AnimatorInflater;
@@ -72,10 +59,7 @@
 import android.graphics.Bitmap;
 import android.graphics.Bitmap_Delegate;
 import android.graphics.Canvas;
-import android.graphics.drawable.Drawable;
 import android.preference.Preference_Delegate;
-import android.util.DisplayMetrics;
-import android.util.TypedValue;
 import android.view.AttachInfo_Accessor;
 import android.view.BridgeInflater;
 import android.view.IWindowManager;
@@ -126,33 +110,22 @@
  */
 public class RenderSessionImpl extends RenderAction<SessionParams> {
 
-    private static final int DEFAULT_TITLE_BAR_HEIGHT = 25;
-    private static final int DEFAULT_STATUS_BAR_HEIGHT = 25;
-
     // scene state
     private RenderSession mScene;
     private BridgeXmlBlockParser mBlockParser;
     private BridgeInflater mInflater;
-    private ResourceValue mWindowBackground;
     private ViewGroup mViewRoot;
     private FrameLayout mContentRoot;
     private Canvas mCanvas;
     private int mMeasuredScreenWidth = -1;
     private int mMeasuredScreenHeight = -1;
     private boolean mIsAlphaChannelImage;
-    private boolean mWindowIsFloating;
-    private Boolean mIsThemeAppCompat;
-
-    private int mStatusBarSize;
-    private int mNavigationBarSize;
-    private int mNavigationBarOrientation = LinearLayout.HORIZONTAL;
-    private int mTitleBarSize;
-    private int mActionBarSize;
 
     // information being returned through the API
     private BufferedImage mImage;
     private List<ViewInfo> mViewInfoList;
     private List<ViewInfo> mSystemViewInfoList;
+    private Layout.Builder mLayoutBuilder;
 
     private static final class PostInflateException extends Exception {
         private static final long serialVersionUID = 1L;
@@ -196,34 +169,24 @@
         SessionParams params = getParams();
         BridgeContext context = getContext();
 
-
-        RenderResources resources = getParams().getResources();
-        DisplayMetrics metrics = getContext().getMetrics();
-
         // use default of true in case it's not found to use alpha by default
-        mIsAlphaChannelImage  = getBooleanThemeValue(resources, "windowIsFloating", true, true);
-        // FIXME: Find out why both variables are taking the same value.
-        mWindowIsFloating = getBooleanThemeValue(resources, "windowIsFloating", true, true);
+        mIsAlphaChannelImage = ResourceHelper.getBooleanThemeValue(params.getResources(),
+                "windowIsFloating", true, true);
 
-        findBackground(resources);
-        findStatusBar(resources, metrics);
-        findActionBar(resources, metrics);
-        findNavigationBar(resources, metrics);
+        mLayoutBuilder = new Layout.Builder(params, context);
 
         // FIXME: find those out, and possibly add them to the render params
         boolean hasNavigationBar = true;
         //noinspection ConstantConditions
         IWindowManager iwm = new IWindowManagerImpl(getContext().getConfiguration(),
-                metrics, Surface.ROTATION_0,
-                hasNavigationBar);
+                context.getMetrics(), Surface.ROTATION_0, hasNavigationBar);
         WindowManagerGlobal_Delegate.setWindowManagerService(iwm);
 
         // build the inflater and parser.
         mInflater = new BridgeInflater(context, params.getLayoutlibCallback());
         context.setBridgeInflater(mInflater);
 
-        mBlockParser = new BridgeXmlBlockParser(
-                params.getLayoutDescription(), context, false /* platformResourceFlag */);
+        mBlockParser = new BridgeXmlBlockParser(params.getLayoutDescription(), context, false);
 
         return SUCCESS.createResult();
     }
@@ -240,164 +203,11 @@
         checkLock();
 
         try {
-
+            mViewRoot = new Layout(mLayoutBuilder);
+            mLayoutBuilder = null;  // Done with the builder.
+            mContentRoot = ((Layout) mViewRoot).getContentRoot();
             SessionParams params = getParams();
-            HardwareConfig hardwareConfig = params.getHardwareConfig();
             BridgeContext context = getContext();
-            boolean isRtl = Bridge.isLocaleRtl(params.getLocale());
-            int layoutDirection = isRtl ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR;
-
-            // the view group that receives the window background.
-            ViewGroup backgroundView;
-
-            if (mWindowIsFloating || params.isForceNoDecor()) {
-                backgroundView = mViewRoot = mContentRoot = new FrameLayout(context);
-                mViewRoot.setLayoutDirection(layoutDirection);
-            } else {
-                int simulatedPlatformVersion = params.getSimulatedPlatformVersion();
-                if (hasSoftwareButtons() && mNavigationBarOrientation == LinearLayout.VERTICAL) {
-                    /*
-                     * This is a special case where the navigation bar is on the right.
-                       +-------------------------------------------------+---+
-                       | Status bar (always)                             |   |
-                       +-------------------------------------------------+   |
-                       | (Layout with background drawable)               |   |
-                       | +---------------------------------------------+ |   |
-                       | | Title/Action bar (optional)                 | |   |
-                       | +---------------------------------------------+ |   |
-                       | | Content, vertical extending                 | |   |
-                       | |                                             | |   |
-                       | +---------------------------------------------+ |   |
-                       +-------------------------------------------------+---+
-
-                       So we create a horizontal layout, with the nav bar on the right,
-                       and the left part is the normal layout below without the nav bar at
-                       the bottom
-                     */
-                    LinearLayout topLayout = new LinearLayout(context);
-                    topLayout.setLayoutDirection(layoutDirection);
-                    mViewRoot = topLayout;
-                    topLayout.setOrientation(LinearLayout.HORIZONTAL);
-
-                    if (Config.showOnScreenNavBar(simulatedPlatformVersion)) {
-                        try {
-                            NavigationBar navigationBar = createNavigationBar(context,
-                                    hardwareConfig.getDensity(), isRtl, params.isRtlSupported(),
-                                    simulatedPlatformVersion);
-                            topLayout.addView(navigationBar);
-                        } catch (XmlPullParserException ignored) {
-                        }
-                    }
-                }
-
-                /*
-                 * we're creating the following layout
-                 *
-                   +-------------------------------------------------+
-                   | Status bar (always)                             |
-                   +-------------------------------------------------+
-                   | (Layout with background drawable)               |
-                   | +---------------------------------------------+ |
-                   | | Title/Action bar (optional)                 | |
-                   | +---------------------------------------------+ |
-                   | | Content, vertical extending                 | |
-                   | |                                             | |
-                   | +---------------------------------------------+ |
-                   +-------------------------------------------------+
-                   | Navigation bar for soft buttons, maybe see above|
-                   +-------------------------------------------------+
-
-                 */
-
-                LinearLayout topLayout = new LinearLayout(context);
-                topLayout.setOrientation(LinearLayout.VERTICAL);
-                topLayout.setLayoutDirection(layoutDirection);
-                // if we don't already have a view root this is it
-                if (mViewRoot == null) {
-                    mViewRoot = topLayout;
-                } else {
-                    int topLayoutWidth =
-                            params.getHardwareConfig().getScreenWidth() - mNavigationBarSize;
-                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
-                            topLayoutWidth, LayoutParams.MATCH_PARENT);
-                    topLayout.setLayoutParams(layoutParams);
-
-                    // this is the case of soft buttons + vertical bar.
-                    // this top layout is the first layout in the horizontal layout. see above)
-                    if (isRtl && params.isRtlSupported()) {
-                        // If RTL is enabled, layoutlib will mirror the layouts. So, add the
-                        // topLayout to the right of Navigation Bar and layoutlib will draw it
-                        // to the left.
-                        mViewRoot.addView(topLayout);
-                    } else {
-                        // Add the top layout to the left of the Navigation Bar.
-                        mViewRoot.addView(topLayout, 0);
-                    }
-                }
-
-                if (mStatusBarSize > 0) {
-                    // system bar
-                    try {
-                        StatusBar statusBar = createStatusBar(context, hardwareConfig.getDensity(),
-                                layoutDirection, params.isRtlSupported(),
-                                simulatedPlatformVersion);
-                        topLayout.addView(statusBar);
-                    } catch (XmlPullParserException ignored) {
-
-                    }
-                }
-
-                LinearLayout backgroundLayout = new LinearLayout(context);
-                backgroundView = backgroundLayout;
-                backgroundLayout.setOrientation(LinearLayout.VERTICAL);
-                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
-                        LayoutParams.MATCH_PARENT, 0);
-                layoutParams.weight = 1;
-                backgroundLayout.setLayoutParams(layoutParams);
-                topLayout.addView(backgroundLayout);
-
-
-                // if the theme says no title/action bar, then the size will be 0
-                if (mActionBarSize > 0) {
-                    BridgeActionBar actionBar = createActionBar(context, params, backgroundLayout);
-                    actionBar.createMenuPopup();
-                    mContentRoot = actionBar.getContentRoot();
-                } else if (mTitleBarSize > 0) {
-                    try {
-                        TitleBar titleBar = createTitleBar(context,
-                                params.getAppLabel(),
-                                simulatedPlatformVersion);
-                        backgroundLayout.addView(titleBar);
-                    } catch (XmlPullParserException ignored) {
-
-                    }
-                }
-
-                // content frame
-                if (mContentRoot == null) {
-                    mContentRoot = new FrameLayout(context);
-                    layoutParams = new LinearLayout.LayoutParams(
-                            LayoutParams.MATCH_PARENT, 0);
-                    layoutParams.weight = 1;
-                    mContentRoot.setLayoutParams(layoutParams);
-                    backgroundLayout.addView(mContentRoot);
-                }
-
-                if (Config.showOnScreenNavBar(simulatedPlatformVersion) &&
-                        mNavigationBarOrientation == LinearLayout.HORIZONTAL &&
-                        mNavigationBarSize > 0) {
-                    // system bar
-                    try {
-                        NavigationBar navigationBar = createNavigationBar(context,
-                                hardwareConfig.getDensity(), isRtl, params.isRtlSupported(),
-                                simulatedPlatformVersion);
-                        topLayout.addView(navigationBar);
-                    } catch (XmlPullParserException ignored) {
-
-                    }
-                }
-            }
-
 
             // Sets the project callback (custom view loader) to the fragment delegate so that
             // it can instantiate the custom Fragment.
@@ -408,7 +218,7 @@
             View view;
             if (isPreference) {
                 view = Preference_Delegate.inflatePreference(getContext(), mBlockParser,
-                  mContentRoot);
+                        mContentRoot);
             } else {
                 view = mInflater.inflate(mBlockParser, mContentRoot);
             }
@@ -427,12 +237,6 @@
 
             setActiveToolbar(view, context, params);
 
-            // get the background drawable
-            if (mWindowBackground != null) {
-                Drawable d = ResourceHelper.getDrawable(mWindowBackground, context);
-                backgroundView.setBackground(d);
-            }
-
             return SUCCESS.createResult();
         } catch (PostInflateException e) {
             return ERROR_INFLATION.createResult(e.getMessage(), e);
@@ -526,6 +330,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()) {
@@ -534,6 +343,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;
+                        }
                     }
                 }
             }
@@ -1063,198 +877,6 @@
         }
     }
 
-
-    private void findBackground(RenderResources resources) {
-        if (!getParams().isBgColorOverridden()) {
-            mWindowBackground = resources.findItemInTheme("windowBackground",
-                    true /*isFrameworkAttr*/);
-            if (mWindowBackground != null) {
-                mWindowBackground = resources.resolveResValue(mWindowBackground);
-            }
-        }
-    }
-
-    private boolean hasSoftwareButtons() {
-        return getParams().getHardwareConfig().hasSoftwareButtons();
-    }
-
-    private void findStatusBar(RenderResources resources, DisplayMetrics metrics) {
-        boolean windowFullscreen = getBooleanThemeValue(resources,
-                "windowFullscreen", false, true);
-
-        if (!windowFullscreen && !mWindowIsFloating) {
-            // default value
-            mStatusBarSize = DEFAULT_STATUS_BAR_HEIGHT;
-
-            // get the real value
-            ResourceValue value = resources.getFrameworkResource(ResourceType.DIMEN,
-                    "status_bar_height");
-
-            if (value != null) {
-                TypedValue typedValue = ResourceHelper.getValue("status_bar_height",
-                        value.getValue(), true /*requireUnit*/);
-                if (typedValue != null) {
-                    // compute the pixel value based on the display metrics
-                    mStatusBarSize = (int)typedValue.getDimension(metrics);
-                }
-            }
-        }
-    }
-
-    private void findActionBar(RenderResources resources, DisplayMetrics metrics) {
-        if (mWindowIsFloating) {
-            return;
-        }
-
-        boolean windowActionBar = getBooleanThemeValue(resources,
-                "windowActionBar", true, !isThemeAppCompat(resources));
-
-        // if there's a value and it's false (default is true)
-        if (windowActionBar) {
-
-            // default size of the window title bar
-            mActionBarSize = DEFAULT_TITLE_BAR_HEIGHT;
-
-            // get value from the theme.
-            ResourceValue value = resources.findItemInTheme("actionBarSize",
-                    true /*isFrameworkAttr*/);
-
-            // resolve it
-            value = resources.resolveResValue(value);
-
-            if (value != null) {
-                // get the numerical value, if available
-                TypedValue typedValue = ResourceHelper.getValue("actionBarSize", value.getValue(),
-                        true /*requireUnit*/);
-                if (typedValue != null) {
-                    // compute the pixel value based on the display metrics
-                    mActionBarSize = (int)typedValue.getDimension(metrics);
-                }
-            }
-        } else {
-            // action bar overrides title bar so only look for this one if action bar is hidden
-            boolean windowNoTitle = getBooleanThemeValue(resources, "windowNoTitle", false, true);
-
-            if (!windowNoTitle) {
-
-                // default size of the window title bar
-                mTitleBarSize = DEFAULT_TITLE_BAR_HEIGHT;
-
-                // get value from the theme.
-                ResourceValue value = resources.findItemInTheme("windowTitleSize",
-                        true /*isFrameworkAttr*/);
-
-                // resolve it
-                value = resources.resolveResValue(value);
-
-                if (value != null) {
-                    // get the numerical value, if available
-                    TypedValue typedValue = ResourceHelper.getValue("windowTitleSize",
-                            value.getValue(), true /*requireUnit*/);
-                    if (typedValue != null) {
-                        // compute the pixel value based on the display metrics
-                        mTitleBarSize = (int)typedValue.getDimension(metrics);
-                    }
-                }
-            }
-
-        }
-    }
-
-    private void findNavigationBar(RenderResources resources, DisplayMetrics metrics) {
-        if (hasSoftwareButtons() && !mWindowIsFloating) {
-
-            // default value
-            mNavigationBarSize = 48; // ??
-
-            HardwareConfig hardwareConfig = getParams().getHardwareConfig();
-
-            boolean barOnBottom = true;
-
-            if (hardwareConfig.getOrientation() == ScreenOrientation.LANDSCAPE) {
-                // compute the dp of the screen.
-                int shortSize = hardwareConfig.getScreenHeight();
-
-                // compute in dp
-                int shortSizeDp = shortSize * DisplayMetrics.DENSITY_DEFAULT /
-                        hardwareConfig.getDensity().getDpiValue();
-
-                // 0-599dp: "phone" UI with bar on the side
-                // 600+dp: "tablet" UI with bar on the bottom
-                barOnBottom = shortSizeDp >= 600;
-            }
-
-            if (barOnBottom) {
-                mNavigationBarOrientation = LinearLayout.HORIZONTAL;
-            } else {
-                mNavigationBarOrientation = LinearLayout.VERTICAL;
-            }
-
-            // get the real value
-            ResourceValue value = resources.getFrameworkResource(ResourceType.DIMEN,
-                    barOnBottom ? "navigation_bar_height" : "navigation_bar_width");
-
-            if (value != null) {
-                TypedValue typedValue = ResourceHelper.getValue("navigation_bar_height",
-                        value.getValue(), true /*requireUnit*/);
-                if (typedValue != null) {
-                    // compute the pixel value based on the display metrics
-                    mNavigationBarSize = (int)typedValue.getDimension(metrics);
-                }
-            }
-        }
-    }
-
-    private boolean isThemeAppCompat(RenderResources resources) {
-        // Ideally, we should check if the corresponding activity extends
-        // android.support.v7.app.ActionBarActivity, and not care about the theme name at all.
-        if (mIsThemeAppCompat == null) {
-            StyleResourceValue defaultTheme = resources.getDefaultTheme();
-          // We can't simply check for parent using resources.themeIsParentOf() since the
-          // inheritance structure isn't really what one would expect. The first common parent
-          // between Theme.AppCompat.Light and Theme.AppCompat is Theme.Material (for v21).
-            boolean isThemeAppCompat = false;
-            for (int i = 0; i < 50; i++) {
-                if (defaultTheme == null) {
-                    break;
-                }
-                // for loop ensures that we don't run into cyclic theme inheritance.
-                if (defaultTheme.getName().startsWith("Theme.AppCompat")) {
-                    isThemeAppCompat = true;
-                    break;
-                }
-                defaultTheme = resources.getParent(defaultTheme);
-            }
-            mIsThemeAppCompat = isThemeAppCompat;
-        }
-        return mIsThemeAppCompat;
-    }
-
-    /**
-     * Looks for an attribute in the current theme.
-     *
-     * @param resources the render resources
-     * @param name the name of the attribute
-     * @param defaultValue the default value.
-     * @param isFrameworkAttr if the attribute is in android namespace
-     * @return the value of the attribute or the default one if not found.
-     */
-    private boolean getBooleanThemeValue(RenderResources resources,
-            String name, boolean defaultValue, boolean isFrameworkAttr) {
-
-        ResourceValue value = resources.findItemInTheme(name, isFrameworkAttr);
-
-        // because it may reference something else, we resolve it.
-        value = resources.resolveResValue(value);
-
-        // if there's no value, return the default.
-        if (value == null || value.getValue() == null) {
-            return defaultValue;
-        }
-
-        return XmlUtils.convertValueToBoolean(value.getValue(), defaultValue);
-    }
-
     /**
      * Post process on a view hierarchy that was just inflated.
      * <p/>
@@ -1727,63 +1349,6 @@
         mMeasuredScreenWidth = mMeasuredScreenHeight = -1;
     }
 
-    /**
-     * Creates the status bar with wifi and battery icons.
-     */
-    private StatusBar createStatusBar(BridgeContext context, Density density, int direction,
-            boolean isRtlSupported, int platformVersion) throws XmlPullParserException {
-        StatusBar statusBar = new StatusBar(context, density,
-                direction, isRtlSupported, platformVersion);
-        statusBar.setLayoutParams(
-                new LinearLayout.LayoutParams(
-                        LayoutParams.MATCH_PARENT, mStatusBarSize));
-        return statusBar;
-    }
-
-    /**
-     * Creates the navigation bar with back, home and recent buttons.
-     *
-     * @param isRtl true if the current locale is right-to-left
-     * @param isRtlSupported true is the project manifest declares that the application
-     *        is RTL aware.
-     */
-    private NavigationBar createNavigationBar(BridgeContext context, Density density,
-            boolean isRtl, boolean isRtlSupported, int simulatedPlatformVersion)
-            throws XmlPullParserException {
-        NavigationBar navigationBar = new NavigationBar(context,
-                density, mNavigationBarOrientation, isRtl,
-                isRtlSupported, simulatedPlatformVersion);
-        if (mNavigationBarOrientation == LinearLayout.VERTICAL) {
-            navigationBar.setLayoutParams(new LinearLayout.LayoutParams(mNavigationBarSize,
-                    LayoutParams.MATCH_PARENT));
-        } else {
-            navigationBar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
-                    mNavigationBarSize));
-        }
-        return navigationBar;
-    }
-
-    private TitleBar createTitleBar(BridgeContext context, String title,
-            int simulatedPlatformVersion)
-            throws XmlPullParserException {
-        TitleBar titleBar = new TitleBar(context, title, simulatedPlatformVersion);
-        titleBar.setLayoutParams(
-                new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, mTitleBarSize));
-        return titleBar;
-    }
-
-    /**
-     * Creates the action bar. Also queries the project callback for missing information.
-     */
-    private BridgeActionBar createActionBar(BridgeContext context, SessionParams params,
-            ViewGroup parentView) {
-        if (mIsThemeAppCompat == Boolean.TRUE) {
-            return new AppCompatActionBar(context, params, parentView);
-        } else {
-            return new FrameworkActionBar(context, params, parentView);
-        }
-    }
-
     public BufferedImage getImage() {
         return mImage;
     }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java
index ca77193..c72eeb1 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java
@@ -21,6 +21,7 @@
 import com.android.ide.common.rendering.api.LayoutLog;
 import com.android.ide.common.rendering.api.RenderResources;
 import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.internal.util.XmlUtils;
 import com.android.layoutlib.bridge.Bridge;
 import com.android.layoutlib.bridge.android.BridgeContext;
 import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
@@ -327,6 +328,25 @@
         return null;
     }
 
+    /**
+     * Looks for an attribute in the current theme.
+     *
+     * @param resources the render resources
+     * @param name the name of the attribute
+     * @param defaultValue the default value.
+     * @param isFrameworkAttr if the attribute is in android namespace
+     * @return the value of the attribute or the default one if not found.
+     */
+    public static boolean getBooleanThemeValue(@NonNull RenderResources resources, String name,
+            boolean isFrameworkAttr, boolean defaultValue) {
+        ResourceValue value = resources.findItemInTheme(name, isFrameworkAttr);
+        value = resources.resolveResValue(value);
+        if (value == null) {
+            return defaultValue;
+        }
+        return XmlUtils.convertValueToBoolean(value.getValue(), defaultValue);
+    }
+
     // ------- TypedValue stuff
     // This is taken from //device/libs/utils/ResourceTypes.cpp
 
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/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index f390075..d915e5d 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -1302,7 +1302,7 @@
      * Return the results of the latest access point scan.
      * @return the list of access points found in the most recent scan. An app must hold
      * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION ACCESS_COARSE_LOCATION} or
-     * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION} permission
+     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission
      * in order to get valid results.
      */
     public List<ScanResult> getScanResults() {