Merge "SystemUI/Keyguard: try authenticate finger after authentication failure" into mnc-dev
diff --git a/api/current.txt b/api/current.txt
index bb1070d..c6b2c28 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -192,16 +192,6 @@
 
   public static final class R.attr {
     ctor public R.attr();
-    field public static final int __removeBeforeMRelease_leftIndents = 16844016; // 0x10104f0
-    field public static final int __removeBeforeMRelease_rightIndents = 16844017; // 0x10104f1
-    field public static final int __reserved0 = 16844020; // 0x10104f4
-    field public static final int __reserved1 = 16844019; // 0x10104f3
-    field public static final int __reserved2 = 16843999; // 0x10104df
-    field public static final int __reserved3 = 16844000; // 0x10104e0
-    field public static final int __reserved4 = 16844001; // 0x10104e1
-    field public static final int __reserved5 = 16844002; // 0x10104e2
-    field public static final int __reserved6 = 16844003; // 0x10104e3
-    field public static final int __reserved7 = 16844004; // 0x10104e4
     field public static final int absListViewStyle = 16842858; // 0x101006a
     field public static final int accessibilityEventTypes = 16843648; // 0x1010380
     field public static final int accessibilityFeedbackType = 16843650; // 0x1010382
@@ -264,7 +254,7 @@
     field public static final int allowParallelSyncs = 16843570; // 0x1010332
     field public static final int allowSingleTap = 16843353; // 0x1010259
     field public static final int allowTaskReparenting = 16843268; // 0x1010204
-    field public static final int allowUndo = 16844006; // 0x10104e6
+    field public static final int allowUndo = 16843999; // 0x10104df
     field public static final int alpha = 16843551; // 0x101031f
     field public static final int alphabeticShortcut = 16843235; // 0x10101e3
     field public static final int alwaysDrawnWithCache = 16842991; // 0x10100ef
@@ -295,7 +285,7 @@
     field public static final int autoStart = 16843445; // 0x10102b5
     field public static final deprecated int autoText = 16843114; // 0x101016a
     field public static final int autoUrlDetect = 16843404; // 0x101028c
-    field public static final int autoVerify = 16844010; // 0x10104ea
+    field public static final int autoVerify = 16844014; // 0x10104ee
     field public static final int background = 16842964; // 0x10100d4
     field public static final int backgroundDimAmount = 16842802; // 0x1010032
     field public static final int backgroundDimEnabled = 16843295; // 0x101021f
@@ -319,7 +309,7 @@
     field public static final int bottomRightRadius = 16843180; // 0x10101ac
     field public static final int breadCrumbShortTitle = 16843524; // 0x1010304
     field public static final int breadCrumbTitle = 16843523; // 0x1010303
-    field public static final int breakStrategy = 16844011; // 0x10104eb
+    field public static final int breakStrategy = 16843997; // 0x10104dd
     field public static final int bufferType = 16843086; // 0x101014e
     field public static final int button = 16843015; // 0x1010107
     field public static final int buttonBarButtonStyle = 16843567; // 0x101032f
@@ -381,7 +371,7 @@
     field public static final int colorActivatedHighlight = 16843664; // 0x1010390
     field public static final int colorBackground = 16842801; // 0x1010031
     field public static final int colorBackgroundCacheHint = 16843435; // 0x10102ab
-    field public static final int colorBackgroundFloating = 16844007; // 0x10104e7
+    field public static final int colorBackgroundFloating = 16844002; // 0x10104e2
     field public static final int colorButtonNormal = 16843819; // 0x101042b
     field public static final int colorControlActivated = 16843818; // 0x101042a
     field public static final int colorControlHighlight = 16843820; // 0x101042c
@@ -415,7 +405,7 @@
     field public static final int contentInsetLeft = 16843861; // 0x1010455
     field public static final int contentInsetRight = 16843862; // 0x1010456
     field public static final int contentInsetStart = 16843859; // 0x1010453
-    field public static final int contextClickable = 16844021; // 0x10104f5
+    field public static final int contextClickable = 16844007; // 0x10104e7
     field public static final int controlX1 = 16843772; // 0x10103fc
     field public static final int controlX2 = 16843774; // 0x10103fe
     field public static final int controlY1 = 16843773; // 0x10103fd
@@ -524,7 +514,7 @@
     field public static final int expandableListViewWhiteStyle = 16843446; // 0x10102b6
     field public static final int exported = 16842768; // 0x1010010
     field public static final int extraTension = 16843371; // 0x101026b
-    field public static final int extractNativeLibs = 16844008; // 0x10104e8
+    field public static final int extractNativeLibs = 16844010; // 0x10104ea
     field public static final int factor = 16843219; // 0x10101d3
     field public static final int fadeDuration = 16843384; // 0x1010278
     field public static final int fadeEnabled = 16843390; // 0x101027e
@@ -550,7 +540,7 @@
     field public static final int fillViewport = 16843130; // 0x101017a
     field public static final int filter = 16843035; // 0x101011b
     field public static final int filterTouchesWhenObscured = 16843460; // 0x10102c4
-    field public static final int fingerprintAuthDrawable = 16844025; // 0x10104f9
+    field public static final int fingerprintAuthDrawable = 16844008; // 0x10104e8
     field public static final int finishOnCloseSystemDialogs = 16843431; // 0x10102a7
     field public static final int finishOnTaskLaunch = 16842772; // 0x1010014
     field public static final int firstDayOfWeek = 16843581; // 0x101033d
@@ -594,7 +584,7 @@
     field public static final int fromXScale = 16843202; // 0x10101c2
     field public static final int fromYDelta = 16843208; // 0x10101c8
     field public static final int fromYScale = 16843204; // 0x10101c4
-    field public static final int fullBackupContent = 16844005; // 0x10104e5
+    field public static final int fullBackupContent = 16844011; // 0x10104eb
     field public static final int fullBackupOnly = 16843891; // 0x1010473
     field public static final int fullBright = 16842954; // 0x10100ca
     field public static final int fullDark = 16842950; // 0x10100c6
@@ -638,7 +628,7 @@
     field public static final int horizontalScrollViewStyle = 16843603; // 0x1010353
     field public static final int horizontalSpacing = 16843028; // 0x1010114
     field public static final int host = 16842792; // 0x1010028
-    field public static final int hyphenationFrequency = 16844024; // 0x10104f8
+    field public static final int hyphenationFrequency = 16843998; // 0x10104de
     field public static final int icon = 16842754; // 0x1010002
     field public static final int iconPreview = 16843337; // 0x1010249
     field public static final int iconifiedByDefault = 16843514; // 0x10102fa
@@ -802,9 +792,9 @@
     field public static final int listSeparatorTextViewStyle = 16843272; // 0x1010208
     field public static final int listViewStyle = 16842868; // 0x1010074
     field public static final int listViewWhiteStyle = 16842869; // 0x1010075
-    field public static final int lockTaskMode = 16844015; // 0x10104ef
+    field public static final int lockTaskMode = 16844013; // 0x10104ed
     field public static final int logo = 16843454; // 0x10102be
-    field public static final int logoDescription = 16844026; // 0x10104fa
+    field public static final int logoDescription = 16844009; // 0x10104e9
     field public static final int longClickable = 16842982; // 0x10100e6
     field public static final int loopViews = 16843527; // 0x1010307
     field public static final int manageSpaceActivity = 16842756; // 0x1010004
@@ -865,7 +855,7 @@
     field public static final int numColumns = 16843032; // 0x1010118
     field public static final int numStars = 16843076; // 0x1010144
     field public static final int numbersBackgroundColor = 16843938; // 0x10104a2
-    field public static final int numbersInnerTextColor = 16843998; // 0x10104de
+    field public static final int numbersInnerTextColor = 16844001; // 0x10104e1
     field public static final int numbersSelectorColor = 16843939; // 0x10104a3
     field public static final int numbersTextColor = 16843937; // 0x10104a1
     field public static final deprecated int numeric = 16843109; // 0x1010165
@@ -977,7 +967,6 @@
     field public static final int readPermission = 16842759; // 0x1010007
     field public static final int recognitionService = 16843932; // 0x101049c
     field public static final int relinquishTaskIdentity = 16843894; // 0x1010476
-    field public static final int removeBeforeMRelease = 16844014; // 0x10104ee
     field public static final int reparent = 16843964; // 0x10104bc
     field public static final int reparentWithOverlay = 16843965; // 0x10104bd
     field public static final int repeatCount = 16843199; // 0x10101bf
@@ -1027,7 +1016,7 @@
     field public static final int screenOrientation = 16842782; // 0x101001e
     field public static final int screenSize = 16843466; // 0x10102ca
     field public static final int scrollHorizontally = 16843099; // 0x101015b
-    field public static final int scrollIndicators = 16844023; // 0x10104f7
+    field public static final int scrollIndicators = 16844006; // 0x10104e6
     field public static final int scrollViewStyle = 16842880; // 0x1010080
     field public static final int scrollX = 16842962; // 0x10100d2
     field public static final int scrollY = 16842963; // 0x10100d3
@@ -1081,7 +1070,7 @@
     field public static final int showAsAction = 16843481; // 0x10102d9
     field public static final int showDefault = 16843258; // 0x10101fa
     field public static final int showDividers = 16843561; // 0x1010329
-    field public static final int showForAllUsers = 16844018; // 0x10104f2
+    field public static final int showForAllUsers = 16844015; // 0x10104ef
     field public static final deprecated int showOnLockScreen = 16843721; // 0x10103c9
     field public static final int showSilent = 16843259; // 0x10101fb
     field public static final int showText = 16843949; // 0x10104ad
@@ -1156,7 +1145,7 @@
     field public static final int submitBackground = 16843912; // 0x1010488
     field public static final int subtitle = 16843473; // 0x10102d1
     field public static final int subtitleTextAppearance = 16843823; // 0x101042f
-    field public static final int subtitleTextColor = 16844028; // 0x10104fc
+    field public static final int subtitleTextColor = 16844004; // 0x10104e4
     field public static final int subtitleTextStyle = 16843513; // 0x10102f9
     field public static final int subtypeExtraValue = 16843674; // 0x101039a
     field public static final int subtypeId = 16843713; // 0x10103c1
@@ -1168,8 +1157,8 @@
     field public static final int summaryColumn = 16843426; // 0x10102a2
     field public static final int summaryOff = 16843248; // 0x10101f0
     field public static final int summaryOn = 16843247; // 0x10101ef
-    field public static final int supportsAssist = 16844012; // 0x10104ec
-    field public static final int supportsLaunchVoiceAssistFromKeyguard = 16844022; // 0x10104f6
+    field public static final int supportsAssist = 16844016; // 0x10104f0
+    field public static final int supportsLaunchVoiceAssistFromKeyguard = 16844017; // 0x10104f1
     field public static final int supportsRtl = 16843695; // 0x10103af
     field public static final int supportsSwitchingToNextInputMethod = 16843755; // 0x10103eb
     field public static final int supportsUploading = 16843419; // 0x101029b
@@ -1270,7 +1259,7 @@
     field public static final int thicknessRatio = 16843164; // 0x101019c
     field public static final int thumb = 16843074; // 0x1010142
     field public static final int thumbOffset = 16843075; // 0x1010143
-    field public static final int thumbPosition = 16844013; // 0x10104ed
+    field public static final int thumbPosition = 16844005; // 0x10104e5
     field public static final int thumbTextPadding = 16843634; // 0x1010372
     field public static final int thumbTint = 16843889; // 0x1010471
     field public static final int thumbTintMode = 16843890; // 0x1010472
@@ -1287,7 +1276,7 @@
     field public static final int title = 16843233; // 0x10101e1
     field public static final int titleCondensed = 16843234; // 0x10101e2
     field public static final int titleTextAppearance = 16843822; // 0x101042e
-    field public static final int titleTextColor = 16844027; // 0x10104fb
+    field public static final int titleTextColor = 16844003; // 0x10104e3
     field public static final int titleTextStyle = 16843512; // 0x10102f8
     field public static final int toAlpha = 16843211; // 0x10101cb
     field public static final int toDegrees = 16843188; // 0x10101b4
@@ -1335,7 +1324,7 @@
     field public static final int useIntrinsicSizeAsMinimum = 16843536; // 0x1010310
     field public static final int useLevel = 16843167; // 0x101019f
     field public static final int userVisible = 16843409; // 0x1010291
-    field public static final int usesCleartextTraffic = 16844009; // 0x10104e9
+    field public static final int usesCleartextTraffic = 16844012; // 0x10104ec
     field public static final int value = 16842788; // 0x1010024
     field public static final int valueFrom = 16843486; // 0x10102de
     field public static final int valueTo = 16843487; // 0x10102df
@@ -1403,7 +1392,7 @@
     field public static final int windowHideAnimation = 16842935; // 0x10100b7
     field public static final int windowIsFloating = 16842839; // 0x1010057
     field public static final int windowIsTranslucent = 16842840; // 0x1010058
-    field public static final int windowLightStatusBar = 16843997; // 0x10104dd
+    field public static final int windowLightStatusBar = 16844000; // 0x10104e0
     field public static final int windowMinWidthMajor = 16843606; // 0x1010356
     field public static final int windowMinWidthMinor = 16843607; // 0x1010357
     field public static final int windowNoDisplay = 16843294; // 0x101021e
@@ -1668,12 +1657,12 @@
   public static final class R.id {
     ctor public R.id();
     field public static final int accessibilityActionContextClick = 16908348; // 0x102003c
-    field public static final int accessibilityActionScrollDown = 16908345; // 0x1020039
-    field public static final int accessibilityActionScrollLeft = 16908344; // 0x1020038
-    field public static final int accessibilityActionScrollRight = 16908346; // 0x102003a
-    field public static final int accessibilityActionScrollToPosition = 16908342; // 0x1020036
-    field public static final int accessibilityActionScrollUp = 16908343; // 0x1020037
-    field public static final int accessibilityActionShowOnScreen = 16908341; // 0x1020035
+    field public static final int accessibilityActionScrollDown = 16908346; // 0x102003a
+    field public static final int accessibilityActionScrollLeft = 16908345; // 0x1020039
+    field public static final int accessibilityActionScrollRight = 16908347; // 0x102003b
+    field public static final int accessibilityActionScrollToPosition = 16908343; // 0x1020037
+    field public static final int accessibilityActionScrollUp = 16908344; // 0x1020038
+    field public static final int accessibilityActionShowOnScreen = 16908342; // 0x1020036
     field public static final int addToDictionary = 16908330; // 0x102002a
     field public static final int background = 16908288; // 0x1020000
     field public static final int button1 = 16908313; // 0x1020019
@@ -1713,7 +1702,7 @@
     field public static final int selectAll = 16908319; // 0x102001f
     field public static final int selectTextMode = 16908333; // 0x102002d
     field public static final int selectedIcon = 16908302; // 0x102000e
-    field public static final int shareText = 16908347; // 0x102003b
+    field public static final int shareText = 16908341; // 0x1020035
     field public static final int startSelectingText = 16908328; // 0x1020028
     field public static final int statusBarBackground = 16908335; // 0x102002f
     field public static final int stopSelectingText = 16908329; // 0x1020029
@@ -1971,7 +1960,7 @@
     field public static final int TextAppearance_Material_Widget_ActionMode_Title = 16974355; // 0x1030213
     field public static final int TextAppearance_Material_Widget_ActionMode_Title_Inverse = 16974356; // 0x1030214
     field public static final int TextAppearance_Material_Widget_Button = 16974357; // 0x1030215
-    field public static final int TextAppearance_Material_Widget_Button_Inverse = 16974565; // 0x10302e5
+    field public static final int TextAppearance_Material_Widget_Button_Inverse = 16974548; // 0x10302d4
     field public static final int TextAppearance_Material_Widget_DropDownHint = 16974358; // 0x1030216
     field public static final int TextAppearance_Material_Widget_DropDownItem = 16974359; // 0x1030217
     field public static final int TextAppearance_Material_Widget_EditText = 16974360; // 0x1030218
@@ -2016,8 +2005,8 @@
     field public static final int ThemeOverlay_Material_ActionBar = 16974409; // 0x1030249
     field public static final int ThemeOverlay_Material_Dark = 16974411; // 0x103024b
     field public static final int ThemeOverlay_Material_Dark_ActionBar = 16974412; // 0x103024c
-    field public static final int ThemeOverlay_Material_Dialog = 16974564; // 0x10302e4
-    field public static final int ThemeOverlay_Material_Dialog_Alert = 16974566; // 0x10302e6
+    field public static final int ThemeOverlay_Material_Dialog = 16974550; // 0x10302d6
+    field public static final int ThemeOverlay_Material_Dialog_Alert = 16974551; // 0x10302d7
     field public static final int ThemeOverlay_Material_Light = 16974410; // 0x103024a
     field public static final int Theme_Black = 16973832; // 0x1030008
     field public static final int Theme_Black_NoTitleBar = 16973833; // 0x1030009
@@ -2108,7 +2097,7 @@
     field public static final int Theme_Material_Light_Dialog_NoActionBar = 16974396; // 0x103023c
     field public static final int Theme_Material_Light_Dialog_NoActionBar_MinWidth = 16974397; // 0x103023d
     field public static final int Theme_Material_Light_Dialog_Presentation = 16974398; // 0x103023e
-    field public static final int Theme_Material_Light_LightStatusBar = 16974563; // 0x10302e3
+    field public static final int Theme_Material_Light_LightStatusBar = 16974549; // 0x10302d5
     field public static final int Theme_Material_Light_NoActionBar = 16974401; // 0x1030241
     field public static final int Theme_Material_Light_NoActionBar_Fullscreen = 16974402; // 0x1030242
     field public static final int Theme_Material_Light_NoActionBar_Overscan = 16974403; // 0x1030243
@@ -2557,21 +2546,6 @@
     field public static final int Widget_Toolbar = 16974311; // 0x10301e7
     field public static final int Widget_Toolbar_Button_Navigation = 16974312; // 0x10301e8
     field public static final int Widget_WebView = 16973875; // 0x1030033
-    field public static final int __reserved10 = 16974550; // 0x10302d6
-    field public static final int __reserved11 = 16974551; // 0x10302d7
-    field public static final int __reserved12 = 16974552; // 0x10302d8
-    field public static final int __reserved13 = 16974553; // 0x10302d9
-    field public static final int __reserved14 = 16974554; // 0x10302da
-    field public static final int __reserved15 = 16974555; // 0x10302db
-    field public static final int __reserved16 = 16974556; // 0x10302dc
-    field public static final int __reserved17 = 16974557; // 0x10302dd
-    field public static final int __reserved18 = 16974558; // 0x10302de
-    field public static final int __reserved19 = 16974559; // 0x10302df
-    field public static final int __reserved20 = 16974560; // 0x10302e0
-    field public static final int __reserved21 = 16974561; // 0x10302e1
-    field public static final int __reserved22 = 16974562; // 0x10302e2
-    field public static final int __reserved8 = 16974548; // 0x10302d4
-    field public static final int __reserved9 = 16974549; // 0x10302d5
   }
 
   public static final class R.transition {
@@ -13466,6 +13440,7 @@
     field public static final int EDGE_MODE_FAST = 1; // 0x1
     field public static final int EDGE_MODE_HIGH_QUALITY = 2; // 0x2
     field public static final int EDGE_MODE_OFF = 0; // 0x0
+    field public static final int EDGE_MODE_ZERO_SHUTTER_LAG = 3; // 0x3
     field public static final int FLASH_MODE_OFF = 0; // 0x0
     field public static final int FLASH_MODE_SINGLE = 1; // 0x1
     field public static final int FLASH_MODE_TORCH = 2; // 0x2
@@ -13494,6 +13469,7 @@
     field public static final int NOISE_REDUCTION_MODE_HIGH_QUALITY = 2; // 0x2
     field public static final int NOISE_REDUCTION_MODE_MINIMAL = 3; // 0x3
     field public static final int NOISE_REDUCTION_MODE_OFF = 0; // 0x0
+    field public static final int NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG = 4; // 0x4
     field public static final int REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE = 0; // 0x0
     field public static final int REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE = 6; // 0x6
     field public static final int REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO = 9; // 0x9
@@ -15427,6 +15403,7 @@
     field public static final int ERROR_KEY_EXPIRED = 2; // 0x2
     field public static final int ERROR_NO_KEY = 1; // 0x1
     field public static final int ERROR_RESOURCE_BUSY = 3; // 0x3
+    field public static final int ERROR_SESSION_NOT_OPENED = 5; // 0x5
   }
 
   public static final class MediaCodec.CryptoInfo {
@@ -30690,6 +30667,11 @@
     method public abstract int getDbm();
     method public abstract int getLevel();
     method public abstract int hashCode();
+    field public static final int SIGNAL_STRENGTH_GOOD = 3; // 0x3
+    field public static final int SIGNAL_STRENGTH_GREAT = 4; // 0x4
+    field public static final int SIGNAL_STRENGTH_MODERATE = 2; // 0x2
+    field public static final int SIGNAL_STRENGTH_NONE_OR_UNKNOWN = 0; // 0x0
+    field public static final int SIGNAL_STRENGTH_POOR = 1; // 0x1
   }
 
   public final class CellSignalStrengthCdma extends android.telephony.CellSignalStrength implements android.os.Parcelable {
@@ -38725,6 +38707,7 @@
     method public abstract java.lang.String[] getResources();
     method public abstract void grant(java.lang.String[]);
     field public static final java.lang.String RESOURCE_AUDIO_CAPTURE = "android.webkit.resource.AUDIO_CAPTURE";
+    field public static final java.lang.String RESOURCE_MIDI_SYSEX = "android.webkit.resource.MIDI_SYSEX";
     field public static final java.lang.String RESOURCE_PROTECTED_MEDIA_ID = "android.webkit.resource.PROTECTED_MEDIA_ID";
     field public static final java.lang.String RESOURCE_VIDEO_CAPTURE = "android.webkit.resource.VIDEO_CAPTURE";
   }
diff --git a/api/system-current.txt b/api/system-current.txt
index 5861560..4e76475 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -282,16 +282,6 @@
 
   public static final class R.attr {
     ctor public R.attr();
-    field public static final int __removeBeforeMRelease_leftIndents = 16844016; // 0x10104f0
-    field public static final int __removeBeforeMRelease_rightIndents = 16844017; // 0x10104f1
-    field public static final int __reserved0 = 16844020; // 0x10104f4
-    field public static final int __reserved1 = 16844019; // 0x10104f3
-    field public static final int __reserved2 = 16843999; // 0x10104df
-    field public static final int __reserved3 = 16844000; // 0x10104e0
-    field public static final int __reserved4 = 16844001; // 0x10104e1
-    field public static final int __reserved5 = 16844002; // 0x10104e2
-    field public static final int __reserved6 = 16844003; // 0x10104e3
-    field public static final int __reserved7 = 16844004; // 0x10104e4
     field public static final int absListViewStyle = 16842858; // 0x101006a
     field public static final int accessibilityEventTypes = 16843648; // 0x1010380
     field public static final int accessibilityFeedbackType = 16843650; // 0x1010382
@@ -354,7 +344,7 @@
     field public static final int allowParallelSyncs = 16843570; // 0x1010332
     field public static final int allowSingleTap = 16843353; // 0x1010259
     field public static final int allowTaskReparenting = 16843268; // 0x1010204
-    field public static final int allowUndo = 16844006; // 0x10104e6
+    field public static final int allowUndo = 16843999; // 0x10104df
     field public static final int alpha = 16843551; // 0x101031f
     field public static final int alphabeticShortcut = 16843235; // 0x10101e3
     field public static final int alwaysDrawnWithCache = 16842991; // 0x10100ef
@@ -385,7 +375,7 @@
     field public static final int autoStart = 16843445; // 0x10102b5
     field public static final deprecated int autoText = 16843114; // 0x101016a
     field public static final int autoUrlDetect = 16843404; // 0x101028c
-    field public static final int autoVerify = 16844010; // 0x10104ea
+    field public static final int autoVerify = 16844014; // 0x10104ee
     field public static final int background = 16842964; // 0x10100d4
     field public static final int backgroundDimAmount = 16842802; // 0x1010032
     field public static final int backgroundDimEnabled = 16843295; // 0x101021f
@@ -409,7 +399,7 @@
     field public static final int bottomRightRadius = 16843180; // 0x10101ac
     field public static final int breadCrumbShortTitle = 16843524; // 0x1010304
     field public static final int breadCrumbTitle = 16843523; // 0x1010303
-    field public static final int breakStrategy = 16844011; // 0x10104eb
+    field public static final int breakStrategy = 16843997; // 0x10104dd
     field public static final int bufferType = 16843086; // 0x101014e
     field public static final int button = 16843015; // 0x1010107
     field public static final int buttonBarButtonStyle = 16843567; // 0x101032f
@@ -471,7 +461,7 @@
     field public static final int colorActivatedHighlight = 16843664; // 0x1010390
     field public static final int colorBackground = 16842801; // 0x1010031
     field public static final int colorBackgroundCacheHint = 16843435; // 0x10102ab
-    field public static final int colorBackgroundFloating = 16844007; // 0x10104e7
+    field public static final int colorBackgroundFloating = 16844002; // 0x10104e2
     field public static final int colorButtonNormal = 16843819; // 0x101042b
     field public static final int colorControlActivated = 16843818; // 0x101042a
     field public static final int colorControlHighlight = 16843820; // 0x101042c
@@ -505,7 +495,7 @@
     field public static final int contentInsetLeft = 16843861; // 0x1010455
     field public static final int contentInsetRight = 16843862; // 0x1010456
     field public static final int contentInsetStart = 16843859; // 0x1010453
-    field public static final int contextClickable = 16844021; // 0x10104f5
+    field public static final int contextClickable = 16844007; // 0x10104e7
     field public static final int controlX1 = 16843772; // 0x10103fc
     field public static final int controlX2 = 16843774; // 0x10103fe
     field public static final int controlY1 = 16843773; // 0x10103fd
@@ -614,7 +604,7 @@
     field public static final int expandableListViewWhiteStyle = 16843446; // 0x10102b6
     field public static final int exported = 16842768; // 0x1010010
     field public static final int extraTension = 16843371; // 0x101026b
-    field public static final int extractNativeLibs = 16844008; // 0x10104e8
+    field public static final int extractNativeLibs = 16844010; // 0x10104ea
     field public static final int factor = 16843219; // 0x10101d3
     field public static final int fadeDuration = 16843384; // 0x1010278
     field public static final int fadeEnabled = 16843390; // 0x101027e
@@ -640,7 +630,7 @@
     field public static final int fillViewport = 16843130; // 0x101017a
     field public static final int filter = 16843035; // 0x101011b
     field public static final int filterTouchesWhenObscured = 16843460; // 0x10102c4
-    field public static final int fingerprintAuthDrawable = 16844025; // 0x10104f9
+    field public static final int fingerprintAuthDrawable = 16844008; // 0x10104e8
     field public static final int finishOnCloseSystemDialogs = 16843431; // 0x10102a7
     field public static final int finishOnTaskLaunch = 16842772; // 0x1010014
     field public static final int firstDayOfWeek = 16843581; // 0x101033d
@@ -684,7 +674,7 @@
     field public static final int fromXScale = 16843202; // 0x10101c2
     field public static final int fromYDelta = 16843208; // 0x10101c8
     field public static final int fromYScale = 16843204; // 0x10101c4
-    field public static final int fullBackupContent = 16844005; // 0x10104e5
+    field public static final int fullBackupContent = 16844011; // 0x10104eb
     field public static final int fullBackupOnly = 16843891; // 0x1010473
     field public static final int fullBright = 16842954; // 0x10100ca
     field public static final int fullDark = 16842950; // 0x10100c6
@@ -728,7 +718,7 @@
     field public static final int horizontalScrollViewStyle = 16843603; // 0x1010353
     field public static final int horizontalSpacing = 16843028; // 0x1010114
     field public static final int host = 16842792; // 0x1010028
-    field public static final int hyphenationFrequency = 16844024; // 0x10104f8
+    field public static final int hyphenationFrequency = 16843998; // 0x10104de
     field public static final int icon = 16842754; // 0x1010002
     field public static final int iconPreview = 16843337; // 0x1010249
     field public static final int iconifiedByDefault = 16843514; // 0x10102fa
@@ -892,9 +882,9 @@
     field public static final int listSeparatorTextViewStyle = 16843272; // 0x1010208
     field public static final int listViewStyle = 16842868; // 0x1010074
     field public static final int listViewWhiteStyle = 16842869; // 0x1010075
-    field public static final int lockTaskMode = 16844015; // 0x10104ef
+    field public static final int lockTaskMode = 16844013; // 0x10104ed
     field public static final int logo = 16843454; // 0x10102be
-    field public static final int logoDescription = 16844026; // 0x10104fa
+    field public static final int logoDescription = 16844009; // 0x10104e9
     field public static final int longClickable = 16842982; // 0x10100e6
     field public static final int loopViews = 16843527; // 0x1010307
     field public static final int manageSpaceActivity = 16842756; // 0x1010004
@@ -955,7 +945,7 @@
     field public static final int numColumns = 16843032; // 0x1010118
     field public static final int numStars = 16843076; // 0x1010144
     field public static final int numbersBackgroundColor = 16843938; // 0x10104a2
-    field public static final int numbersInnerTextColor = 16843998; // 0x10104de
+    field public static final int numbersInnerTextColor = 16844001; // 0x10104e1
     field public static final int numbersSelectorColor = 16843939; // 0x10104a3
     field public static final int numbersTextColor = 16843937; // 0x10104a1
     field public static final deprecated int numeric = 16843109; // 0x1010165
@@ -1067,7 +1057,6 @@
     field public static final int readPermission = 16842759; // 0x1010007
     field public static final int recognitionService = 16843932; // 0x101049c
     field public static final int relinquishTaskIdentity = 16843894; // 0x1010476
-    field public static final int removeBeforeMRelease = 16844014; // 0x10104ee
     field public static final int reparent = 16843964; // 0x10104bc
     field public static final int reparentWithOverlay = 16843965; // 0x10104bd
     field public static final int repeatCount = 16843199; // 0x10101bf
@@ -1117,7 +1106,7 @@
     field public static final int screenOrientation = 16842782; // 0x101001e
     field public static final int screenSize = 16843466; // 0x10102ca
     field public static final int scrollHorizontally = 16843099; // 0x101015b
-    field public static final int scrollIndicators = 16844023; // 0x10104f7
+    field public static final int scrollIndicators = 16844006; // 0x10104e6
     field public static final int scrollViewStyle = 16842880; // 0x1010080
     field public static final int scrollX = 16842962; // 0x10100d2
     field public static final int scrollY = 16842963; // 0x10100d3
@@ -1175,7 +1164,7 @@
     field public static final int showAsAction = 16843481; // 0x10102d9
     field public static final int showDefault = 16843258; // 0x10101fa
     field public static final int showDividers = 16843561; // 0x1010329
-    field public static final int showForAllUsers = 16844018; // 0x10104f2
+    field public static final int showForAllUsers = 16844015; // 0x10104ef
     field public static final deprecated int showOnLockScreen = 16843721; // 0x10103c9
     field public static final int showSilent = 16843259; // 0x10101fb
     field public static final int showText = 16843949; // 0x10104ad
@@ -1250,7 +1239,7 @@
     field public static final int submitBackground = 16843912; // 0x1010488
     field public static final int subtitle = 16843473; // 0x10102d1
     field public static final int subtitleTextAppearance = 16843823; // 0x101042f
-    field public static final int subtitleTextColor = 16844028; // 0x10104fc
+    field public static final int subtitleTextColor = 16844004; // 0x10104e4
     field public static final int subtitleTextStyle = 16843513; // 0x10102f9
     field public static final int subtypeExtraValue = 16843674; // 0x101039a
     field public static final int subtypeId = 16843713; // 0x10103c1
@@ -1262,8 +1251,8 @@
     field public static final int summaryColumn = 16843426; // 0x10102a2
     field public static final int summaryOff = 16843248; // 0x10101f0
     field public static final int summaryOn = 16843247; // 0x10101ef
-    field public static final int supportsAssist = 16844012; // 0x10104ec
-    field public static final int supportsLaunchVoiceAssistFromKeyguard = 16844022; // 0x10104f6
+    field public static final int supportsAssist = 16844016; // 0x10104f0
+    field public static final int supportsLaunchVoiceAssistFromKeyguard = 16844017; // 0x10104f1
     field public static final int supportsRtl = 16843695; // 0x10103af
     field public static final int supportsSwitchingToNextInputMethod = 16843755; // 0x10103eb
     field public static final int supportsUploading = 16843419; // 0x101029b
@@ -1364,7 +1353,7 @@
     field public static final int thicknessRatio = 16843164; // 0x101019c
     field public static final int thumb = 16843074; // 0x1010142
     field public static final int thumbOffset = 16843075; // 0x1010143
-    field public static final int thumbPosition = 16844013; // 0x10104ed
+    field public static final int thumbPosition = 16844005; // 0x10104e5
     field public static final int thumbTextPadding = 16843634; // 0x1010372
     field public static final int thumbTint = 16843889; // 0x1010471
     field public static final int thumbTintMode = 16843890; // 0x1010472
@@ -1381,7 +1370,7 @@
     field public static final int title = 16843233; // 0x10101e1
     field public static final int titleCondensed = 16843234; // 0x10101e2
     field public static final int titleTextAppearance = 16843822; // 0x101042e
-    field public static final int titleTextColor = 16844027; // 0x10104fb
+    field public static final int titleTextColor = 16844003; // 0x10104e3
     field public static final int titleTextStyle = 16843512; // 0x10102f8
     field public static final int toAlpha = 16843211; // 0x10101cb
     field public static final int toDegrees = 16843188; // 0x10101b4
@@ -1429,7 +1418,7 @@
     field public static final int useIntrinsicSizeAsMinimum = 16843536; // 0x1010310
     field public static final int useLevel = 16843167; // 0x101019f
     field public static final int userVisible = 16843409; // 0x1010291
-    field public static final int usesCleartextTraffic = 16844009; // 0x10104e9
+    field public static final int usesCleartextTraffic = 16844012; // 0x10104ec
     field public static final int value = 16842788; // 0x1010024
     field public static final int valueFrom = 16843486; // 0x10102de
     field public static final int valueTo = 16843487; // 0x10102df
@@ -1497,7 +1486,7 @@
     field public static final int windowHideAnimation = 16842935; // 0x10100b7
     field public static final int windowIsFloating = 16842839; // 0x1010057
     field public static final int windowIsTranslucent = 16842840; // 0x1010058
-    field public static final int windowLightStatusBar = 16843997; // 0x10104dd
+    field public static final int windowLightStatusBar = 16844000; // 0x10104e0
     field public static final int windowMinWidthMajor = 16843606; // 0x1010356
     field public static final int windowMinWidthMinor = 16843607; // 0x1010357
     field public static final int windowNoDisplay = 16843294; // 0x101021e
@@ -1762,12 +1751,12 @@
   public static final class R.id {
     ctor public R.id();
     field public static final int accessibilityActionContextClick = 16908348; // 0x102003c
-    field public static final int accessibilityActionScrollDown = 16908345; // 0x1020039
-    field public static final int accessibilityActionScrollLeft = 16908344; // 0x1020038
-    field public static final int accessibilityActionScrollRight = 16908346; // 0x102003a
-    field public static final int accessibilityActionScrollToPosition = 16908342; // 0x1020036
-    field public static final int accessibilityActionScrollUp = 16908343; // 0x1020037
-    field public static final int accessibilityActionShowOnScreen = 16908341; // 0x1020035
+    field public static final int accessibilityActionScrollDown = 16908346; // 0x102003a
+    field public static final int accessibilityActionScrollLeft = 16908345; // 0x1020039
+    field public static final int accessibilityActionScrollRight = 16908347; // 0x102003b
+    field public static final int accessibilityActionScrollToPosition = 16908343; // 0x1020037
+    field public static final int accessibilityActionScrollUp = 16908344; // 0x1020038
+    field public static final int accessibilityActionShowOnScreen = 16908342; // 0x1020036
     field public static final int addToDictionary = 16908330; // 0x102002a
     field public static final int background = 16908288; // 0x1020000
     field public static final int button1 = 16908313; // 0x1020019
@@ -1807,7 +1796,7 @@
     field public static final int selectAll = 16908319; // 0x102001f
     field public static final int selectTextMode = 16908333; // 0x102002d
     field public static final int selectedIcon = 16908302; // 0x102000e
-    field public static final int shareText = 16908347; // 0x102003b
+    field public static final int shareText = 16908341; // 0x1020035
     field public static final int startSelectingText = 16908328; // 0x1020028
     field public static final int statusBarBackground = 16908335; // 0x102002f
     field public static final int stopSelectingText = 16908329; // 0x1020029
@@ -2067,7 +2056,7 @@
     field public static final int TextAppearance_Material_Widget_ActionMode_Title = 16974355; // 0x1030213
     field public static final int TextAppearance_Material_Widget_ActionMode_Title_Inverse = 16974356; // 0x1030214
     field public static final int TextAppearance_Material_Widget_Button = 16974357; // 0x1030215
-    field public static final int TextAppearance_Material_Widget_Button_Inverse = 16974565; // 0x10302e5
+    field public static final int TextAppearance_Material_Widget_Button_Inverse = 16974548; // 0x10302d4
     field public static final int TextAppearance_Material_Widget_DropDownHint = 16974358; // 0x1030216
     field public static final int TextAppearance_Material_Widget_DropDownItem = 16974359; // 0x1030217
     field public static final int TextAppearance_Material_Widget_EditText = 16974360; // 0x1030218
@@ -2112,8 +2101,8 @@
     field public static final int ThemeOverlay_Material_ActionBar = 16974409; // 0x1030249
     field public static final int ThemeOverlay_Material_Dark = 16974411; // 0x103024b
     field public static final int ThemeOverlay_Material_Dark_ActionBar = 16974412; // 0x103024c
-    field public static final int ThemeOverlay_Material_Dialog = 16974564; // 0x10302e4
-    field public static final int ThemeOverlay_Material_Dialog_Alert = 16974566; // 0x10302e6
+    field public static final int ThemeOverlay_Material_Dialog = 16974550; // 0x10302d6
+    field public static final int ThemeOverlay_Material_Dialog_Alert = 16974551; // 0x10302d7
     field public static final int ThemeOverlay_Material_Light = 16974410; // 0x103024a
     field public static final int Theme_Black = 16973832; // 0x1030008
     field public static final int Theme_Black_NoTitleBar = 16973833; // 0x1030009
@@ -2205,7 +2194,7 @@
     field public static final int Theme_Material_Light_Dialog_NoActionBar = 16974396; // 0x103023c
     field public static final int Theme_Material_Light_Dialog_NoActionBar_MinWidth = 16974397; // 0x103023d
     field public static final int Theme_Material_Light_Dialog_Presentation = 16974398; // 0x103023e
-    field public static final int Theme_Material_Light_LightStatusBar = 16974563; // 0x10302e3
+    field public static final int Theme_Material_Light_LightStatusBar = 16974549; // 0x10302d5
     field public static final int Theme_Material_Light_NoActionBar = 16974401; // 0x1030241
     field public static final int Theme_Material_Light_NoActionBar_Fullscreen = 16974402; // 0x1030242
     field public static final int Theme_Material_Light_NoActionBar_Overscan = 16974403; // 0x1030243
@@ -2654,21 +2643,6 @@
     field public static final int Widget_Toolbar = 16974311; // 0x10301e7
     field public static final int Widget_Toolbar_Button_Navigation = 16974312; // 0x10301e8
     field public static final int Widget_WebView = 16973875; // 0x1030033
-    field public static final int __reserved10 = 16974550; // 0x10302d6
-    field public static final int __reserved11 = 16974551; // 0x10302d7
-    field public static final int __reserved12 = 16974552; // 0x10302d8
-    field public static final int __reserved13 = 16974553; // 0x10302d9
-    field public static final int __reserved14 = 16974554; // 0x10302da
-    field public static final int __reserved15 = 16974555; // 0x10302db
-    field public static final int __reserved16 = 16974556; // 0x10302dc
-    field public static final int __reserved17 = 16974557; // 0x10302dd
-    field public static final int __reserved18 = 16974558; // 0x10302de
-    field public static final int __reserved19 = 16974559; // 0x10302df
-    field public static final int __reserved20 = 16974560; // 0x10302e0
-    field public static final int __reserved21 = 16974561; // 0x10302e1
-    field public static final int __reserved22 = 16974562; // 0x10302e2
-    field public static final int __reserved8 = 16974548; // 0x10302d4
-    field public static final int __reserved9 = 16974549; // 0x10302d5
   }
 
   public static final class R.transition {
@@ -13806,6 +13780,7 @@
     field public static final int EDGE_MODE_FAST = 1; // 0x1
     field public static final int EDGE_MODE_HIGH_QUALITY = 2; // 0x2
     field public static final int EDGE_MODE_OFF = 0; // 0x0
+    field public static final int EDGE_MODE_ZERO_SHUTTER_LAG = 3; // 0x3
     field public static final int FLASH_MODE_OFF = 0; // 0x0
     field public static final int FLASH_MODE_SINGLE = 1; // 0x1
     field public static final int FLASH_MODE_TORCH = 2; // 0x2
@@ -13834,6 +13809,7 @@
     field public static final int NOISE_REDUCTION_MODE_HIGH_QUALITY = 2; // 0x2
     field public static final int NOISE_REDUCTION_MODE_MINIMAL = 3; // 0x3
     field public static final int NOISE_REDUCTION_MODE_OFF = 0; // 0x0
+    field public static final int NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG = 4; // 0x4
     field public static final int REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE = 0; // 0x0
     field public static final int REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE = 6; // 0x6
     field public static final int REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO = 9; // 0x9
@@ -16690,6 +16666,7 @@
     field public static final int ERROR_KEY_EXPIRED = 2; // 0x2
     field public static final int ERROR_NO_KEY = 1; // 0x1
     field public static final int ERROR_RESOURCE_BUSY = 3; // 0x3
+    field public static final int ERROR_SESSION_NOT_OPENED = 5; // 0x5
   }
 
   public static final class MediaCodec.CryptoInfo {
@@ -32922,6 +32899,11 @@
     method public abstract int getDbm();
     method public abstract int getLevel();
     method public abstract int hashCode();
+    field public static final int SIGNAL_STRENGTH_GOOD = 3; // 0x3
+    field public static final int SIGNAL_STRENGTH_GREAT = 4; // 0x4
+    field public static final int SIGNAL_STRENGTH_MODERATE = 2; // 0x2
+    field public static final int SIGNAL_STRENGTH_NONE_OR_UNKNOWN = 0; // 0x0
+    field public static final int SIGNAL_STRENGTH_POOR = 1; // 0x1
   }
 
   public final class CellSignalStrengthCdma extends android.telephony.CellSignalStrength implements android.os.Parcelable {
@@ -41072,6 +41054,7 @@
     method public abstract java.lang.String[] getResources();
     method public abstract void grant(java.lang.String[]);
     field public static final java.lang.String RESOURCE_AUDIO_CAPTURE = "android.webkit.resource.AUDIO_CAPTURE";
+    field public static final java.lang.String RESOURCE_MIDI_SYSEX = "android.webkit.resource.MIDI_SYSEX";
     field public static final java.lang.String RESOURCE_PROTECTED_MEDIA_ID = "android.webkit.resource.PROTECTED_MEDIA_ID";
     field public static final java.lang.String RESOURCE_VIDEO_CAPTURE = "android.webkit.resource.VIDEO_CAPTURE";
   }
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index d28ff51..f2c907a 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -3975,6 +3975,8 @@
      *   This setting is only available from {@link android.os.Build.VERSION_CODES#MNC} onwards
      *   and can only be set if {@link #setMaximumTimeToLock} is not used to set a timeout.</li>
      * <li>{@link Settings.Global#WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN}</li>
+     *   This setting is only available from {@link android.os.Build.VERSION_CODES#MNC} onwards.
+     *   </li>
      * </ul>
      * <p>Changing the following settings has no effect as of
      * {@link android.os.Build.VERSION_CODES#MNC}:
diff --git a/core/java/android/hardware/SystemSensorManager.java b/core/java/android/hardware/SystemSensorManager.java
index 50e1a68..e7deae8 100644
--- a/core/java/android/hardware/SystemSensorManager.java
+++ b/core/java/android/hardware/SystemSensorManager.java
@@ -42,12 +42,12 @@
 public class SystemSensorManager extends SensorManager {
     private static native void nativeClassInit();
     private static native long nativeCreate(String opPackageName);
-    private static native int nativeGetNextSensor(long nativeInstance, Sensor sensor, int next);
+    private static native boolean nativeGetSensorAtIndex(long nativeInstance,
+            Sensor sensor, int index);
     private static native boolean nativeIsDataInjectionEnabled(long nativeInstance);
 
     private static boolean sSensorModuleInitialized = false;
     private static InjectEventQueue mInjectEventQueue = null;
-    private static boolean mDataInjectionMode = false;
 
     private final Object mLock = new Object();
 
@@ -81,15 +81,12 @@
         }
 
         // initialize the sensor list
-        int i = 0;
-        do {
+        for (int index = 0;;++index) {
             Sensor sensor = new Sensor();
-            i = nativeGetNextSensor(mNativeInstance, sensor, i);
-            if (i >= 0) {
-                mFullSensorsList.add(sensor);
-                mHandleToSensor.append(sensor.getHandle(), sensor);
-            }
-        } while (i > 0);
+            if (!nativeGetSensorAtIndex(mNativeInstance, sensor, index)) break;
+            mFullSensorsList.add(sensor);
+            mHandleToSensor.append(sensor.getHandle(), sensor);
+        }
     }
 
 
@@ -235,7 +232,6 @@
                     Log.e(TAG, "Data Injection mode not enabled");
                     return false;
                 }
-                mDataInjectionMode = true;
                 // Initialize a client for data_injection.
                 if (mInjectEventQueue == null) {
                     mInjectEventQueue = new InjectEventQueue(mMainLooper, this);
@@ -254,7 +250,7 @@
     protected boolean injectSensorDataImpl(Sensor sensor, float[] values, int accuracy,
             long timestamp) {
         synchronized (mLock) {
-            if (!mDataInjectionMode) {
+            if (mInjectEventQueue == null) {
                 Log.e(TAG, "Data injection mode not activated before calling injectSensorData");
                 return false;
             }
@@ -264,7 +260,6 @@
             if (ret != 0) {
                 mInjectEventQueue.dispose();
                 mInjectEventQueue = null;
-                mDataInjectionMode = false;
             }
             return ret == 0;
         }
diff --git a/core/java/android/hardware/camera2/CameraCaptureSession.java b/core/java/android/hardware/camera2/CameraCaptureSession.java
index c547b06..62ebfb3 100644
--- a/core/java/android/hardware/camera2/CameraCaptureSession.java
+++ b/core/java/android/hardware/camera2/CameraCaptureSession.java
@@ -497,8 +497,9 @@
      *
      * <p>Each reprocessable capture session has an input {@link Surface} where the reprocess
      * capture requests get the input images from, rather than the camera device. The application
-     * can create a {@link android.media.ImageWriter} with this input {@link Surface} and use it to
-     * provide input images for reprocess capture requests.</p>
+     * can create a {@link android.media.ImageWriter ImageWriter} with this input {@link Surface}
+     * and use it to provide input images for reprocess capture requests. When the reprocessable
+     * capture session is closed, the input {@link Surface} is abandoned and becomes invalid.</p>
      *
      * @return The {@link Surface} where reprocessing capture requests get the input images from. If
      *         this is not a reprocess capture session, {@code null} will be returned.
diff --git a/core/java/android/hardware/camera2/CameraCharacteristics.java b/core/java/android/hardware/camera2/CameraCharacteristics.java
index 835daab..6c74a9f 100644
--- a/core/java/android/hardware/camera2/CameraCharacteristics.java
+++ b/core/java/android/hardware/camera2/CameraCharacteristics.java
@@ -116,6 +116,20 @@
         }
 
         /**
+         * Return this {@link Key} as a string representation.
+         *
+         * <p>{@code "CameraCharacteristics.Key(%s)"}, where {@code %s} represents
+         * the name of this key as returned by {@link #getName}.</p>
+         *
+         * @return string representation of {@link Key}
+         */
+        @NonNull
+        @Override
+        public String toString() {
+            return String.format("CameraCharacteristics.Key(%s)", mKey.getName());
+        }
+
+        /**
          * Visible for CameraMetadataNative implementation only; do not use.
          *
          * TODO: Make this private or remove it altogether.
diff --git a/core/java/android/hardware/camera2/CameraMetadata.java b/core/java/android/hardware/camera2/CameraMetadata.java
index e8dbc5b..f7c6274 100644
--- a/core/java/android/hardware/camera2/CameraMetadata.java
+++ b/core/java/android/hardware/camera2/CameraMetadata.java
@@ -488,9 +488,13 @@
      * <li>{@link CaptureRequest#EDGE_MODE android.edge.mode}</li>
      * </ul>
      * </li>
+     * <li>{@link CameraCharacteristics#NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES android.noiseReduction.availableNoiseReductionModes} and
+     *   {@link CameraCharacteristics#EDGE_AVAILABLE_EDGE_MODES android.edge.availableEdgeModes} will both list ZERO_SHUTTER_LAG as a supported mode.</li>
      * </ul>
      *
+     * @see CameraCharacteristics#EDGE_AVAILABLE_EDGE_MODES
      * @see CaptureRequest#EDGE_MODE
+     * @see CameraCharacteristics#NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES
      * @see CaptureRequest#NOISE_REDUCTION_MODE
      * @see CameraCharacteristics#REPROCESS_MAX_CAPTURE_STALL
      * @see CameraCharacteristics#REQUEST_MAX_NUM_INPUT_STREAMS
@@ -593,9 +597,13 @@
      * <li>{@link CaptureRequest#REPROCESS_EFFECTIVE_EXPOSURE_FACTOR android.reprocess.effectiveExposureFactor}</li>
      * </ul>
      * </li>
+     * <li>{@link CameraCharacteristics#NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES android.noiseReduction.availableNoiseReductionModes} and
+     *   {@link CameraCharacteristics#EDGE_AVAILABLE_EDGE_MODES android.edge.availableEdgeModes} will both list ZERO_SHUTTER_LAG as a supported mode.</li>
      * </ul>
      *
+     * @see CameraCharacteristics#EDGE_AVAILABLE_EDGE_MODES
      * @see CaptureRequest#EDGE_MODE
+     * @see CameraCharacteristics#NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES
      * @see CaptureRequest#NOISE_REDUCTION_MODE
      * @see CaptureRequest#REPROCESS_EFFECTIVE_EXPOSURE_FACTOR
      * @see CameraCharacteristics#REPROCESS_MAX_CAPTURE_STALL
@@ -1999,6 +2007,30 @@
      */
     public static final int EDGE_MODE_HIGH_QUALITY = 2;
 
+    /**
+     * <p>Edge enhancement is applied at different levels for different output streams,
+     * based on resolution. Streams at maximum recording resolution (see {@link android.hardware.camera2.CameraDevice#createCaptureSession }) or below have
+     * edge enhancement applied, while higher-resolution streams have no edge enhancement
+     * applied. The level of edge enhancement for low-resolution streams is tuned so that
+     * frame rate is not impacted, and the quality is equal to or better than FAST (since it
+     * is only applied to lower-resolution outputs, quality may improve from FAST).</p>
+     * <p>This mode is intended to be used by applications operating in a zero-shutter-lag mode
+     * with YUV or PRIVATE reprocessing, where the application continuously captures
+     * high-resolution intermediate buffers into a circular buffer, from which a final image is
+     * produced via reprocessing when a user takes a picture.  For such a use case, the
+     * high-resolution buffers must not have edge enhancement applied to maximize efficiency of
+     * preview and to avoid double-applying enhancement when reprocessed, while low-resolution
+     * buffers (used for recording or preview, generally) need edge enhancement applied for
+     * reasonable preview quality.</p>
+     * <p>This mode is guaranteed to be supported by devices that support either the
+     * YUV_REPROCESSING or PRIVATE_REPROCESSING capabilities
+     * ({@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities} lists either of those capabilities).</p>
+     *
+     * @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
+     * @see CaptureRequest#EDGE_MODE
+     */
+    public static final int EDGE_MODE_ZERO_SHUTTER_LAG = 3;
+
     //
     // Enumeration values for CaptureRequest#FLASH_MODE
     //
@@ -2104,6 +2136,31 @@
      */
     public static final int NOISE_REDUCTION_MODE_MINIMAL = 3;
 
+    /**
+     * <p>Noise reduction is applied at different levels for different output streams,
+     * based on resolution. Streams at maximum recording resolution (see {@link android.hardware.camera2.CameraDevice#createCaptureSession }) or below have noise
+     * reduction applied, while higher-resolution streams have MINIMAL (if supported) or no
+     * noise reduction applied (if MINIMAL is not supported.) The degree of noise reduction
+     * for low-resolution streams is tuned so that frame rate is not impacted, and the quality
+     * is equal to or better than FAST (since it is only applied to lower-resolution outputs,
+     * quality may improve from FAST).</p>
+     * <p>This mode is intended to be used by applications operating in a zero-shutter-lag mode
+     * with YUV or PRIVATE reprocessing, where the application continuously captures
+     * high-resolution intermediate buffers into a circular buffer, from which a final image is
+     * produced via reprocessing when a user takes a picture.  For such a use case, the
+     * high-resolution buffers must not have noise reduction applied to maximize efficiency of
+     * preview and to avoid over-applying noise filtering when reprocessing, while
+     * low-resolution buffers (used for recording or preview, generally) need noise reduction
+     * applied for reasonable preview quality.</p>
+     * <p>This mode is guaranteed to be supported by devices that support either the
+     * YUV_REPROCESSING or PRIVATE_REPROCESSING capabilities
+     * ({@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities} lists either of those capabilities).</p>
+     *
+     * @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
+     * @see CaptureRequest#NOISE_REDUCTION_MODE
+     */
+    public static final int NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG = 4;
+
     //
     // Enumeration values for CaptureRequest#SENSOR_TEST_PATTERN_MODE
     //
diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java
index 33cc962..6d8cc54 100644
--- a/core/java/android/hardware/camera2/CaptureRequest.java
+++ b/core/java/android/hardware/camera2/CaptureRequest.java
@@ -150,6 +150,20 @@
         }
 
         /**
+         * Return this {@link Key} as a string representation.
+         *
+         * <p>{@code "CaptureRequest.Key(%s)"}, where {@code %s} represents
+         * the name of this key as returned by {@link #getName}.</p>
+         *
+         * @return string representation of {@link Key}
+         */
+        @NonNull
+        @Override
+        public String toString() {
+            return String.format("CaptureRequest.Key(%s)", mKey.getName());
+        }
+
+        /**
          * Visible for CameraMetadataNative implementation only; do not use.
          *
          * TODO: Make this private or remove it altogether.
@@ -1569,7 +1583,14 @@
      * will be applied. HIGH_QUALITY mode indicates that the
      * camera device will use the highest-quality enhancement algorithms,
      * even if it slows down capture rate. FAST means the camera device will
-     * not slow down capture rate when applying edge enhancement.</p>
+     * not slow down capture rate when applying edge enhancement. Every output stream will
+     * have a similar amount of enhancement applied.</p>
+     * <p>ZERO_SHUTTER_LAG is meant to be used by applications that maintain a continuous circular
+     * buffer of high-resolution images during preview and reprocess image(s) from that buffer
+     * into a final capture when triggered by the user. In this mode, the camera device applies
+     * edge enhancement to low-resolution streams (below maximum recording resolution) to
+     * maximize preview quality, but does not apply edge enhancement to high-resolution streams,
+     * since those will be reprocessed later if necessary.</p>
      * <p>For YUV_REPROCESSING, these FAST/HIGH_QUALITY modes both mean that the camera
      * device will apply FAST/HIGH_QUALITY YUV-domain edge enhancement, respectively.
      * The camera device may adjust its internal noise reduction parameters for best
@@ -1579,6 +1600,7 @@
      *   <li>{@link #EDGE_MODE_OFF OFF}</li>
      *   <li>{@link #EDGE_MODE_FAST FAST}</li>
      *   <li>{@link #EDGE_MODE_HIGH_QUALITY HIGH_QUALITY}</li>
+     *   <li>{@link #EDGE_MODE_ZERO_SHUTTER_LAG ZERO_SHUTTER_LAG}</li>
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#EDGE_AVAILABLE_EDGE_MODES android.edge.availableEdgeModes}</p>
@@ -1593,6 +1615,7 @@
      * @see #EDGE_MODE_OFF
      * @see #EDGE_MODE_FAST
      * @see #EDGE_MODE_HIGH_QUALITY
+     * @see #EDGE_MODE_ZERO_SHUTTER_LAG
      */
     @PublicKey
     public static final Key<Integer> EDGE_MODE =
@@ -1979,7 +2002,14 @@
      * will be applied. HIGH_QUALITY mode indicates that the camera device
      * will use the highest-quality noise filtering algorithms,
      * even if it slows down capture rate. FAST means the camera device will not
-     * slow down capture rate when applying noise filtering.</p>
+     * slow down capture rate when applying noise filtering. Every output stream will
+     * have a similar amount of enhancement applied.</p>
+     * <p>ZERO_SHUTTER_LAG is meant to be used by applications that maintain a continuous circular
+     * buffer of high-resolution images during preview and reprocess image(s) from that buffer
+     * into a final capture when triggered by the user. In this mode, the camera device applies
+     * noise reduction to low-resolution streams (below maximum recording resolution) to maximize
+     * preview quality, but does not apply noise reduction to high-resolution streams, since
+     * those will be reprocessed later if necessary.</p>
      * <p>For YUV_REPROCESSING, these FAST/HIGH_QUALITY modes both mean that the camera device
      * will apply FAST/HIGH_QUALITY YUV domain noise reduction, respectively. The camera device
      * may adjust the noise reduction parameters for best image quality based on the
@@ -1990,6 +2020,7 @@
      *   <li>{@link #NOISE_REDUCTION_MODE_FAST FAST}</li>
      *   <li>{@link #NOISE_REDUCTION_MODE_HIGH_QUALITY HIGH_QUALITY}</li>
      *   <li>{@link #NOISE_REDUCTION_MODE_MINIMAL MINIMAL}</li>
+     *   <li>{@link #NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG ZERO_SHUTTER_LAG}</li>
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES android.noiseReduction.availableNoiseReductionModes}</p>
@@ -2005,6 +2036,7 @@
      * @see #NOISE_REDUCTION_MODE_FAST
      * @see #NOISE_REDUCTION_MODE_HIGH_QUALITY
      * @see #NOISE_REDUCTION_MODE_MINIMAL
+     * @see #NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG
      */
     @PublicKey
     public static final Key<Integer> NOISE_REDUCTION_MODE =
diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java
index 9dee045..f7cf1850 100644
--- a/core/java/android/hardware/camera2/CaptureResult.java
+++ b/core/java/android/hardware/camera2/CaptureResult.java
@@ -127,6 +127,20 @@
         }
 
         /**
+         * Return this {@link Key} as a string representation.
+         *
+         * <p>{@code "CaptureResult.Key(%s)"}, where {@code %s} represents
+         * the name of this key as returned by {@link #getName}.</p>
+         *
+         * @return string representation of {@link Key}
+         */
+        @NonNull
+        @Override
+        public String toString() {
+            return String.format("CaptureResult.Key(%s)", mKey.getName());
+        }
+
+        /**
          * Visible for CameraMetadataNative implementation only; do not use.
          *
          * TODO: Make this private or remove it altogether.
@@ -2081,7 +2095,14 @@
      * will be applied. HIGH_QUALITY mode indicates that the
      * camera device will use the highest-quality enhancement algorithms,
      * even if it slows down capture rate. FAST means the camera device will
-     * not slow down capture rate when applying edge enhancement.</p>
+     * not slow down capture rate when applying edge enhancement. Every output stream will
+     * have a similar amount of enhancement applied.</p>
+     * <p>ZERO_SHUTTER_LAG is meant to be used by applications that maintain a continuous circular
+     * buffer of high-resolution images during preview and reprocess image(s) from that buffer
+     * into a final capture when triggered by the user. In this mode, the camera device applies
+     * edge enhancement to low-resolution streams (below maximum recording resolution) to
+     * maximize preview quality, but does not apply edge enhancement to high-resolution streams,
+     * since those will be reprocessed later if necessary.</p>
      * <p>For YUV_REPROCESSING, these FAST/HIGH_QUALITY modes both mean that the camera
      * device will apply FAST/HIGH_QUALITY YUV-domain edge enhancement, respectively.
      * The camera device may adjust its internal noise reduction parameters for best
@@ -2091,6 +2112,7 @@
      *   <li>{@link #EDGE_MODE_OFF OFF}</li>
      *   <li>{@link #EDGE_MODE_FAST FAST}</li>
      *   <li>{@link #EDGE_MODE_HIGH_QUALITY HIGH_QUALITY}</li>
+     *   <li>{@link #EDGE_MODE_ZERO_SHUTTER_LAG ZERO_SHUTTER_LAG}</li>
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#EDGE_AVAILABLE_EDGE_MODES android.edge.availableEdgeModes}</p>
@@ -2105,6 +2127,7 @@
      * @see #EDGE_MODE_OFF
      * @see #EDGE_MODE_FAST
      * @see #EDGE_MODE_HIGH_QUALITY
+     * @see #EDGE_MODE_ZERO_SHUTTER_LAG
      */
     @PublicKey
     public static final Key<Integer> EDGE_MODE =
@@ -2763,7 +2786,14 @@
      * will be applied. HIGH_QUALITY mode indicates that the camera device
      * will use the highest-quality noise filtering algorithms,
      * even if it slows down capture rate. FAST means the camera device will not
-     * slow down capture rate when applying noise filtering.</p>
+     * slow down capture rate when applying noise filtering. Every output stream will
+     * have a similar amount of enhancement applied.</p>
+     * <p>ZERO_SHUTTER_LAG is meant to be used by applications that maintain a continuous circular
+     * buffer of high-resolution images during preview and reprocess image(s) from that buffer
+     * into a final capture when triggered by the user. In this mode, the camera device applies
+     * noise reduction to low-resolution streams (below maximum recording resolution) to maximize
+     * preview quality, but does not apply noise reduction to high-resolution streams, since
+     * those will be reprocessed later if necessary.</p>
      * <p>For YUV_REPROCESSING, these FAST/HIGH_QUALITY modes both mean that the camera device
      * will apply FAST/HIGH_QUALITY YUV domain noise reduction, respectively. The camera device
      * may adjust the noise reduction parameters for best image quality based on the
@@ -2774,6 +2804,7 @@
      *   <li>{@link #NOISE_REDUCTION_MODE_FAST FAST}</li>
      *   <li>{@link #NOISE_REDUCTION_MODE_HIGH_QUALITY HIGH_QUALITY}</li>
      *   <li>{@link #NOISE_REDUCTION_MODE_MINIMAL MINIMAL}</li>
+     *   <li>{@link #NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG ZERO_SHUTTER_LAG}</li>
      * </ul></p>
      * <p><b>Available values for this device:</b><br>
      * {@link CameraCharacteristics#NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES android.noiseReduction.availableNoiseReductionModes}</p>
@@ -2789,6 +2820,7 @@
      * @see #NOISE_REDUCTION_MODE_FAST
      * @see #NOISE_REDUCTION_MODE_HIGH_QUALITY
      * @see #NOISE_REDUCTION_MODE_MINIMAL
+     * @see #NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG
      */
     @PublicKey
     public static final Key<Integer> NOISE_REDUCTION_MODE =
diff --git a/core/java/android/view/IWindow.aidl b/core/java/android/view/IWindow.aidl
index 9cf3759..acad496 100644
--- a/core/java/android/view/IWindow.aidl
+++ b/core/java/android/view/IWindow.aidl
@@ -83,7 +83,8 @@
      * The window is beginning to animate. The application should stop drawing frames until the
      * window is not animating anymore, indicated by being called {@link #windowEndAnimating}.
      *
-     * @param remainingFrameCount how many frames the app might still draw before stopping drawing
+     * @param remainingFrameCount how many frames the app might still draw before stopping drawing;
+     *                            pass -1 to let it continue drawing
      */
     void onAnimationStarted(int remainingFrameCount);
 
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 63dd492..de61c31 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -15366,7 +15366,8 @@
                 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
         if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
             if (width > 0 && height > 0) {
-                Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
+                Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is"
+                        + " too large to fit into a software layer (or drawing cache), needs "
                         + projectedBitmapSize + " bytes, only "
                         + drawingCacheSize + " available");
             }
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 6d0d788..9b1db57 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -2367,8 +2367,7 @@
      * @hide
      */
     void outputDisplayList(View view) {
-        RenderNode renderNode = view.updateDisplayListIfDirty();
-        renderNode.output();
+        view.mRenderNode.output();
     }
 
     /**
@@ -5327,7 +5326,7 @@
     }
 
     public void handleDispatchWindowAnimationStarted(int remainingFrameCount) {
-        if (!mDrawDuringWindowsAnimating) {
+        if (!mDrawDuringWindowsAnimating && remainingFrameCount != -1) {
             mRemainingFrameCount = remainingFrameCount;
             mWindowsAnimating = true;
         }
diff --git a/core/java/android/webkit/PermissionRequest.java b/core/java/android/webkit/PermissionRequest.java
index 6ad639c..18ec334 100644
--- a/core/java/android/webkit/PermissionRequest.java
+++ b/core/java/android/webkit/PermissionRequest.java
@@ -26,6 +26,16 @@
  *
  * Either {@link #grant(String[]) grant()} or {@link #deny()} must be called in UI
  * thread to respond to the request.
+ *
+ * New protected resources whose names are not defined here may be requested in
+ * future versions of WebView, even when running on an older Android release. To
+ * avoid unintentionally granting requests for new permissions, you should pass the
+ * specific permissions you intend to grant to {@link #grant(String[]) grant()},
+ * and avoid writing code like this example:
+ * <pre>
+ * permissionRequest.grant(permissionRequest.getResources())  // This is wrong!!!
+ * </pre>
+ * See the WebView's release notes for information about new protected resources.
  */
 public abstract class PermissionRequest {
     /**
@@ -43,6 +53,15 @@
      */
     public final static String RESOURCE_PROTECTED_MEDIA_ID =
             "android.webkit.resource.PROTECTED_MEDIA_ID";
+    /**
+     * Resource will allow sysex messages to be sent to or received from MIDI devices. These
+     * messages are privileged operations, e.g. modifying sound libraries and sampling data, or
+     * even updating the MIDI device's firmware.
+     *
+     * Permission may be requested for this resource in API levels 21 and above, if the Android
+     * device has been updated to WebView 45 or above.
+     */
+    public final static String RESOURCE_MIDI_SYSEX = "android.webkit.resource.MIDI_SYSEX";
 
     /**
      * Call this method to get the origin of the web page which is trying to access
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index 8bf6992..b2b98db 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -6605,8 +6605,8 @@
         void addScrapView(View scrap, int position) {
             final AbsListView.LayoutParams lp = (AbsListView.LayoutParams) scrap.getLayoutParams();
             if (lp == null) {
-                // Can't recycle, skip the scrap heap.
-                getSkippedScrap().add(scrap);
+                // Can't recycle, but we don't know anything about the view.
+                // Ignore it completely.
                 return;
             }
 
@@ -6616,8 +6616,12 @@
             // should otherwise not be recycled.
             final int viewType = lp.viewType;
             if (!shouldRecycleViewType(viewType)) {
-                // Can't recycle, skip the scrap heap.
-                getSkippedScrap().add(scrap);
+                // Can't recycle. If it's not a header or footer, which have
+                // special handling and should be ignored, then skip the scrap
+                // heap and we'll fully detach the view later.
+                if (viewType != ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
+                    getSkippedScrap().add(scrap);
+                }
                 return;
             }
 
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index 1158d1e..7c4ff18 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -1121,7 +1121,6 @@
                 if (mTemporaryDetach) mPreserveDetachedSelection = false;
                 downgradeEasyCorrectionSpans();
             }
-
             // No need to create the controller
             if (mSelectionModifierCursorController != null) {
                 mSelectionModifierCursorController.resetTouchOffsets();
@@ -1793,7 +1792,7 @@
      *
      * @return true if there already was a selection or if the current word was selected.
      */
-    private boolean checkFieldAndSelectCurrentWord() {
+    boolean checkFieldAndSelectCurrentWord() {
         if (!mTextView.canSelectText() || !mTextView.requestFocus()) {
             Log.w(TextView.LOG_TAG,
                     "TextView does not support text selection. Selection cancelled.");
@@ -1840,7 +1839,7 @@
         return selectionStarted;
     }
 
-    private boolean extractedTextModeWillBeStarted() {
+    boolean extractedTextModeWillBeStarted() {
         if (!(mTextView.isInExtractedMode())) {
             final InputMethodManager imm = InputMethodManager.peekInstance();
             return  imm != null && imm.isFullscreenMode();
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 6b8abab..43edc44 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -5232,7 +5232,11 @@
         // - onFocusChanged cannot start it when focus is given to a view with selected text (after
         //   a screen rotation) since layout is not yet initialized at that point.
         if (mEditor != null && mEditor.mCreatedWithASelection) {
-            mEditor.startSelectionActionMode();
+            if (mEditor.extractedTextModeWillBeStarted()) {
+                mEditor.checkFieldAndSelectCurrentWord();
+            } else {
+                mEditor.startSelectionActionMode();
+            }
             mEditor.mCreatedWithASelection = false;
         }
 
diff --git a/core/java/com/android/internal/app/ChooserActivity.java b/core/java/com/android/internal/app/ChooserActivity.java
index 1b55557..c4f57c7 100644
--- a/core/java/com/android/internal/app/ChooserActivity.java
+++ b/core/java/com/android/internal/app/ChooserActivity.java
@@ -59,6 +59,8 @@
 import com.android.internal.logging.MetricsLogger;
 
 import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
 import java.util.List;
 
 public class ChooserActivity extends ResolverActivity {
@@ -97,7 +99,10 @@
                                 + " Have you considered returning results faster?");
                         break;
                     }
-                    mChooserListAdapter.addServiceResults(sri.originalTarget, sri.resultTargets);
+                    if (sri.resultTargets != null) {
+                        mChooserListAdapter.addServiceResults(sri.originalTarget,
+                                sri.resultTargets);
+                    }
                     unbindService(sri.connection);
                     mServiceConnections.remove(sri.connection);
                     if (mServiceConnections.isEmpty()) {
@@ -485,10 +490,13 @@
         private Drawable mDisplayIcon;
         private final Intent mFillInIntent;
         private final int mFillInFlags;
+        private final float mModifiedScore;
 
-        public ChooserTargetInfo(DisplayResolveInfo sourceInfo, ChooserTarget chooserTarget) {
+        public ChooserTargetInfo(DisplayResolveInfo sourceInfo, ChooserTarget chooserTarget,
+                float modifiedScore) {
             mSourceInfo = sourceInfo;
             mChooserTarget = chooserTarget;
+            mModifiedScore = modifiedScore;
             if (sourceInfo != null) {
                 final ResolveInfo ri = sourceInfo.getResolveInfo();
                 if (ri != null) {
@@ -520,6 +528,11 @@
             mDisplayIcon = other.mDisplayIcon;
             mFillInIntent = fillInIntent;
             mFillInFlags = flags;
+            mModifiedScore = other.mModifiedScore;
+        }
+
+        public float getModifiedScore() {
+            return mModifiedScore;
         }
 
         @Override
@@ -632,9 +645,16 @@
         public static final int TARGET_SERVICE = 1;
         public static final int TARGET_STANDARD = 2;
 
+        private static final int MAX_SERVICE_TARGETS = 8;
+
         private final List<ChooserTargetInfo> mServiceTargets = new ArrayList<>();
         private final List<TargetInfo> mCallerTargets = new ArrayList<>();
 
+        private float mLateFee = 1.f;
+
+        private final BaseChooserTargetComparator mBaseTargetComparator
+                = new BaseChooserTargetComparator();
+
         public ChooserListAdapter(Context context, List<Intent> payloadIntents,
                 Intent[] initialIntents, List<ResolveInfo> rList, int launchedFromUid,
                 boolean filterLastUsed) {
@@ -703,12 +723,12 @@
 
         @Override
         public int getCount() {
-            return super.getCount() + mServiceTargets.size() + mCallerTargets.size();
+            return super.getCount() + getServiceTargetCount() + getCallerTargetCount();
         }
 
         @Override
         public int getUnfilteredCount() {
-            return super.getUnfilteredCount() + mServiceTargets.size() + mCallerTargets.size();
+            return super.getUnfilteredCount() + getServiceTargetCount() + getCallerTargetCount();
         }
 
         public int getCallerTargetCount() {
@@ -716,7 +736,7 @@
         }
 
         public int getServiceTargetCount() {
-            return mServiceTargets.size();
+            return Math.min(mServiceTargets.size(), MAX_SERVICE_TARGETS);
         }
 
         public int getStandardTargetCount() {
@@ -726,13 +746,13 @@
         public int getPositionTargetType(int position) {
             int offset = 0;
 
-            final int callerTargetCount = mCallerTargets.size();
+            final int callerTargetCount = getCallerTargetCount();
             if (position < callerTargetCount) {
                 return TARGET_CALLER;
             }
             offset += callerTargetCount;
 
-            final int serviceTargetCount = mServiceTargets.size();
+            final int serviceTargetCount = getServiceTargetCount();
             if (position - offset < serviceTargetCount) {
                 return TARGET_SERVICE;
             }
@@ -755,13 +775,13 @@
         public TargetInfo targetInfoForPosition(int position, boolean filtered) {
             int offset = 0;
 
-            final int callerTargetCount = mCallerTargets.size();
+            final int callerTargetCount = getCallerTargetCount();
             if (position < callerTargetCount) {
                 return mCallerTargets.get(position);
             }
             offset += callerTargetCount;
 
-            final int serviceTargetCount = mServiceTargets.size();
+            final int serviceTargetCount = getServiceTargetCount();
             if (position - offset < serviceTargetCount) {
                 return mServiceTargets.get(position - offset);
             }
@@ -774,15 +794,49 @@
         public void addServiceResults(DisplayResolveInfo origTarget, List<ChooserTarget> targets) {
             if (DEBUG) Log.d(TAG, "addServiceResults " + origTarget + ", " + targets.size()
                     + " targets");
+            final float parentScore = getScore(origTarget);
+            Collections.sort(targets, mBaseTargetComparator);
+            float lastScore = 0;
             for (int i = 0, N = targets.size(); i < N; i++) {
-                mServiceTargets.add(new ChooserTargetInfo(origTarget, targets.get(i)));
+                final ChooserTarget target = targets.get(i);
+                float targetScore = target.getScore();
+                targetScore *= parentScore;
+                targetScore *= mLateFee;
+                if (i > 0 && targetScore >= lastScore) {
+                    // Apply a decay so that the top app can't crowd out everything else.
+                    // This incents ChooserTargetServices to define what's truly better.
+                    targetScore = lastScore * 0.95f;
+                }
+                insertServiceTarget(new ChooserTargetInfo(origTarget, target, targetScore));
+
+                if (DEBUG) {
+                    Log.d(TAG, " => " + target.toString() + " score=" + targetScore
+                            + " base=" + target.getScore()
+                            + " lastScore=" + lastScore
+                            + " parentScore=" + parentScore
+                            + " lateFee=" + mLateFee);
+                }
+
+                lastScore = targetScore;
             }
 
-            // TODO: Maintain sort by ranking scores.
+            mLateFee *= 0.95f;
 
             notifyDataSetChanged();
         }
 
+        private void insertServiceTarget(ChooserTargetInfo chooserTargetInfo) {
+            final float newScore = chooserTargetInfo.getModifiedScore();
+            for (int i = 0, N = mServiceTargets.size(); i < N; i++) {
+                final ChooserTargetInfo serviceTarget = mServiceTargets.get(i);
+                if (newScore > serviceTarget.getModifiedScore()) {
+                    mServiceTargets.add(i, chooserTargetInfo);
+                    return;
+                }
+            }
+            mServiceTargets.add(chooserTargetInfo);
+        }
+
         private void pruneServiceTargets() {
             if (DEBUG) Log.d(TAG, "pruneServiceTargets");
             for (int i = mServiceTargets.size() - 1; i >= 0; i--) {
@@ -795,6 +849,14 @@
         }
     }
 
+    static class BaseChooserTargetComparator implements Comparator<ChooserTarget> {
+        @Override
+        public int compare(ChooserTarget lhs, ChooserTarget rhs) {
+            // Descending order
+            return (int) Math.signum(lhs.getScore() - rhs.getScore());
+        }
+    }
+
     class ChooserRowAdapter extends BaseAdapter {
         private ChooserListAdapter mChooserListAdapter;
         private final LayoutInflater mLayoutInflater;
diff --git a/core/java/com/android/internal/app/MediaRouteControllerDialog.java b/core/java/com/android/internal/app/MediaRouteControllerDialog.java
index 4a468be..b0e0373 100644
--- a/core/java/com/android/internal/app/MediaRouteControllerDialog.java
+++ b/core/java/com/android/internal/app/MediaRouteControllerDialog.java
@@ -18,7 +18,7 @@
 
 import com.android.internal.R;
 
-import android.app.AlertDialog;
+import android.app.Dialog;
 import android.app.MediaRouteActionProvider;
 import android.app.MediaRouteButton;
 import android.content.Context;
@@ -46,7 +46,7 @@
  *
  * TODO: Move this back into the API, as in the support library media router.
  */
-public class MediaRouteControllerDialog extends AlertDialog {
+public class MediaRouteControllerDialog extends Dialog {
     // Time to wait before updating the volume when the user lets go of the seek bar
     // to allow the route provider time to propagate the change and publish a new
     // route descriptor.
@@ -134,6 +134,8 @@
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
+        getWindow().requestFeature(Window.FEATURE_LEFT_ICON);
+
         setContentView(R.layout.media_route_controller_dialog);
 
         mVolumeLayout = (LinearLayout)findViewById(R.id.media_route_volume_layout);
diff --git a/core/java/com/android/internal/app/ResolverActivity.java b/core/java/com/android/internal/app/ResolverActivity.java
index e5ff51c..7bc18f3 100644
--- a/core/java/com/android/internal/app/ResolverActivity.java
+++ b/core/java/com/android/internal/app/ResolverActivity.java
@@ -1142,6 +1142,10 @@
             return mFilterLastUsed && mLastChosenPosition >= 0;
         }
 
+        public float getScore(DisplayResolveInfo target) {
+            return mResolverComparator.getScore(target.getResolvedComponentName());
+        }
+
         private void rebuildList() {
             List<ResolvedComponentInfo> currentResolveList = null;
 
diff --git a/core/java/com/android/internal/app/ResolverComparator.java b/core/java/com/android/internal/app/ResolverComparator.java
index 585cdf1..31556e2 100644
--- a/core/java/com/android/internal/app/ResolverComparator.java
+++ b/core/java/com/android/internal/app/ResolverComparator.java
@@ -191,6 +191,14 @@
         return mCollator.compare(sa.toString().trim(), sb.toString().trim());
     }
 
+    public float getScore(ComponentName name) {
+        final ScoredTarget target = mScoredTargets.get(name);
+        if (target != null) {
+            return target.score;
+        }
+        return 0;
+    }
+
     static class ScoredTarget {
         public final ComponentInfo componentInfo;
         public float score;
diff --git a/core/java/com/android/internal/logging/MetricsLogger.java b/core/java/com/android/internal/logging/MetricsLogger.java
index 263e522..66fa8fc 100644
--- a/core/java/com/android/internal/logging/MetricsLogger.java
+++ b/core/java/com/android/internal/logging/MetricsLogger.java
@@ -43,7 +43,7 @@
     public static final int SYSTEM_ALERT_WINDOW_APPS = 221;
     public static final int DREAMING = 222;
     public static final int DOZING = 223;
-
+    public static final int OVERVIEW_ACTIVITY = 224;
     // Temporary constants go here, to await migration to MetricsConstants.
 
     public static void visible(Context context, int category) throws IllegalArgumentException {
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 8b4b9942..f421189 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -183,6 +183,7 @@
     public interface ExternalStatsSync {
         void scheduleSync(String reason);
         void scheduleWifiSync(String reason);
+        void scheduleCpuSyncDueToRemovedUid(int uid);
     }
 
     public final MyHandler mHandler;
@@ -2522,13 +2523,28 @@
         mIsolatedUids.put(isolatedUid, appUid);
     }
 
-    public void removeIsolatedUidLocked(int isolatedUid, int appUid) {
+    /**
+     * Schedules a read of the latest cpu times before removing the isolated UID.
+     * @see #removeIsolatedUidLocked(int)
+     */
+    public void scheduleRemoveIsolatedUidLocked(int isolatedUid, int appUid) {
         int curUid = mIsolatedUids.get(isolatedUid, -1);
         if (curUid == appUid) {
-            mIsolatedUids.delete(isolatedUid);
+            if (mExternalSync != null) {
+                mExternalSync.scheduleCpuSyncDueToRemovedUid(isolatedUid);
+            }
         }
     }
 
+    /**
+     * This should only be called after the cpu times have been read.
+     * @see #scheduleRemoveIsolatedUidLocked(int, int)
+     */
+    public void removeIsolatedUidLocked(int isolatedUid) {
+        mIsolatedUids.delete(isolatedUid);
+        mKernelUidCpuTimeReader.removeUid(isolatedUid);
+    }
+
     public int mapUid(int uid) {
         int isolated = mIsolatedUids.get(uid, -1);
         return isolated > 0 ? isolated : uid;
diff --git a/core/java/com/android/internal/view/FloatingActionMode.java b/core/java/com/android/internal/view/FloatingActionMode.java
index b2699f8..ef2fef0 100644
--- a/core/java/com/android/internal/view/FloatingActionMode.java
+++ b/core/java/com/android/internal/view/FloatingActionMode.java
@@ -45,6 +45,7 @@
     private final Rect mPreviousContentRectOnWindow;
     private final int[] mViewPosition;
     private final int[] mPreviousViewPosition;
+    private final int[] mRootViewPosition;
     private final Rect mViewRect;
     private final Rect mPreviousViewRect;
     private final Rect mScreenRect;
@@ -80,6 +81,7 @@
         mPreviousContentRectOnWindow = new Rect();
         mViewPosition = new int[2];
         mPreviousViewPosition = new int[2];
+        mRootViewPosition = new int[2];
         mViewRect = new Rect();
         mPreviousViewRect = new Rect();
         mScreenRect = new Rect();
@@ -137,7 +139,9 @@
         checkToolbarInitialized();
 
         mOriginatingView.getLocationInWindow(mViewPosition);
+        mOriginatingView.getRootView().getLocationInWindow(mRootViewPosition);
         mOriginatingView.getGlobalVisibleRect(mViewRect);
+        mViewRect.offset(mRootViewPosition[0], mRootViewPosition[1]);
 
         if (!Arrays.equals(mViewPosition, mPreviousViewPosition)
                 || !mViewRect.equals(mPreviousViewRect)) {
diff --git a/core/java/com/android/internal/widget/ResolverDrawerLayout.java b/core/java/com/android/internal/widget/ResolverDrawerLayout.java
index 1071e12..fc9a1a5 100644
--- a/core/java/com/android/internal/widget/ResolverDrawerLayout.java
+++ b/core/java/com/android/internal/widget/ResolverDrawerLayout.java
@@ -231,7 +231,7 @@
                 mInitialTouchY = mLastTouchY = y;
                 mActivePointerId = ev.getPointerId(0);
                 final boolean hitView = findChildUnder(mInitialTouchX, mInitialTouchY) != null;
-                handled = (!hitView && mOnDismissedListener != null) || mCollapsibleHeight > 0;
+                handled = mOnDismissedListener != null || mCollapsibleHeight > 0;
                 mIsDragging = hitView && handled;
                 abortAnimation();
             }
diff --git a/core/jni/android_hardware_SensorManager.cpp b/core/jni/android_hardware_SensorManager.cpp
index 1356c99..ec56507 100644
--- a/core/jni/android_hardware_SensorManager.cpp
+++ b/core/jni/android_hardware_SensorManager.cpp
@@ -141,18 +141,18 @@
     return (jlong) new SensorManager(String16(opPackageNameUtf.c_str()));
 }
 
-static jint
-nativeGetNextSensor(JNIEnv *env, jclass clazz, jlong sensorManager, jobject sensor, jint next)
+static jboolean
+nativeGetSensorAtIndex(JNIEnv *env, jclass clazz, jlong sensorManager, jobject sensor, jint index)
 {
     SensorManager* mgr = reinterpret_cast<SensorManager*>(sensorManager);
 
     Sensor const* const* sensorList;
     size_t count = mgr->getSensorList(&sensorList);
-    if (size_t(next) >= count) {
-        return -1;
+    if (size_t(index) >= count) {
+        return false;
     }
 
-    Sensor const* const list = sensorList[next];
+    Sensor const* const list = sensorList[index];
     const SensorOffsets& sensorOffsets(gSensorOffsets);
     jstring name = getInternedString(env, &list->getName());
     jstring vendor = getInternedString(env, &list->getVendor());
@@ -177,8 +177,7 @@
         jstring stringType = getInternedString(env, &list->getStringType());
         env->SetObjectField(sensor, sensorOffsets.stringType, stringType);
     }
-    next++;
-    return size_t(next) < count ? next : 0;
+    return true;
 }
 
 static jboolean nativeIsDataInjectionEnabled(JNIEnv *_env, jclass _this, jlong sensorManager) {
@@ -352,9 +351,9 @@
              "(Ljava/lang/String;)J",
              (void*)nativeCreate },
 
-    {"nativeGetNextSensor",
-            "(JLandroid/hardware/Sensor;I)I",
-            (void*)nativeGetNextSensor },
+    {"nativeGetSensorAtIndex",
+            "(JLandroid/hardware/Sensor;I)Z",
+            (void*)nativeGetSensorAtIndex },
 
     {"nativeIsDataInjectionEnabled",
             "(J)Z",
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 451813c..3bb2abb1 100755
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -369,7 +369,7 @@
     <bool translatable="false" name="config_wifi_dual_band_support">false</bool>
 
     <!-- Boolean indicating whether Hotspot 2.0/Passpoint and ANQP queries is enabled -->
-    <bool translatable="false" name="config_wifi_hotspot2_enabled">true</bool>
+    <bool translatable="false" name="config_wifi_hotspot2_enabled">false</bool>
 
     <!-- Device type information conforming to Annex B format in WiFi Direct specification.
          The default represents a dual-mode smartphone -->
@@ -1266,7 +1266,7 @@
          of their choosing.
          This can be overridden for devices where a different default SMS
          application is desired. -->
-    <string name="default_sms_application" translatable="false">com.android.mms</string>
+    <string name="default_sms_application" translatable="false">com.google.android.apps.messaging</string>
 
     <!-- Default web browser.  This is the package name of the application that will
          be the default browser when the device first boots.  Afterwards the user
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index ab798bb..568e61e 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -2606,115 +2606,50 @@
   <!-- ===============================================================
        Resources added in version MNC of the platform
        =============================================================== -->
-  <eat-comment />
+    <eat-comment />
 
-  <public type="attr" name="trackTint" />
-  <public type="attr" name="trackTintMode" />
-  <public type="attr" name="start" />
-  <public type="attr" name="end" />
-  <public type="attr" name="windowLightStatusBar" />
-  <public type="attr" name="numbersInnerTextColor" />
+    <public type="attr" name="trackTint" id="0x010104d9" />
+    <public type="attr" name="trackTintMode" id="0x010104da" />
+    <public type="attr" name="start" id="0x010104db" />
+    <public type="attr" name="end" id="0x010104dc" />
+    <public type="attr" name="breakStrategy" id="0x010104dd" />
+    <public type="attr" name="hyphenationFrequency" id="0x010104de" />
+    <public type="attr" name="allowUndo" id="0x010104df" />
+    <public type="attr" name="windowLightStatusBar" id="0x010104e0" />
+    <public type="attr" name="numbersInnerTextColor" id="0x010104e1" />
+    <public type="attr" name="colorBackgroundFloating" id="0x010104e2" />
+    <public type="attr" name="titleTextColor" id="0x010104e3" />
+    <public type="attr" name="subtitleTextColor" id="0x010104e4" />
+    <public type="attr" name="thumbPosition" id="0x010104e5" />
+    <public type="attr" name="scrollIndicators" id="0x010104e6" />
+    <public type="attr" name="contextClickable" id="0x010104e7" />
+    <public type="attr" name="fingerprintAuthDrawable" id="0x010104e8" />
+    <public type="attr" name="logoDescription" id="0x010104e9" />
+    <public type="attr" name="extractNativeLibs" id="0x010104ea" />
+    <public type="attr" name="fullBackupContent" id="0x010104eb" />
+    <public type="attr" name="usesCleartextTraffic" id="0x010104ec" />
+    <public type="attr" name="lockTaskMode" id="0x010104ed" />
+    <public type="attr" name="autoVerify" id="0x010104ee" />
+    <public type="attr" name="showForAllUsers" id="0x010104ef" />
+    <public type="attr" name="supportsAssist" id="0x010104f0" />
+    <public type="attr" name="supportsLaunchVoiceAssistFromKeyguard" id="0x010104f1" />
 
-  <attr name="__reserved2" format="boolean" />
-  <public type="attr" name="__reserved2" />
-  <attr name="__reserved3" format="boolean" />
-  <public type="attr" name="__reserved3" />
-  <attr name="__reserved4" format="boolean" />
-  <public type="attr" name="__reserved4" />
-  <attr name="__reserved5" format="boolean" />
-  <public type="attr" name="__reserved5" />
-  <attr name="__reserved6" format="boolean" />
-  <public type="attr" name="__reserved6" />
-  <attr name="__reserved7" format="boolean" />
-  <public type="attr" name="__reserved7" />
+    <public type="style" name="Widget.Material.Button.Colored" id="0x010302d3" />
+    <public type="style" name="TextAppearance.Material.Widget.Button.Inverse" id="0x010302d4" />
+    <public type="style" name="Theme.Material.Light.LightStatusBar" id="0x010302d5" />
+    <public type="style" name="ThemeOverlay.Material.Dialog" id="0x010302d6" />
+    <public type="style" name="ThemeOverlay.Material.Dialog.Alert" id="0x010302d7" />
 
-  <public type="attr" name="fullBackupContent" />
-
-  <public type="style" name="Widget.Material.Button.Colored" />
-
-  <style name="__reserved8" />
-  <public type="style" name="__reserved8" />
-  <style name="__reserved9" />
-  <public type="style" name="__reserved9" />
-  <style name="__reserved10" />
-  <public type="style" name="__reserved10" />
-  <style name="__reserved11" />
-  <public type="style" name="__reserved11" />
-  <style name="__reserved12" />
-  <public type="style" name="__reserved12" />
-  <style name="__reserved13" />
-  <public type="style" name="__reserved13" />
-  <style name="__reserved14" />
-  <public type="style" name="__reserved14" />
-  <style name="__reserved15" />
-  <public type="style" name="__reserved15" />
-  <style name="__reserved16" />
-  <public type="style" name="__reserved16" />
-  <style name="__reserved17" />
-  <public type="style" name="__reserved17" />
-  <style name="__reserved18" />
-  <public type="style" name="__reserved18" />
-  <style name="__reserved19" />
-  <public type="style" name="__reserved19" />
-  <style name="__reserved20" />
-  <public type="style" name="__reserved20" />
-  <style name="__reserved21" />
-  <public type="style" name="__reserved21" />
-  <style name="__reserved22" />
-  <public type="style" name="__reserved22" />
-  <public type="style" name="Theme.Material.Light.LightStatusBar" />
-  <public type="style" name="ThemeOverlay.Material.Dialog" />
-  <public type="style" name="TextAppearance.Material.Widget.Button.Inverse" />
-  <public type="style" name="ThemeOverlay.Material.Dialog.Alert" />
-
-  <public type="id" name="pasteAsPlainText" />
-  <public type="id" name="undo" />
-  <public type="id" name="redo" />
-  <public type="id" name="replaceText" />
-  <public type="id" name="accessibilityActionShowOnScreen" />
-  <public type="id" name="accessibilityActionScrollToPosition" />
-  <public type="id" name="accessibilityActionScrollUp" />
-  <public type="id" name="accessibilityActionScrollLeft" />
-  <public type="id" name="accessibilityActionScrollDown" />
-  <public type="id" name="accessibilityActionScrollRight" />
-  <public type="id" name="shareText" />
-  <public type="id" name="accessibilityActionContextClick" />
-
-  <public type="attr" name="allowUndo" />
-  <public type="attr" name="colorBackgroundFloating" />
-  <public type="attr" name="extractNativeLibs" />
-  <public type="attr" name="usesCleartextTraffic" />
-
-  <!--IntentFilter auto verification -->
-  <public type="attr" name="autoVerify" />
-  <public type="attr" name="breakStrategy" />
-
-  <public type="attr" name="supportsAssist" />
-  <public type="attr" name="thumbPosition" />
-
-  <!-- Placeholder for a removed attribute. Remove this before M release. -->
-  <public type="attr" name="removeBeforeMRelease" />
-
-  <public type="attr" name="lockTaskMode" />
-
-  <!-- Placeholder for a removed attribute. Remove this before M release. -->
-  <public type="attr" name="__removeBeforeMRelease_leftIndents" />
-  <public type="attr" name="__removeBeforeMRelease_rightIndents" />
-
-  <public type="attr" name="showForAllUsers" />
-
-  <attr name="__reserved1" format="boolean" />
-  <public type="attr" name="__reserved1" />
-
-  <attr name="__reserved0" format="boolean" />
-  <public type="attr" name="__reserved0" />
-
-  <public type="attr" name="contextClickable" />
-  <public type="attr" name="supportsLaunchVoiceAssistFromKeyguard" />
-  <public type="attr" name="scrollIndicators" />
-  <public type="attr" name="hyphenationFrequency" />
-  <public type="attr" name="fingerprintAuthDrawable" />
-  <public type="attr" name="logoDescription" />
-  <public type="attr" name="titleTextColor" />
-  <public type="attr" name="subtitleTextColor" />
+    <public type="id" name="pasteAsPlainText" id="0x01020031" />
+    <public type="id" name="undo" id="0x01020032" />
+    <public type="id" name="redo" id="0x01020033" />
+    <public type="id" name="replaceText" id="0x01020034" />
+    <public type="id" name="shareText" id="0x01020035" />
+    <public type="id" name="accessibilityActionShowOnScreen" id="0x01020036" />
+    <public type="id" name="accessibilityActionScrollToPosition" id="0x01020037" />
+    <public type="id" name="accessibilityActionScrollUp" id="0x01020038" />
+    <public type="id" name="accessibilityActionScrollLeft" id="0x01020039" />
+    <public type="id" name="accessibilityActionScrollDown" id="0x0102003a" />
+    <public type="id" name="accessibilityActionScrollRight" id="0x0102003b" />
+    <public type="id" name="accessibilityActionContextClick" id="0x0102003c" />
 </resources>
diff --git a/docs/html/preview/api-overview.jd b/docs/html/preview/api-overview.jd
index 1686d79..75b3c528 100644
--- a/docs/html/preview/api-overview.jd
+++ b/docs/html/preview/api-overview.jd
@@ -86,9 +86,11 @@
 <a href="{@docRoot}preview/features/app-linking.html">App Linking</a>.
 
 <h2 id="backup">Auto Backup for Apps</h2>
-<p>The system now performs automatic full data backup and restore for apps. This behavior is
-enabled by default for apps targeting M Preview; you do not need to add any additional code. If
-users delete their Google accounts, their backup data is deleted as well. To learn how this feature
+<p>The system now performs automatic full data backup and restore for apps. For the
+duration of the <a href="{@docRoot}preview/overview.html">M Developer Preview program</a>, all
+apps are backed up, independent of which SDK version they target. After the final M SDK release,
+your app must target M to enable this behavior; you do not need to add any additional code. If users
+delete their Google accounts, their backup data is deleted as well. To learn how this feature
 works and how to configure what to back up on the file system, see
 <a href="{@docRoot}preview/backup/index.html">Auto Backup for Apps</a>.</p>
 
@@ -152,10 +154,9 @@
 
 <p>To set the timeout duration for which the same key can be re-used after a user is successfully
 authenticated, call the new
-{@code android.security.keystore.KeyGenParameterSpec.setUserAuthenticationValidityDurationSeconds()}
+{@code android.security.keystore.KeyGenParameterSpec.Builder.setUserAuthenticationValidityDurationSeconds()}
 method when you set up a {@link javax.crypto.KeyGenerator} or
-{@link java.security.KeyPairGenerator}. This feature currently works for symmetric cryptographic
-operations.</p>
+{@link java.security.KeyPairGenerator}.</p>
 
 <p>Avoid showing the re-authentication dialog excessively -- your apps should try using the
 cryptographic object first and if the the timeout expires, use the
@@ -236,7 +237,7 @@
 <p>Your app can elect to not share the current context with the assistant by setting the
 {@link android.view.WindowManager.LayoutParams#FLAG_SECURE} flag. In addition to the
 standard set of information that the platform passes to the assistant, your app can share
-additional information by using the new {@code android.app.Activity.AssistContent} class.</p>
+additional information by using the new {@code android.app.assist.AssistContent} class.</p>
 
 <p>To provide the assistant with additional context from your app, follow these steps:</p>
 
@@ -273,7 +274,7 @@
 information from the touch screen is fused with pressure and button information from the stylus to
 provide a greater range of expression than with the touch screen alone. Your app can listen for
 stylus button presses and perform secondary actions, by registering the new
-{@code View.onStylusButtonPressListener} and {@code GestureDetector.OnStylusButtonPressListener}
+{@code View.onContextClickListener} and {@code GestureDetector.onContextClickListener}
 callbacks in your activity.</p>
 
 <p>Use the {@link android.view.MotionEvent} methods and constants to detect stylus button
@@ -284,11 +285,11 @@
 {@link android.view.MotionEvent#TOOL_TYPE_STYLUS}.</li>
 <li>For apps targeting M Preview, the
 {@link android.view.MotionEvent#getButtonState() getButtonState()}
-method returns {@code MotionEvent.STYLUS_BUTTON_PRIMARY} when the user
+method returns {@code MotionEvent.BUTTON_STYLUS_PRIMARY} when the user
 presses the primary stylus button. If the stylus has a second button, the same method returns
-{@code MotionEvent.STYLUS_BUTTON_SECONDARY} when the user presses it. If the user presses
+{@code MotionEvent.BUTTON_STYLUS_SECONDARY} when the user presses it. If the user presses
 both buttons simultaneously, the method returns both values OR'ed together
-({@code STYLUS_BUTTON_PRIMARY|STYLUS_BUTTON_SECONDARY}).</li>
+({@code BUTTON_STYLUS_PRIMARY|BUTTON_STYLUS_SECONDARY}).</li>
 <li>
 For apps targeting a lower platform version, the
 {@link android.view.MotionEvent#getButtonState() getButtonState()} method returns
@@ -314,7 +315,7 @@
 {@link android.net.wifi.WifiEnterpriseConfig} class, such as {@code setPlmn()} and
 {@code setRealm()}. In the {@link android.net.wifi.WifiConfiguration} object, you can set the
 {@link android.net.wifi.WifiConfiguration#FQDN} and the {@code providerFriendlyName} fields.
-The new {@code ScanResult.PasspointNetwork} property indicates if a detected
+The new {@code ScanResult.isPasspointNetwork()} method indicates if a detected
 network represents a Hotspot 2.0 access point.
 </p>
 
@@ -356,10 +357,10 @@
 TV. The system invokes the new {@code android.app.Activity.onSearchRequested()} callback when the
 user starts a search. To determine if the user's input device has a built-in microphone, retrieve
 the {@link android.view.InputDevice} object from that callback, then call the new
-{@code InputDevice.hasMic()} method.</li>
-  <li>New {@code android.media.AudioDevicesManager} class which lets you retrieve a list of all
-attached source and sink audio devices. You can also specify an
-{@code android.media.OnAudioDeviceConnectionListener} object if you want your app to be notified
+{@code InputDevice.hasMicrophone()} method.</li>
+  <li>New {@code AudioManager.getDevices() method which lets you retrieve a list of all
+    audio devices currently connected to the system. You can also register an
+{@code android.media.AudioDeviceCallback} object if you want your app to be notified
 when an audio device is connected or disconnected.</li>
 </ul>
 
@@ -407,14 +408,15 @@
 
 <h3 id="reprocessing">Reprocessing API</h3>
 <p>The {@link android.hardware.camera2 Camera2} API is extended to support YUV and private
-opaque format image reprocessing. Your app determine if the reprocessing capabilities are available
-via {@code CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES}. If a device supports reprocessing,
-you can create a reprocessable camera capture session by calling
+opaque format image reprocessing. To determine if these reprocessing capabilities are available,
+call {@link android.hardware.camera2.CameraManager#getCameraCharacteristics(java.lang.String)
+getCameraCharacteristics()} and check for the {@code REPROCESS_MAX_CAPTURE_STALL} key. If a
+device supports reprocessing, you can create a reprocessable camera capture session by calling
 {@code CameraDevice.createReprocessableCaptureSession()}, and create requests for input
 buffer reprocessing.</p>
 
-<p>Use the {@code ImageWriter} class to connect the input buffer flow to the camera reprocessing
-input. To get an empty buffer, follow this programming model:</p>
+<p>Use the {@code android.media.ImageWriter} class to connect the input buffer flow to the camera
+reprocessing input. To get an empty buffer, follow this programming model:</p>
 
 <ol>
 <li>Call the {@code ImageWriter.dequeueInputImage()} method.</li>
@@ -428,10 +430,10 @@
 {@code ImageWriter} by calling the {@code ImageWriter.queueInputImage()} method without any
 buffer copy.</p>
 
-<p>The {@code ImageReader} class now supports {@code android.graphics.ImageFormat.PRIVATE} format
-image streams. This support allows your app to maintain a circular image queue of
-{@code ImageReader} output images, select one or more images, and send them to the
-{@code ImageWriter} for camera reprocessing.</p>
+<p>The {@link android.media.ImageReader} class now supports
+{@code android.graphics.ImageFormat.PRIVATE} format image streams. This support allows your app to
+maintain a circular image queue of {@link android.media.ImageReader} output images, select one or
+more images, and send them to the {@code ImageWriter} for camera reprocessing.</p>
 
 <h2 id="afw">Android for Work Features</h2>
 <p>This preview includes the following new APIs for Android for Work:</p>
@@ -441,10 +443,10 @@
 Corporate-Owned, Single-Use (COSU) devices:
   <ul>
     <li>Disable or re-enable the keyguard with the
-{@code DevicePolicyManager.setKeyguardEnabledState()} method.</li>
+{@code DevicePolicyManager.setKeyguardDisabled()} method.</li>
     <li>Disable or re-enable the status bar (including quick settings, notifications, and the
 navigation swipe-up gesture that launches Google Now) with the
-{@code DevicePolicyManager.setStatusBarEnabledState()} method.</li>
+{@code DevicePolicyManager.setStatusBarDisabled()} method.</li>
     <li>Disable or re-enable safe boot with the {@link android.os.UserManager} constant
 {@code DISALLOW_SAFE_BOOT}.</li>
     <li>Prevent the screen from turning off while plugged in with the
@@ -489,16 +491,6 @@
 installKeyPair()}</li>
 </ul>
 </li>
-<li><strong>Enterprise factory reset protection:</strong> When provisioning a Device Owner, you can
-now configure parameters to unlock Factory Reset Protection (FRP) by setting the
-{@code DeviceManagerPolicy.EXTRA_PROVISIONING_RESET_PROTECTION_PARAMETERS} bundle. An NFC Programmer
-app can provide these parameters after a device has been reset to unlock FRP and provision the device,
-without requiring the previously configured Google account. If you don't modify these parameters,
-FRP remains in-place and prevents the device from being activated without the previously activated
-Google credentials.
-<p>Additionally, by setting app restrictions on Google Play services, Device Owners can specify
-alternative Google accounts for unlocking FRP to replace the ones activated on the device.</p>
-</li>
 <img src="{@docRoot}preview/images/work-profile-screen.png"
 srcset="{@docRoot}preview/images/work-profile-screen.png 1x, {@docRoot}preview/images/work-profile-screen_2x.png 2x"
 style="float:right; margin:0 0 10px 20px" width="282" height="476" />
diff --git a/docs/html/preview/behavior-changes.jd b/docs/html/preview/behavior-changes.jd
index 5ddac7a..8a8ea05 100644
--- a/docs/html/preview/behavior-changes.jd
+++ b/docs/html/preview/behavior-changes.jd
@@ -23,8 +23,9 @@
     <li><a href="#behavior-keystore">Android Keystore Changes</a></li>
     <li><a href="#behavior-network">Wi-Fi and Networking Changes</a></li>
     <li><a href="#behavior-camera">Camera Service Changes</a></li>
-    <li><a href="#behavior-art-runtime">ART Runtime</a></li>
+    <li><a href="#behavior-runtime">Runtime</a></li>
     <li><a href="#behavior-apk-validation">APK Validation</a></li>
+    <li><a href="#behavior-usb">USB Connection</a></li>
     <li><a href="#behavior-afw">Android for Work Changes</a></li>
 </ol>
 
@@ -46,8 +47,8 @@
 system changes and API behavior changes. This document highlights
 some of the key changes that you should understand and account for in your apps.</p>
 
-<p>If you have previously published an app for Android, be aware that your app
-  might be affected by these changes in the platform.</p>
+<p>If you have previously published an app for Android, be aware that these changes in the
+platform affect your app.</p>
 
 <h2 id="behavior-runtime-permissions">Runtime Permissions</h1>
 <p>This preview introduces a new permissions model, where users can now directly manage
@@ -55,11 +56,11 @@
 permissions, while streamlining the installation and auto-update processes for app developers.
 Users can grant or revoke permissions individually for installed apps. </p>
 
-<p>On your apps that target the M Preview, make sure to check and request for permissions at
-runtime. To determine if your app has been granted a permission, call the
-new {@code Context.checkSelfPermission()} method. To request for a permission, call the new
-{@code Activity.requestPermission()} method. Even if your app is not targeting M, you
-should test your app under the new permissions model.</p>
+<p>On your apps that target the M Preview release or higher, make sure to check for and request
+permissions at runtime. To determine if your app has been granted a permission, call the
+new {@code Context.checkSelfPermission()} method. To request a permission, call the new
+{@code Activity.requestPermission()} method. Even if your app is not targeting the M Preview
+release, you should test your app under the new permissions model.</p>
 
 <p>For details on supporting the new permissions model in your app, see the
 <a href="{@docRoot}preview/features/runtime-permissions.html">
@@ -329,7 +330,7 @@
 </li>
 </ul>
 
-<h2 id="behavior-art-runtime">ART Runtime</h2>
+<h2 id="behavior-runtime">Runtime</h2>
 <p>The ART runtime now properly implements access rules for the
 {@link java.lang.reflect.Constructor#newInstance(java.lang.Object...) newInstance()} method. This
 change fixes a problem where Dalvik was checking access rules incorrectly in previous versions.
@@ -362,14 +363,22 @@
 declared in the manifest but not present in the APK itself. An APK must be re-signed if any of the
 contents are removed.</p>
 
+<h2 id="behavior-usb">USB Connection</h2>
+<p>Device connections through the USB port are now set to charge-only mode by default. To access
+the device and its content over a USB connection, users must explicitly grant permission for such
+interactions. If your app supports user interactions with the device over a USB port, take into
+consideration that the interaction must be explicitly enabled.
+</p>
+
 <h2 id="behavior-afw">Android for Work Changes</h2>
 <p>This preview includes the following behavior changes for Android for Work:</p>
 <ul>
 <li><strong>Work contacts in personal contexts.</strong> The Google Dialer
 Call Log now displays work contacts when the user views past calls.
-Setting {@code DevicePolicyManager.setCrossProfileCallerIdDisabled()} to {@code true} hides the
-work profile contacts in the Google Dialer Call Log. Work contacts can be displayed along with
-personal contacts to devices over Bluetooth only if
+Setting
+{@link android.app.admin.DevicePolicyManager#setCrossProfileCallerIdDisabled(android.content.ComponentName, boolean) setCrossProfileCallerIdDisabled()}
+to {@code true} hides the work profile contacts in the Google Dialer Call Log. Work contacts can be
+displayed along with personal contacts to devices over Bluetooth only if
 you set {@code DevicePolicyManager.setBluetoothContactSharingDisabled()} to {@code false}. By
 default, it is set to {@code true}.
 </li>
diff --git a/docs/html/preview/features/runtime-permissions.jd b/docs/html/preview/features/runtime-permissions.jd
index 79f0d88..06a2f3d 100644
--- a/docs/html/preview/features/runtime-permissions.jd
+++ b/docs/html/preview/features/runtime-permissions.jd
@@ -35,12 +35,23 @@
 <!--
   <h2>See also</h2>
   <ol>
-    <li></li>
+    <li>
+    </li>
   </ol>
 -->
+
   </div> <!-- qv -->
 </div> <!-- qv-wrapper -->
 
+<!-- video box -->
+<a class="notice-developers-video"
+    href="https://www.youtube.com/watch?v=f17qe9vZ8RM">
+<div>
+    <h3>Video</h3>
+    <p>Google I/O 2015—Android M Permissions: Best Practices for
+      Developers</p>
+</div>
+</a>
 
 <p>
   The M Developer Preview introduces a new app permissions model which
@@ -204,12 +215,7 @@
 
 <ul>
   <li>System components automatically receive all
-  the permissions listed in their manifests. However, the user can still revoke
-  permissions at any time by going to the system's <strong>Settings</strong>
-  app and choosing <strong>Apps &gt;</strong> <i>app_name</i> <strong>&gt;
-  Permissions</strong>. Because users can revoke these permissions at will,
-  the app should continue to check for permissions at run
-  time and request them if necessary.
+  the permissions listed in their manifests.
   </li>
 
   <li>If the app requests permissions in the manifest that fall under {@link
@@ -952,10 +958,6 @@
   </li>
 
   <li>
-    <code>android.permission.READ_EXTERNAL_STORAGE</code>
-  </li>
-
-  <li>
     <code>android.permission.REORDER_TASKS</code>
   </li>
 
diff --git a/docs/html/preview/support.jd b/docs/html/preview/support.jd
index 7ae7a98..f05fa98 100644
--- a/docs/html/preview/support.jd
+++ b/docs/html/preview/support.jd
@@ -30,10 +30,12 @@
     <dt>API Name Changes:</dt>
     <dd>
       <ul>
-        <li>Moved the {@code android.app.AssistContent} class to a different package,
-          {@code android.app.assist.AssistContent} in the Assist API.</li>
-        <li>Moved the {@code android.app.AssistStructure} class to a different package,
-          {@code android.app.assist.AssistStructure} in the Assist API.</li>
+        <li>Moved the {@code android.app.AssistContent} class into the new package,
+          {@code android.app.assist} in the Assist API. The full class
+          name is now {@code android.app.assist.AssistContent}.</li>
+        <li>Moved the {@code android.app.AssistStructure} class to the new package,
+          {@code android.app.assist} in the Assist API. The full class name
+          is now {@code android.app.assist.AssistStructure}.</li>
         <li>Replaced the {@code ScanResult.PasspointNetwork} property with the
           {@code ScanResult.isPasspointNetwork()} method for HotSpot 2.0 support.</li>
         <li>Replaced the {@code InputDevice.hasMic()} method with {@code InputDevice.hasMicrophone()}
@@ -44,7 +46,7 @@
           {@code GestureDetector.OnContextClickListener} for Bluetooth Stylus support.</li>
         <li>Renamed the {@code android.app.usage.NetworkUsageStats} class to
           {@code android.app.usage.NetworkStats}.</li>
-        <li>Renames the {@code android.app.usage.NetworkUsageStats.Bucket} class to
+        <li>Renamed the {@code android.app.usage.NetworkUsageStats.Bucket} class to
           {@code android.app.usage.NetworkStats.Bucket}.</li>
       </ul>
     </dd>
diff --git a/docs/html/preview/testing/performance.jd b/docs/html/preview/testing/performance.jd
index abb41c4..6f0a5f1 100644
--- a/docs/html/preview/testing/performance.jd
+++ b/docs/html/preview/testing/performance.jd
@@ -112,10 +112,10 @@
 </p>
 
 <pre class="noprettyprint">
-0,49762224585003,49762241251670,9223372036854775807,0,49762257627204,49762257646058,49762257969704,49762258002100,49762265541631,49762273951162,49762300914808,49762303675954,
-0,49762445152142,49762445152142,9223372036854775807,0,49762446678818,49762446705589,49762447268818,49762447388037,49762453551527,49762457134131,49762474889027,49762476150120,
-0,49762462118845,49762462118845,9223372036854775807,0,49762462595381,49762462619287,49762462919964,49762462968454,49762476194547,49762476483454,49762480214964,49762480911527,
-0,49762479085548,49762479085548,9223372036854775807,0,49762480066370,49762480099339,49762481013089,49762481085850,49762482232152,49762482478350,49762485657620,49762486116683,
+0,27965466202353,27965466202353,27965449758000,27965461202353,27965467153286,27965471442505,27965471925682,27965474025318,27965474588547,27965474860786,27965475078599,27965479796151,27965480589068,
+0,27965482993342,27965482993342,27965465835000,27965477993342,27965483807401,27965486875630,27965487288443,27965489520682,27965490184380,27965490568703,27965491408078,27965496119641,27965496619641,
+0,27965499784331,27965499784331,27965481404000,27965494784331,27965500785318,27965503736099,27965504201151,27965506776568,27965507298443,27965507515005,27965508405474,27965513495318,27965514061984,
+0,27965516575320,27965516575320,27965497155000,27965511575320,27965517697349,27965521276151,27965521734797,27965524350474,27965524884536,27965525160578,27965526020891,27965531371203,27965532114484,
 </pre>
 
 <p>
@@ -283,6 +283,22 @@
     </ul>
   </li>
 
+  <li>SYNC_QUEUED
+    <ul>
+      <li>The time at which a sync request was sent to the RenderThread.
+      </li>
+
+      <li>This marks the point at which a message to start the sync
+      phase was sent to the RenderThread. If the time between this and
+      SYNC_START is substantial (&gt;0.1ms or so), it means that
+      the RenderThread was busy working on a different frame. Internally
+      this is used to differentiate between the frame doing too much work
+      and exceeding the 16ms budget and the frame being stalled due to
+      the previous frame exceeding the 16ms budget.
+      </li>
+    </ul>
+  </li>
+
   <li>SYNC_START
     <ul>
       <li>The time at which the sync phase of the drawing started.
diff --git a/keystore/java/android/security/keystore/AndroidKeyStoreKeyGeneratorSpi.java b/keystore/java/android/security/keystore/AndroidKeyStoreKeyGeneratorSpi.java
index 258133d..6a7930a 100644
--- a/keystore/java/android/security/keystore/AndroidKeyStoreKeyGeneratorSpi.java
+++ b/keystore/java/android/security/keystore/AndroidKeyStoreKeyGeneratorSpi.java
@@ -239,6 +239,13 @@
                                 "At least one digest algorithm must be specified");
                     }
                 }
+
+                // Check that user authentication related parameters are acceptable. This method
+                // will throw an IllegalStateException if there are issues (e.g., secure lock screen
+                // not set up).
+                KeymasterUtils.addUserAuthArgs(new KeymasterArguments(),
+                        spec.isUserAuthenticationRequired(),
+                        spec.getUserAuthenticationValidityDurationSeconds());
             } catch (IllegalStateException | IllegalArgumentException e) {
                 throw new InvalidAlgorithmParameterException(e);
             }
diff --git a/keystore/java/android/security/keystore/AndroidKeyStoreKeyPairGeneratorSpi.java b/keystore/java/android/security/keystore/AndroidKeyStoreKeyPairGeneratorSpi.java
index 459514d..6b36a58 100644
--- a/keystore/java/android/security/keystore/AndroidKeyStoreKeyPairGeneratorSpi.java
+++ b/keystore/java/android/security/keystore/AndroidKeyStoreKeyPairGeneratorSpi.java
@@ -310,7 +310,14 @@
                 } else {
                     mKeymasterDigests = EmptyArray.INT;
                 }
-            } catch (IllegalArgumentException e) {
+
+                // Check that user authentication related parameters are acceptable. This method
+                // will throw an IllegalStateException if there are issues (e.g., secure lock screen
+                // not set up).
+                KeymasterUtils.addUserAuthArgs(new KeymasterArguments(),
+                        mSpec.isUserAuthenticationRequired(),
+                        mSpec.getUserAuthenticationValidityDurationSeconds());
+            } catch (IllegalArgumentException | IllegalStateException e) {
                 throw new InvalidAlgorithmParameterException(e);
             }
 
diff --git a/keystore/java/android/security/keystore/AndroidKeyStoreSpi.java b/keystore/java/android/security/keystore/AndroidKeyStoreSpi.java
index dc8f1e3..e9f19cd 100644
--- a/keystore/java/android/security/keystore/AndroidKeyStoreSpi.java
+++ b/keystore/java/android/security/keystore/AndroidKeyStoreSpi.java
@@ -484,8 +484,8 @@
                         spec.getKeyValidityForOriginationEnd());
                 importArgs.addDateIfNotNull(KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME,
                         spec.getKeyValidityForConsumptionEnd());
-            } catch (IllegalArgumentException e) {
-                throw new KeyStoreException("Invalid parameter", e);
+            } catch (IllegalArgumentException | IllegalStateException e) {
+                throw new KeyStoreException(e);
             }
         }
 
@@ -598,102 +598,100 @@
                     + " RAW format export");
         }
 
-        String keyAlgorithmString = key.getAlgorithm();
-        int keymasterAlgorithm;
-        int keymasterDigest;
-        try {
-            keymasterAlgorithm =
-                    KeyProperties.KeyAlgorithm.toKeymasterSecretKeyAlgorithm(keyAlgorithmString);
-            keymasterDigest = KeyProperties.KeyAlgorithm.toKeymasterDigest(keyAlgorithmString);
-        } catch (IllegalArgumentException e) {
-            throw new KeyStoreException("Unsupported secret key algorithm: " + keyAlgorithmString);
-        }
-
         KeymasterArguments args = new KeymasterArguments();
-        args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, keymasterAlgorithm);
+        try {
+            int keymasterAlgorithm =
+                    KeyProperties.KeyAlgorithm.toKeymasterSecretKeyAlgorithm(key.getAlgorithm());
+            args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, keymasterAlgorithm);
 
-        int[] keymasterDigests;
-        if (params.isDigestsSpecified()) {
-            // Digest(s) specified in parameters
-            keymasterDigests = KeyProperties.Digest.allToKeymaster(params.getDigests());
-            if (keymasterDigest != -1) {
-                // Digest also specified in the JCA key algorithm name.
-                if (!com.android.internal.util.ArrayUtils.contains(
-                        keymasterDigests, keymasterDigest)) {
-                    throw new KeyStoreException("Key digest mismatch"
-                            + ". Key: " + keyAlgorithmString
-                            + ", parameter spec: " + Arrays.asList(params.getDigests()));
-                }
-                // When the key is read back from keystore we reconstruct the JCA key algorithm
-                // name from the KM_TAG_ALGORITHM and the first KM_TAG_DIGEST. Thus we need to
-                // ensure that the digest reflected in the JCA key algorithm name is the first
-                // KM_TAG_DIGEST tag.
-                if (keymasterDigests[0] != keymasterDigest) {
-                    // The first digest is not the one implied by the JCA key algorithm name.
-                    // Swap the implied digest with the first one.
-                    for (int i = 0; i < keymasterDigests.length; i++) {
-                        if (keymasterDigests[i] == keymasterDigest) {
-                            keymasterDigests[i] = keymasterDigests[0];
-                            keymasterDigests[0] = keymasterDigest;
-                            break;
+            int[] keymasterDigests;
+            int keymasterDigest = KeyProperties.KeyAlgorithm.toKeymasterDigest(key.getAlgorithm());
+            if (params.isDigestsSpecified()) {
+                // Digest(s) specified in parameters
+                keymasterDigests = KeyProperties.Digest.allToKeymaster(params.getDigests());
+                if (keymasterDigest != -1) {
+                    // Digest also specified in the JCA key algorithm name.
+                    if (!com.android.internal.util.ArrayUtils.contains(
+                            keymasterDigests, keymasterDigest)) {
+                        throw new KeyStoreException("Digest specified in key algorithm "
+                                + key.getAlgorithm() + " not specified in protection parameters: "
+                                + Arrays.asList(params.getDigests()));
+                    }
+                    // When the key is read back from keystore we reconstruct the JCA key algorithm
+                    // name from the KM_TAG_ALGORITHM and the first KM_TAG_DIGEST. Thus we need to
+                    // ensure that the digest reflected in the JCA key algorithm name is the first
+                    // KM_TAG_DIGEST tag.
+                    if (keymasterDigests[0] != keymasterDigest) {
+                        // The first digest is not the one implied by the JCA key algorithm name.
+                        // Swap the implied digest with the first one.
+                        for (int i = 0; i < keymasterDigests.length; i++) {
+                            if (keymasterDigests[i] == keymasterDigest) {
+                                keymasterDigests[i] = keymasterDigests[0];
+                                keymasterDigests[0] = keymasterDigest;
+                                break;
+                            }
                         }
                     }
                 }
-            }
-        } else {
-            // No digest specified in parameters
-            if (keymasterDigest != -1) {
-                // Digest specified in the JCA key algorithm name.
-                keymasterDigests = new int[] {keymasterDigest};
             } else {
-                keymasterDigests = EmptyArray.INT;
-            }
-        }
-        args.addEnums(KeymasterDefs.KM_TAG_DIGEST, keymasterDigests);
-        if (keymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_HMAC) {
-            if (keymasterDigests.length == 0) {
-                throw new KeyStoreException("At least one digest algorithm must be specified"
-                        + " for key algorithm " + keyAlgorithmString);
-            }
-        }
-
-        @KeyProperties.PurposeEnum int purposes = params.getPurposes();
-        int[] keymasterBlockModes =
-                KeyProperties.BlockMode.allToKeymaster(params.getBlockModes());
-        if (((purposes & KeyProperties.PURPOSE_ENCRYPT) != 0)
-                && (params.isRandomizedEncryptionRequired())) {
-            for (int keymasterBlockMode : keymasterBlockModes) {
-                if (!KeymasterUtils.isKeymasterBlockModeIndCpaCompatibleWithSymmetricCrypto(
-                        keymasterBlockMode)) {
-                    throw new KeyStoreException(
-                            "Randomized encryption (IND-CPA) required but may be violated by block"
-                            + " mode: "
-                            + KeyProperties.BlockMode.fromKeymaster(keymasterBlockMode)
-                            + ". See KeyProtection documentation.");
+                // No digest specified in parameters
+                if (keymasterDigest != -1) {
+                    // Digest specified in the JCA key algorithm name.
+                    keymasterDigests = new int[] {keymasterDigest};
+                } else {
+                    keymasterDigests = EmptyArray.INT;
                 }
             }
-        }
-        args.addEnums(KeymasterDefs.KM_TAG_PURPOSE, KeyProperties.Purpose.allToKeymaster(purposes));
-        args.addEnums(KeymasterDefs.KM_TAG_BLOCK_MODE, keymasterBlockModes);
-        if (params.getSignaturePaddings().length > 0) {
-            throw new KeyStoreException("Signature paddings not supported for symmetric keys");
-        }
-        int[] keymasterPaddings = KeyProperties.EncryptionPadding.allToKeymaster(
-                params.getEncryptionPaddings());
-        args.addEnums(KeymasterDefs.KM_TAG_PADDING, keymasterPaddings);
-        KeymasterUtils.addUserAuthArgs(args,
-                params.isUserAuthenticationRequired(),
-                params.getUserAuthenticationValidityDurationSeconds());
-        args.addDateIfNotNull(KeymasterDefs.KM_TAG_ACTIVE_DATETIME, params.getKeyValidityStart());
-        args.addDateIfNotNull(KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME,
-                params.getKeyValidityForOriginationEnd());
-        args.addDateIfNotNull(KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME,
-                params.getKeyValidityForConsumptionEnd());
+            args.addEnums(KeymasterDefs.KM_TAG_DIGEST, keymasterDigests);
+            if (keymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_HMAC) {
+                if (keymasterDigests.length == 0) {
+                    throw new KeyStoreException("At least one digest algorithm must be specified"
+                            + " for key algorithm " + key.getAlgorithm());
+                }
+            }
 
-        if (((purposes & KeyProperties.PURPOSE_ENCRYPT) != 0)
-                && (!params.isRandomizedEncryptionRequired())) {
-            // Permit caller-provided IV when encrypting with this key
-            args.addBoolean(KeymasterDefs.KM_TAG_CALLER_NONCE);
+            @KeyProperties.PurposeEnum int purposes = params.getPurposes();
+            int[] keymasterBlockModes =
+                    KeyProperties.BlockMode.allToKeymaster(params.getBlockModes());
+            if (((purposes & KeyProperties.PURPOSE_ENCRYPT) != 0)
+                    && (params.isRandomizedEncryptionRequired())) {
+                for (int keymasterBlockMode : keymasterBlockModes) {
+                    if (!KeymasterUtils.isKeymasterBlockModeIndCpaCompatibleWithSymmetricCrypto(
+                            keymasterBlockMode)) {
+                        throw new KeyStoreException(
+                                "Randomized encryption (IND-CPA) required but may be violated by"
+                                + " block mode: "
+                                + KeyProperties.BlockMode.fromKeymaster(keymasterBlockMode)
+                                + ". See KeyProtection documentation.");
+                    }
+                }
+            }
+            args.addEnums(KeymasterDefs.KM_TAG_PURPOSE,
+                    KeyProperties.Purpose.allToKeymaster(purposes));
+            args.addEnums(KeymasterDefs.KM_TAG_BLOCK_MODE, keymasterBlockModes);
+            if (params.getSignaturePaddings().length > 0) {
+                throw new KeyStoreException("Signature paddings not supported for symmetric keys");
+            }
+            int[] keymasterPaddings = KeyProperties.EncryptionPadding.allToKeymaster(
+                    params.getEncryptionPaddings());
+            args.addEnums(KeymasterDefs.KM_TAG_PADDING, keymasterPaddings);
+            KeymasterUtils.addUserAuthArgs(args,
+                    params.isUserAuthenticationRequired(),
+                    params.getUserAuthenticationValidityDurationSeconds());
+            args.addDateIfNotNull(KeymasterDefs.KM_TAG_ACTIVE_DATETIME,
+                    params.getKeyValidityStart());
+            args.addDateIfNotNull(KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME,
+                    params.getKeyValidityForOriginationEnd());
+            args.addDateIfNotNull(KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME,
+                    params.getKeyValidityForConsumptionEnd());
+
+            if (((purposes & KeyProperties.PURPOSE_ENCRYPT) != 0)
+                    && (!params.isRandomizedEncryptionRequired())) {
+                // Permit caller-provided IV when encrypting with this key
+                args.addBoolean(KeymasterDefs.KM_TAG_CALLER_NONCE);
+            }
+        } catch (IllegalArgumentException | IllegalStateException e) {
+            throw new KeyStoreException(e);
         }
 
         Credentials.deleteAllTypesForAlias(mKeyStore, entryAlias);
diff --git a/keystore/java/android/security/keystore/KeyProperties.java b/keystore/java/android/security/keystore/KeyProperties.java
index f9fe176..2b49297 100644
--- a/keystore/java/android/security/keystore/KeyProperties.java
+++ b/keystore/java/android/security/keystore/KeyProperties.java
@@ -210,10 +210,6 @@
                 int keymasterAlgorithm, int keymasterDigest) {
             switch (keymasterAlgorithm) {
                 case KeymasterDefs.KM_ALGORITHM_AES:
-                    if (keymasterDigest != -1) {
-                        throw new IllegalArgumentException("Digest not supported for AES key: "
-                                + Digest.fromKeymaster(keymasterDigest));
-                    }
                     return KEY_ALGORITHM_AES;
                 case KeymasterDefs.KM_ALGORITHM_HMAC:
                     switch (keymasterDigest) {
diff --git a/keystore/java/android/security/keystore/KeymasterUtils.java b/keystore/java/android/security/keystore/KeymasterUtils.java
index 3cd3f2a..92d636c 100644
--- a/keystore/java/android/security/keystore/KeymasterUtils.java
+++ b/keystore/java/android/security/keystore/KeymasterUtils.java
@@ -87,6 +87,10 @@
      * @param userAuthenticationValidityDurationSeconds duration of time (seconds) for which user
      *        authentication is valid as authorization for using the key or {@code -1} if every
      *        use of the key needs authorization.
+     *
+     * @throws IllegalStateException if user authentication is required but the system is in a wrong
+     *         state (e.g., secure lock screen not set up) for generating or importing keys that
+     *         require user authentication.
      */
     public static void addUserAuthArgs(KeymasterArguments args,
             boolean userAuthenticationRequired,
diff --git a/libs/hwui/FrameInfo.cpp b/libs/hwui/FrameInfo.cpp
index 85998f1..41e2233 100644
--- a/libs/hwui/FrameInfo.cpp
+++ b/libs/hwui/FrameInfo.cpp
@@ -30,6 +30,7 @@
     "AnimationStart",
     "PerformTraversalsStart",
     "DrawStart",
+    "SyncQueued",
     "SyncStart",
     "IssueDrawCommandsStart",
     "SwapBuffers",
diff --git a/libs/hwui/FrameInfo.h b/libs/hwui/FrameInfo.h
index 23339ce..f8013ab 100644
--- a/libs/hwui/FrameInfo.h
+++ b/libs/hwui/FrameInfo.h
@@ -41,6 +41,8 @@
     DrawStart,
     // End of UI frame info
 
+    SyncQueued,
+
     SyncStart,
     IssueDrawCommandsStart,
     SwapBuffers,
@@ -117,8 +119,7 @@
     }
 
     inline int64_t operator[](FrameInfoIndex index) const {
-        if (index == FrameInfoIndex::NumIndexes) return 0;
-        return mFrameInfo[static_cast<int>(index)];
+        return get(index);
     }
 
     inline int64_t operator[](int index) const {
@@ -127,10 +128,20 @@
     }
 
     inline int64_t duration(FrameInfoIndex start, FrameInfoIndex end) const {
-        int64_t endtime = mFrameInfo[static_cast<int>(end)];
-        int64_t starttime = mFrameInfo[static_cast<int>(start)];
+        int64_t endtime = get(end);
+        int64_t starttime = get(start);
         int64_t gap = endtime - starttime;
         gap = starttime > 0 ? gap : 0;
+        if (end > FrameInfoIndex::SyncQueued &&
+                start < FrameInfoIndex::SyncQueued) {
+            // Need to subtract out the time spent in a stalled state
+            // as this will be captured by the previous frame's info
+            int64_t offset = get(FrameInfoIndex::SyncStart)
+                    - get(FrameInfoIndex::SyncQueued);
+            if (offset > 0) {
+                gap -= offset;
+            }
+        }
         return gap > 0 ? gap : 0;
     }
 
@@ -138,11 +149,16 @@
         return duration(FrameInfoIndex::IntendedVsync, FrameInfoIndex::FrameCompleted);
     }
 
-private:
     inline int64_t& set(FrameInfoIndex index) {
         return mFrameInfo[static_cast<int>(index)];
     }
 
+    inline int64_t get(FrameInfoIndex index) const {
+        if (index == FrameInfoIndex::NumIndexes) return 0;
+        return mFrameInfo[static_cast<int>(index)];
+    }
+
+private:
     int64_t mFrameInfo[static_cast<int>(FrameInfoIndex::NumIndexes)];
 };
 
diff --git a/libs/hwui/FrameInfoVisualizer.cpp b/libs/hwui/FrameInfoVisualizer.cpp
index 7f9d9b9..b416615 100644
--- a/libs/hwui/FrameInfoVisualizer.cpp
+++ b/libs/hwui/FrameInfoVisualizer.cpp
@@ -189,7 +189,7 @@
         // Set the bottom to the old top (build upwards)
         rect[ri + 3] = rect[ri + 1];
         // Move the top up by the duration
-        rect[ri + 1] -= mVerticalUnit * duration(fi, start, end);
+        rect[ri + 1] -= mVerticalUnit * durationMS(fi, start, end);
     }
 }
 
@@ -253,10 +253,10 @@
         }
         mLastFrameLogged = mFrameSource[i][FrameInfoIndex::IntendedVsync];
         fprintf(file, "\t%3.2f\t%3.2f\t%3.2f\t%3.2f\n",
-                duration(i, FrameInfoIndex::IntendedVsync, FrameInfoIndex::SyncStart),
-                duration(i, FrameInfoIndex::SyncStart, FrameInfoIndex::IssueDrawCommandsStart),
-                duration(i, FrameInfoIndex::IssueDrawCommandsStart, FrameInfoIndex::SwapBuffers),
-                duration(i, FrameInfoIndex::SwapBuffers, FrameInfoIndex::FrameCompleted));
+                durationMS(i, FrameInfoIndex::IntendedVsync, FrameInfoIndex::SyncStart),
+                durationMS(i, FrameInfoIndex::SyncStart, FrameInfoIndex::IssueDrawCommandsStart),
+                durationMS(i, FrameInfoIndex::IssueDrawCommandsStart, FrameInfoIndex::SwapBuffers),
+                durationMS(i, FrameInfoIndex::SwapBuffers, FrameInfoIndex::FrameCompleted));
     }
 
     fflush(file);
diff --git a/libs/hwui/FrameInfoVisualizer.h b/libs/hwui/FrameInfoVisualizer.h
index f1dc954..cf877c4 100644
--- a/libs/hwui/FrameInfoVisualizer.h
+++ b/libs/hwui/FrameInfoVisualizer.h
@@ -59,10 +59,8 @@
     void drawGraph(OpenGLRenderer* canvas);
     void drawThreshold(OpenGLRenderer* canvas);
 
-    inline float duration(size_t index, FrameInfoIndex start, FrameInfoIndex end) {
-        nsecs_t ns_start = mFrameSource[index][start];
-        nsecs_t ns_end = mFrameSource[index][end];
-        float duration = ((ns_end - ns_start) * 0.000001f);
+    inline float durationMS(size_t index, FrameInfoIndex start, FrameInfoIndex end) {
+        float duration = mFrameSource[index].duration(start, end) * 0.000001f;
         // Clamp to large to avoid spiking off the top of the screen
         duration = duration > 50.0f ? 50.0f : duration;
         return duration > 0.0f ? duration : 0.0f;
diff --git a/libs/hwui/JankTracker.cpp b/libs/hwui/JankTracker.cpp
index 5c0801e..eb9b55f 100644
--- a/libs/hwui/JankTracker.cpp
+++ b/libs/hwui/JankTracker.cpp
@@ -31,7 +31,7 @@
         "High input latency",
         "Slow UI thread",
         "Slow bitmap uploads",
-        "Slow draw",
+        "Slow issue draw commands",
 };
 
 struct Comparison {
@@ -223,7 +223,7 @@
     mData->jankFrameCount++;
 
     for (int i = 0; i < NUM_BUCKETS; i++) {
-        int64_t delta = frame[COMPARISONS[i].end] - frame[COMPARISONS[i].start];
+        int64_t delta = frame.duration(COMPARISONS[i].start, COMPARISONS[i].end);
         if (delta >= mThresholds[i] && delta < IGNORE_EXCEEDING) {
             mData->jankTypeCounts[i]++;
         }
diff --git a/libs/hwui/Matrix.cpp b/libs/hwui/Matrix.cpp
index 061d26a..06e67c0 100644
--- a/libs/hwui/Matrix.cpp
+++ b/libs/hwui/Matrix.cpp
@@ -155,8 +155,7 @@
 }
 
 void Matrix4::load(const Matrix4& v) {
-    memcpy(data, v.data, sizeof(data));
-    mType = v.getType();
+    *this = v;
 }
 
 void Matrix4::load(const SkMatrix& v) {
diff --git a/libs/hwui/Matrix.h b/libs/hwui/Matrix.h
index c152789..ed54a25 100644
--- a/libs/hwui/Matrix.h
+++ b/libs/hwui/Matrix.h
@@ -85,10 +85,6 @@
         load(v);
     }
 
-    Matrix4(const Matrix4& v) {
-        load(v);
-    }
-
     Matrix4(const SkMatrix& v) {
         load(v);
     }
diff --git a/libs/hwui/renderthread/CanvasContext.cpp b/libs/hwui/renderthread/CanvasContext.cpp
index b88f30e..260fb6f 100644
--- a/libs/hwui/renderthread/CanvasContext.cpp
+++ b/libs/hwui/renderthread/CanvasContext.cpp
@@ -160,7 +160,7 @@
     return info && ((*info)[FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame);
 }
 
-void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo) {
+void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo, int64_t syncQueued) {
     mRenderThread.removeFrameCallback(this);
 
     // If the previous frame was dropped we don't need to hold onto it, so
@@ -169,6 +169,7 @@
         mCurrentFrameInfo = &mFrames.next();
     }
     mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo);
+    mCurrentFrameInfo->set(FrameInfoIndex::SyncQueued) = syncQueued;
     mCurrentFrameInfo->markSyncStart();
 
     info.damageAccumulator = &mDamageAccumulator;
@@ -293,7 +294,7 @@
                 mRenderThread.timeLord().latestVsync());
 
     TreeInfo info(TreeInfo::MODE_RT_ONLY, mRenderThread.renderState());
-    prepareTree(info, frameInfo);
+    prepareTree(info, frameInfo, systemTime(CLOCK_MONOTONIC));
     if (info.out.canDrawThisFrame) {
         draw();
     }
diff --git a/libs/hwui/renderthread/CanvasContext.h b/libs/hwui/renderthread/CanvasContext.h
index 10e66e9..f2fa9cd 100644
--- a/libs/hwui/renderthread/CanvasContext.h
+++ b/libs/hwui/renderthread/CanvasContext.h
@@ -78,7 +78,7 @@
     void setOpaque(bool opaque);
     void makeCurrent();
     void processLayerUpdate(DeferredLayerUpdater* layerUpdater);
-    void prepareTree(TreeInfo& info, int64_t* uiFrameInfo);
+    void prepareTree(TreeInfo& info, int64_t* uiFrameInfo, int64_t syncQueued);
     void draw();
     void destroy();
 
diff --git a/libs/hwui/renderthread/DrawFrameTask.cpp b/libs/hwui/renderthread/DrawFrameTask.cpp
index 008e297..6507ce8 100644
--- a/libs/hwui/renderthread/DrawFrameTask.cpp
+++ b/libs/hwui/renderthread/DrawFrameTask.cpp
@@ -69,6 +69,7 @@
     LOG_ALWAYS_FATAL_IF(!mContext, "Cannot drawFrame with no CanvasContext!");
 
     mSyncResult = kSync_OK;
+    mSyncQueued = systemTime(CLOCK_MONOTONIC);
     postAndWait();
 
     return mSyncResult;
@@ -119,7 +120,7 @@
         mContext->processLayerUpdate(mLayers[i].get());
     }
     mLayers.clear();
-    mContext->prepareTree(info, mFrameInfo);
+    mContext->prepareTree(info, mFrameInfo, mSyncQueued);
 
     // This is after the prepareTree so that any pending operations
     // (RenderNode tree state, prefetched layers, etc...) will be flushed.
diff --git a/libs/hwui/renderthread/DrawFrameTask.h b/libs/hwui/renderthread/DrawFrameTask.h
index 8039643..ebefcba 100644
--- a/libs/hwui/renderthread/DrawFrameTask.h
+++ b/libs/hwui/renderthread/DrawFrameTask.h
@@ -85,6 +85,7 @@
     std::vector< sp<DeferredLayerUpdater> > mLayers;
 
     int mSyncResult;
+    int64_t mSyncQueued;
 
     int64_t mFrameInfo[UI_THREAD_FRAME_INFO_SIZE];
 };
diff --git a/libs/hwui/tests/main.cpp b/libs/hwui/tests/main.cpp
index ceee953..80d7029 100644
--- a/libs/hwui/tests/main.cpp
+++ b/libs/hwui/tests/main.cpp
@@ -111,8 +111,6 @@
         for (int i = 0; i < animation.getFrameCount(); i++) {
             testContext.waitForVsync();
 
-            // workaround b/20853441
-            proxy->fence();
             ATRACE_NAME("UI-Draw Frame");
             nsecs_t vsync = systemTime(CLOCK_MONOTONIC);
             UiFrameInfoBuilder(proxy->frameInfo())
diff --git a/media/java/android/media/IRingtonePlayer.aidl b/media/java/android/media/IRingtonePlayer.aidl
index 7c011e6..aa5fde3 100644
--- a/media/java/android/media/IRingtonePlayer.aidl
+++ b/media/java/android/media/IRingtonePlayer.aidl
@@ -25,9 +25,10 @@
  */
 interface IRingtonePlayer {
     /** Used for Ringtone.java playback */
-    void play(IBinder token, in Uri uri, in AudioAttributes aa);
+    void play(IBinder token, in Uri uri, in AudioAttributes aa, float volume, boolean looping);
     void stop(IBinder token);
     boolean isPlaying(IBinder token);
+    void setPlaybackProperties(IBinder token, float volume, boolean looping);
 
     /** Used for Notification sound playback. */
     void playAsync(in Uri uri, in UserHandle user, boolean looping, in AudioAttributes aa);
diff --git a/media/java/android/media/ImageUtils.java b/media/java/android/media/ImageUtils.java
index 2763d1d..ba3949a 100644
--- a/media/java/android/media/ImageUtils.java
+++ b/media/java/android/media/ImageUtils.java
@@ -21,6 +21,8 @@
 import android.media.Image.Plane;
 import android.util.Size;
 
+import libcore.io.Memory;
+
 import java.nio.ByteBuffer;
 
 /**
@@ -109,12 +111,50 @@
         ByteBuffer srcBuffer = null;
         ByteBuffer dstBuffer = null;
         for (int i = 0; i < srcPlanes.length; i++) {
+            int srcRowStride = srcPlanes[i].getRowStride();
+            int dstRowStride = dstPlanes[i].getRowStride();
             srcBuffer = srcPlanes[i].getBuffer();
+            dstBuffer = dstPlanes[i].getBuffer();
+            if (!(srcBuffer.isDirect() && dstBuffer.isDirect())) {
+                throw new IllegalArgumentException("Source and destination ByteBuffers must be"
+                        + " direct byteBuffer!");
+            }
+            if (srcPlanes[i].getPixelStride() != dstPlanes[i].getPixelStride()) {
+                throw new IllegalArgumentException("Source plane image pixel stride " +
+                        srcPlanes[i].getPixelStride() +
+                        " must be same as destination image pixel stride " +
+                        dstPlanes[i].getPixelStride());
+            }
+
             int srcPos = srcBuffer.position();
             srcBuffer.rewind();
-            dstBuffer = dstPlanes[i].getBuffer();
             dstBuffer.rewind();
-            dstBuffer.put(srcBuffer);
+            if (srcRowStride == dstRowStride) {
+                // Fast path, just copy the content if the byteBuffer all together.
+                dstBuffer.put(srcBuffer);
+            } else {
+                // Source and destination images may have different alignment requirements,
+                // therefore may have different strides. Copy row by row for such case.
+                int srcOffset = srcBuffer.position();
+                int dstOffset = dstBuffer.position();
+                Size effectivePlaneSize = getEffectivePlaneSizeForImage(src, i);
+                int srcByteCount = effectivePlaneSize.getWidth() * srcPlanes[i].getPixelStride();
+                for (int row = 0; row < effectivePlaneSize.getHeight(); row++) {
+                    if (row == effectivePlaneSize.getHeight() - 1) {
+                        // Special case for NV21 backed YUV420_888: need handle the last row
+                        // carefully to avoid memory corruption. Check if we have enough bytes to
+                        // copy.
+                        int remainingBytes = srcBuffer.remaining() - srcOffset;
+                        if (srcByteCount > remainingBytes) {
+                            srcByteCount = remainingBytes;
+                        }
+                    }
+                    directByteBufferCopy(srcBuffer, srcOffset, dstBuffer, dstOffset, srcByteCount);
+                    srcOffset += srcRowStride;
+                    dstOffset += dstRowStride;
+                }
+            }
+
             srcBuffer.position(srcPos);
             dstBuffer.rewind();
         }
@@ -175,4 +215,44 @@
 
         return (int)(width * height * estimatedBytePerPixel * numImages);
     }
+
+    private static Size getEffectivePlaneSizeForImage(Image image, int planeIdx) {
+        switch (image.getFormat()) {
+            case ImageFormat.YV12:
+            case ImageFormat.YUV_420_888:
+            case ImageFormat.NV21:
+                if (planeIdx == 0) {
+                    return new Size(image.getWidth(), image.getHeight());
+                } else {
+                    return new Size(image.getWidth() / 2, image.getHeight() / 2);
+                }
+            case ImageFormat.NV16:
+                if (planeIdx == 0) {
+                    return new Size(image.getWidth(), image.getHeight());
+                } else {
+                    return new Size(image.getWidth(), image.getHeight() / 2);
+                }
+            case PixelFormat.RGB_565:
+            case PixelFormat.RGBA_8888:
+            case PixelFormat.RGBX_8888:
+            case PixelFormat.RGB_888:
+            case ImageFormat.JPEG:
+            case ImageFormat.YUY2:
+            case ImageFormat.Y8:
+            case ImageFormat.Y16:
+            case ImageFormat.RAW_SENSOR:
+            case ImageFormat.RAW10:
+                return new Size(image.getWidth(), image.getHeight());
+            case ImageFormat.PRIVATE:
+                return new Size(0, 0);
+            default:
+                throw new UnsupportedOperationException(
+                        String.format("Invalid image format %d", image.getFormat()));
+        }
+    }
+
+    private static void directByteBufferCopy(ByteBuffer srcBuffer, int srcOffset,
+            ByteBuffer dstBuffer, int dstOffset, int srcByteCount) {
+        Memory.memmove(dstBuffer, dstOffset, srcBuffer, srcOffset, srcByteCount);
+    }
 }
diff --git a/media/java/android/media/ImageWriter.java b/media/java/android/media/ImageWriter.java
index 2ef2519..9fb3286 100644
--- a/media/java/android/media/ImageWriter.java
+++ b/media/java/android/media/ImageWriter.java
@@ -40,8 +40,8 @@
  * Several Android API classes can provide input {@link android.view.Surface
  * Surface} objects for ImageWriter to produce data into, including
  * {@link MediaCodec MediaCodec} (encoder),
- * {@link android.hardware.camera2.CameraDevice CameraDevice} (reprocessing
- * input), {@link ImageReader}, etc.
+ * {@link android.hardware.camera2.CameraCaptureSession CameraCaptureSession}
+ * (reprocessing input), {@link ImageReader}, etc.
  * </p>
  * <p>
  * The input Image data is encapsulated in {@link Image} objects. To produce
@@ -64,7 +64,14 @@
  * {@link android.hardware.camera2.CameraDevice}) to consume the Images. If the
  * downstream components cannot consume the Images at least as fast as the
  * ImageWriter production rate, the {@link #dequeueInputImage} call will
- * eventually block and the application will have to drop input frames. </p>
+ * eventually block and the application will have to drop input frames.
+ * </p>
+ * <p>
+ * If the consumer component that provided the input {@link android.view.Surface Surface}
+ * abandons the {@link android.view.Surface Surface}, {@link #queueInputImage queueing}
+ * or {@link #dequeueInputImage dequeueing} an {@link Image} will throw an
+ * {@link IllegalStateException}.
+ * </p>
  */
 public class ImageWriter implements AutoCloseable {
     private final Object mListenerLock = new Object();
@@ -188,7 +195,9 @@
      * @return The next available input Image from this ImageWriter.
      * @throws IllegalStateException if {@code maxImages} Images are currently
      *             dequeued, or the ImageWriter format is
-     *             {@link ImageFormat#PRIVATE PRIVATE}.
+     *             {@link ImageFormat#PRIVATE PRIVATE}, or the input
+     *             {@link android.view.Surface Surface} has been abandoned by the
+     *             consumer component that provided the {@link android.view.Surface Surface}.
      * @see #queueInputImage
      * @see Image#close
      */
@@ -254,6 +263,11 @@
      *
      * @param image The Image to be queued back to ImageWriter for future
      *            consumption.
+     * @throws IllegalStateException if the image was already queued previously,
+     *            or the image was aborted previously, or the input
+     *            {@link android.view.Surface Surface} has been abandoned by the
+     *            consumer component that provided the
+     *            {@link android.view.Surface Surface}.
      * @see #dequeueInputImage()
      */
     public void queueInputImage(Image image) {
@@ -699,7 +713,7 @@
         }
 
         private void clearSurfacePlanes() {
-            if (mIsImageValid) {
+            if (mIsImageValid && mPlanes != null) {
                 for (int i = 0; i < mPlanes.length; i++) {
                     if (mPlanes[i] != null) {
                         mPlanes[i].clearBuffer();
diff --git a/media/java/android/media/MediaCodec.java b/media/java/android/media/MediaCodec.java
index a79dd04..5f60891 100644
--- a/media/java/android/media/MediaCodec.java
+++ b/media/java/android/media/MediaCodec.java
@@ -2029,12 +2029,21 @@
          */
         public static final int ERROR_INSUFFICIENT_OUTPUT_PROTECTION = 4;
 
+        /**
+         * This indicates that decryption was attempted on a session that is
+         * not opened, which could be due to a failure to open the session,
+         * closing the session prematurely, or the session being reclaimed
+         * by the resource manager.
+         */
+        public static final int ERROR_SESSION_NOT_OPENED = 5;
+
         /** @hide */
         @IntDef({
             ERROR_NO_KEY,
             ERROR_KEY_EXPIRED,
             ERROR_RESOURCE_BUSY,
             ERROR_INSUFFICIENT_OUTPUT_PROTECTION,
+            ERROR_SESSION_NOT_OPENED,
         })
         @Retention(RetentionPolicy.SOURCE)
         public @interface CryptoErrorCode {}
diff --git a/media/java/android/media/Ringtone.java b/media/java/android/media/Ringtone.java
index 166ff38..faeebe6 100644
--- a/media/java/android/media/Ringtone.java
+++ b/media/java/android/media/Ringtone.java
@@ -76,6 +76,10 @@
             .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
             .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
             .build();
+    // playback properties, use synchronized with mPlaybackSettingsLock
+    private boolean mIsLooping = false;
+    private float mVolume = 1.0f;
+    private final Object mPlaybackSettingsLock = new Object();
 
     /** {@hide} */
     public Ringtone(Context context, boolean allowRemote) {
@@ -136,6 +140,52 @@
     }
 
     /**
+     * @hide
+     * Sets the player to be looping or non-looping.
+     * @param looping whether to loop or not
+     */
+    public void setLooping(boolean looping) {
+        synchronized (mPlaybackSettingsLock) {
+            mIsLooping = looping;
+            applyPlaybackProperties_sync();
+        }
+    }
+
+    /**
+     * @hide
+     * Sets the volume on this player.
+     * @param volume a raw scalar in range 0.0 to 1.0, where 0.0 mutes this player, and 1.0
+     *   corresponds to no attenuation being applied.
+     */
+    public void setVolume(float volume) {
+        synchronized (mPlaybackSettingsLock) {
+            if (volume < 0.0f) { volume = 0.0f; }
+            if (volume > 1.0f) { volume = 1.0f; }
+            mVolume = volume;
+            applyPlaybackProperties_sync();
+        }
+    }
+
+    /**
+     * Must be called synchronized on mPlaybackSettingsLock
+     */
+    private void applyPlaybackProperties_sync() {
+        if (mLocalPlayer != null) {
+            mLocalPlayer.setVolume(mVolume);
+            mLocalPlayer.setLooping(mIsLooping);
+        } else if (mAllowRemote && (mRemotePlayer != null)) {
+            try {
+                mRemotePlayer.setPlaybackProperties(mRemoteToken, mVolume, mIsLooping);
+            } catch (RemoteException e) {
+                Log.w(TAG, "Problem setting playback properties: ", e);
+            }
+        } else {
+            Log.w(TAG,
+                    "Neither local nor remote player available when applying playback properties");
+        }
+    }
+
+    /**
      * Returns a human-presentable title for ringtone. Looks in media
      * content provider. If not in either, uses the filename
      * 
@@ -221,6 +271,9 @@
         try {
             mLocalPlayer.setDataSource(mContext, mUri);
             mLocalPlayer.setAudioAttributes(mAudioAttributes);
+            synchronized (mPlaybackSettingsLock) {
+                applyPlaybackProperties_sync();
+            }
             mLocalPlayer.prepare();
 
         } catch (SecurityException | IOException e) {
@@ -257,8 +310,14 @@
             }
         } else if (mAllowRemote && (mRemotePlayer != null)) {
             final Uri canonicalUri = mUri.getCanonicalUri();
+            final boolean looping;
+            final float volume;
+            synchronized (mPlaybackSettingsLock) {
+                looping = mIsLooping;
+                volume = mVolume;
+            }
             try {
-                mRemotePlayer.play(mRemoteToken, canonicalUri, mAudioAttributes);
+                mRemotePlayer.play(mRemoteToken, canonicalUri, mAudioAttributes, volume, looping);
             } catch (RemoteException e) {
                 if (!playFallbackRingtone()) {
                     Log.w(TAG, "Problem playing ringtone: " + e);
@@ -349,6 +408,9 @@
                                     afd.getDeclaredLength());
                         }
                         mLocalPlayer.setAudioAttributes(mAudioAttributes);
+                        synchronized (mPlaybackSettingsLock) {
+                            applyPlaybackProperties_sync();
+                        }
                         mLocalPlayer.prepare();
                         startLocalPlayer();
                         afd.close();
diff --git a/media/java/android/media/session/MediaSessionManager.java b/media/java/android/media/session/MediaSessionManager.java
index 6ac0efb..2364a13 100644
--- a/media/java/android/media/session/MediaSessionManager.java
+++ b/media/java/android/media/session/MediaSessionManager.java
@@ -202,7 +202,8 @@
                 Log.w(TAG, "Attempted to add session listener twice, ignoring.");
                 return;
             }
-            SessionsChangedWrapper wrapper = new SessionsChangedWrapper(sessionListener, handler);
+            SessionsChangedWrapper wrapper = new SessionsChangedWrapper(mContext, sessionListener,
+                    handler);
             try {
                 mService.addSessionsListener(wrapper.mStub, notificationListener, userId);
                 mListeners.put(sessionListener, wrapper);
@@ -229,6 +230,8 @@
                     mService.removeSessionsListener(wrapper.mStub);
                 } catch (RemoteException e) {
                     Log.e(TAG, "Error in removeOnActiveSessionsChangedListener.", e);
+                } finally {
+                    wrapper.release();
                 }
             }
         }
@@ -317,11 +320,14 @@
         public void onActiveSessionsChanged(@Nullable List<MediaController> controllers);
     }
 
-    private final class SessionsChangedWrapper {
-        private final OnActiveSessionsChangedListener mListener;
-        private final Handler mHandler;
+    private static final class SessionsChangedWrapper {
+        private Context mContext;
+        private OnActiveSessionsChangedListener mListener;
+        private Handler mHandler;
 
-        public SessionsChangedWrapper(OnActiveSessionsChangedListener listener, Handler handler) {
+        public SessionsChangedWrapper(Context context, OnActiveSessionsChangedListener listener,
+                Handler handler) {
+            mContext = context;
             mListener = listener;
             mHandler = handler;
         }
@@ -333,17 +339,25 @@
                     mHandler.post(new Runnable() {
                         @Override
                         public void run() {
-                            ArrayList<MediaController> controllers
-                                    = new ArrayList<MediaController>();
-                            int size = tokens.size();
-                            for (int i = 0; i < size; i++) {
-                                controllers.add(new MediaController(mContext, tokens.get(i)));
+                            if (mListener != null) {
+                                ArrayList<MediaController> controllers
+                                        = new ArrayList<MediaController>();
+                                int size = tokens.size();
+                                for (int i = 0; i < size; i++) {
+                                    controllers.add(new MediaController(mContext, tokens.get(i)));
+                                }
+                                mListener.onActiveSessionsChanged(controllers);
                             }
-                            mListener.onActiveSessionsChanged(controllers);
                         }
                     });
                 }
             }
         };
+
+        private void release() {
+            mContext = null;
+            mListener = null;
+            mHandler = null;
+        }
     }
 }
diff --git a/media/jni/android_media_ImageWriter.cpp b/media/jni/android_media_ImageWriter.cpp
index ba7634c..f92a8ef 100644
--- a/media/jni/android_media_ImageWriter.cpp
+++ b/media/jni/android_media_ImageWriter.cpp
@@ -338,9 +338,16 @@
     int fenceFd = -1;
     status_t res = anw->dequeueBuffer(anw.get(), &anb, &fenceFd);
     if (res != OK) {
-        // TODO: handle different error cases here.
         ALOGE("%s: Dequeue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
-        jniThrowRuntimeException(env, "dequeue buffer failed");
+        switch (res) {
+            case NO_INIT:
+                jniThrowException(env, "java/lang/IllegalStateException",
+                    "Surface has been abandoned");
+                break;
+            default:
+                // TODO: handle other error cases here.
+                jniThrowRuntimeException(env, "dequeue buffer failed");
+        }
         return;
     }
     // New GraphicBuffer object doesn't own the handle, thus the native buffer
@@ -468,7 +475,16 @@
     // Finally, queue input buffer
     res = anw->queueBuffer(anw.get(), buffer, fenceFd);
     if (res != OK) {
-        jniThrowRuntimeException(env, "Queue input buffer failed");
+        ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
+        switch (res) {
+            case NO_INIT:
+                jniThrowException(env, "java/lang/IllegalStateException",
+                    "Surface has been abandoned");
+                break;
+            default:
+                // TODO: handle other error cases here.
+                jniThrowRuntimeException(env, "Queue input buffer failed");
+        }
         return;
     }
 
@@ -514,9 +530,16 @@
     // Step 1. Attach Image
     res = surface->attachBuffer(opaqueBuffer->mGraphicBuffer.get());
     if (res != OK) {
-        // TODO: handle different error case separately.
         ALOGE("Attach image failed: %s (%d)", strerror(-res), res);
-        jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
+        switch (res) {
+            case NO_INIT:
+                jniThrowException(env, "java/lang/IllegalStateException",
+                    "Surface has been abandoned");
+                break;
+            default:
+                // TODO: handle other error cases here.
+                jniThrowRuntimeException(env, "nativeAttachImage failed!!!");
+        }
         return res;
     }
     sp < ANativeWindow > anw = surface;
@@ -545,7 +568,16 @@
     res = anw->queueBuffer(anw.get(), opaqueBuffer->mGraphicBuffer.get(), /*fenceFd*/
             -1);
     if (res != OK) {
-        jniThrowRuntimeException(env, "Queue input buffer failed");
+        ALOGE("%s: Queue buffer failed: %s (%d)", __FUNCTION__, strerror(-res), res);
+        switch (res) {
+            case NO_INIT:
+                jniThrowException(env, "java/lang/IllegalStateException",
+                    "Surface has been abandoned");
+                break;
+            default:
+                // TODO: handle other error cases here.
+                jniThrowRuntimeException(env, "Queue input buffer failed");
+        }
         return res;
     }
 
diff --git a/media/jni/android_media_MediaCodec.cpp b/media/jni/android_media_MediaCodec.cpp
index ce7f7e5..218a117 100644
--- a/media/jni/android_media_MediaCodec.cpp
+++ b/media/jni/android_media_MediaCodec.cpp
@@ -64,6 +64,7 @@
     jint cryptoErrorKeyExpired;
     jint cryptoErrorResourceBusy;
     jint cryptoErrorInsufficientOutputProtection;
+    jint cryptoErrorSessionNotOpened;
 } gCryptoErrorCodes;
 
 static struct CodecActionCodes {
@@ -843,6 +844,9 @@
         case ERROR_DRM_INSUFFICIENT_OUTPUT_PROTECTION:
             err = gCryptoErrorCodes.cryptoErrorInsufficientOutputProtection;
             break;
+        case ERROR_DRM_SESSION_NOT_OPENED:
+            err = gCryptoErrorCodes.cryptoErrorSessionNotOpened;
+            break;
         default:  /* Other negative DRM error codes go out as is. */
             break;
     }
@@ -1689,6 +1693,11 @@
     gCryptoErrorCodes.cryptoErrorInsufficientOutputProtection =
         env->GetStaticIntField(clazz.get(), field);
 
+    field = env->GetStaticFieldID(clazz.get(), "ERROR_SESSION_NOT_OPENED", "I");
+    CHECK(field != NULL);
+    gCryptoErrorCodes.cryptoErrorSessionNotOpened =
+        env->GetStaticIntField(clazz.get(), field);
+
     clazz.reset(env->FindClass("android/media/MediaCodec$CodecException"));
     CHECK(clazz.get() != NULL);
     field = env->GetStaticFieldID(clazz.get(), "ACTION_TRANSIENT", "I");
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 41043eb..8d9f3fd 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -1774,6 +1774,26 @@
             Uri uri = getNotificationUriFor(key, name);
 
             sendNotify(uri, userId);
+            if (isSecureSettingsKey(key)) {
+                maybeNotifyProfiles(userId, uri, name, sSecureCloneToManagedSettings);
+            } else if (isSystemSettingsKey(key)) {
+                maybeNotifyProfiles(userId, uri, name, sSystemCloneToManagedSettings);
+            }
+        }
+
+        private void maybeNotifyProfiles(int userId, Uri uri, String name,
+                Set<String> keysCloned) {
+            if (keysCloned.contains(name)) {
+                List<UserInfo> profiles = mUserManager.getProfiles(userId);
+                int size = profiles.size();
+                for (int i = 0; i < size; i++) {
+                    UserInfo profile = profiles.get(i);
+                    // the notification for userId has already been sent.
+                    if (profile.id != userId) {
+                        sendNotify(uri, profile.id);
+                    }
+                }
+            }
         }
 
         private int makeKey(int type, int userId) {
diff --git a/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java b/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
index 7eed7f2..e9a256c 100644
--- a/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
+++ b/packages/SystemUI/src/com/android/systemui/media/RingtonePlayer.java
@@ -92,7 +92,8 @@
 
     private IRingtonePlayer mCallback = new IRingtonePlayer.Stub() {
         @Override
-        public void play(IBinder token, Uri uri, AudioAttributes aa) throws RemoteException {
+        public void play(IBinder token, Uri uri, AudioAttributes aa, float volume, boolean looping)
+                throws RemoteException {
             if (LOGD) {
                 Log.d(TAG, "play(token=" + token + ", uri=" + uri + ", uid="
                         + Binder.getCallingUid() + ")");
@@ -107,6 +108,8 @@
                     mClients.put(token, client);
                 }
             }
+            client.mRingtone.setLooping(looping);
+            client.mRingtone.setVolume(volume);
             client.mRingtone.play();
         }
 
@@ -138,6 +141,19 @@
         }
 
         @Override
+        public void setPlaybackProperties(IBinder token, float volume, boolean looping) {
+            Client client;
+            synchronized (mClients) {
+                client = mClients.get(token);
+            }
+            if (client != null) {
+                client.mRingtone.setVolume(volume);
+                client.mRingtone.setLooping(looping);
+            }
+            // else no client for token when setting playback properties but will be set at play()
+        }
+
+        @Override
         public void playAsync(Uri uri, UserHandle user, boolean looping, AudioAttributes aa) {
             if (LOGD) Log.d(TAG, "playAsync(uri=" + uri + ", user=" + user + ")");
             if (Binder.getCallingUid() != Process.SYSTEM_UID) {
diff --git a/packages/SystemUI/src/com/android/systemui/recents/Constants.java b/packages/SystemUI/src/com/android/systemui/recents/Constants.java
index 18c213d..a4acf83 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/Constants.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/Constants.java
@@ -20,6 +20,14 @@
  * Constants
  */
 public class Constants {
+
+    public static class Metrics {
+        // DO NOT MODIFY THE ORDER OF THESE METRICS
+        public static final int DismissSourceKeyboard = 0;
+        public static final int DismissSourceSwipeGesture = 1;
+        public static final int DismissSourceHeaderButton = 2;
+    }
+
     public static class DebugFlags {
         // Enable this with any other debug flag to see more info
         public static final boolean Verbose = false;
diff --git a/packages/SystemUI/src/com/android/systemui/recents/Recents.java b/packages/SystemUI/src/com/android/systemui/recents/Recents.java
index 6a45369..8c2ac88 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/Recents.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/Recents.java
@@ -39,6 +39,8 @@
 import android.view.Display;
 import android.view.LayoutInflater;
 import android.view.View;
+
+import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.Prefs;
 import com.android.systemui.R;
 import com.android.systemui.RecentsComponent;
@@ -453,6 +455,9 @@
             return;
         }
 
+        // Keep track of actually launched affiliated tasks
+        MetricsLogger.count(mContext, "overview_affiliated_task_launch", 1);
+
         // Launch the task
         if (toTask.isActive) {
             // Bring an active task to the foreground
@@ -465,11 +470,15 @@
 
     @Override
     public void showNextAffiliatedTask() {
+        // Keep track of when the affiliated task is triggered
+        MetricsLogger.count(mContext, "overview_affiliated_task_next", 1);
         showRelativeAffiliatedTask(true);
     }
 
     @Override
     public void showPrevAffiliatedTask() {
+        // Keep track of when the affiliated task is triggered
+        MetricsLogger.count(mContext, "overview_affiliated_task_prev", 1);
         showRelativeAffiliatedTask(false);
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java b/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java
index bf15c68..789457da 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java
@@ -33,6 +33,8 @@
 import android.view.ViewStub;
 import android.widget.Toast;
 
+import com.android.internal.logging.MetricsConstants;
+import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.Prefs;
 import com.android.systemui.R;
 import com.android.systemui.recents.misc.Console;
@@ -224,6 +226,7 @@
 
         // Mark the task that is the launch target
         int taskStackCount = stacks.size();
+        int launchTaskIndexInStack = 0;
         if (mConfig.launchedToTaskId != -1) {
             for (int i = 0; i < taskStackCount; i++) {
                 TaskStack stack = stacks.get(i);
@@ -233,6 +236,7 @@
                     Task t = tasks.get(j);
                     if (t.key.id == mConfig.launchedToTaskId) {
                         t.isLaunchTarget = true;
+                        launchTaskIndexInStack = tasks.size() - j - 1;
                         break;
                     }
                 }
@@ -259,6 +263,28 @@
 
         // Animate the SystemUI scrims into view
         mScrimViews.prepareEnterRecentsAnimation();
+
+        // Keep track of whether we launched from the nav bar button or via alt-tab
+        if (mConfig.launchedWithAltTab) {
+            MetricsLogger.count(this, "overview_trigger_alttab", 1);
+        } else {
+            MetricsLogger.count(this, "overview_trigger_nav_btn", 1);
+        }
+        // Keep track of whether we launched from an app or from home
+        if (mConfig.launchedFromAppWithThumbnail) {
+            MetricsLogger.count(this, "overview_source_app", 1);
+            // If from an app, track the stack index of the app in the stack (for affiliated tasks)
+            MetricsLogger.histogram(this, "overview_source_app_index", launchTaskIndexInStack);
+        } else {
+            MetricsLogger.count(this, "overview_source_home", 1);
+        }
+        // Keep track of the total stack task count
+        int taskCount = 0;
+        for (int i = 0; i < stacks.size(); i++) {
+            TaskStack stack = stacks.get(i);
+            taskCount += stack.getTaskCount();
+        }
+        MetricsLogger.histogram(this, "overview_task_count", taskCount);
     }
 
     /** Dismisses recents if we are already visible and the intent is to toggle the recents view */
@@ -374,6 +400,7 @@
     @Override
     protected void onStart() {
         super.onStart();
+        MetricsLogger.visible(this, MetricsLogger.OVERVIEW_ACTIVITY);
         RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
         SystemServicesProxy ssp = loader.getSystemServicesProxy();
         Recents.notifyVisibilityChanged(this, ssp, true);
@@ -414,6 +441,7 @@
     @Override
     protected void onStop() {
         super.onStop();
+        MetricsLogger.hidden(this, MetricsLogger.OVERVIEW_ACTIVITY);
         RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
         SystemServicesProxy ssp = loader.getSystemServicesProxy();
         Recents.notifyVisibilityChanged(this, ssp, false);
@@ -498,6 +526,9 @@
             case KeyEvent.KEYCODE_DEL:
             case KeyEvent.KEYCODE_FORWARD_DEL: {
                 mRecentsView.dismissFocusedTask();
+                // Keep track of deletions by keyboard
+                MetricsLogger.histogram(this, "overview_task_dismissed_source",
+                        Constants.Metrics.DismissSourceKeyboard);
                 return true;
             }
             default:
@@ -591,6 +622,8 @@
         RecentsTaskLoader loader = RecentsTaskLoader.getInstance();
         SystemServicesProxy ssp = loader.getSystemServicesProxy();
         Recents.startScreenPinning(this, ssp);
+
+        MetricsLogger.count(this, "overview_screen_pinned", 1);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java b/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java
index 6cb11b1..947c19c 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java
@@ -37,6 +37,7 @@
 import android.view.WindowManagerGlobal;
 import android.widget.FrameLayout;
 
+import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.R;
 import com.android.systemui.recents.Constants;
 import com.android.systemui.recents.RecentsAppWidgetHostView;
@@ -589,11 +590,22 @@
                         if (mCb != null) {
                             mCb.onTaskLaunchFailed();
                         }
+
+                        // Keep track of failed launches
+                        MetricsLogger.count(getContext(), "overview_task_launch_failed", 1);
                     }
                 }
             }
         };
 
+        // Keep track of the index of the task launch
+        int taskIndexFromFront = 0;
+        int taskIndex = stack.indexOfTask(task);
+        if (taskIndex > -1) {
+            taskIndexFromFront = stack.getTaskCount() - taskIndex - 1;
+        }
+        MetricsLogger.histogram(getContext(), "overview_task_launch_index", taskIndexFromFront);
+
         // Launch the app right away if there is no task view, otherwise, animate the icon out first
         if (tv == null) {
             launchRunnable.run();
@@ -644,6 +656,9 @@
         }
 
         mCb.onAllTaskViewsDismissed();
+
+        // Keep track of all-deletions
+        MetricsLogger.count(getContext(), "overview_task_all_dismissed", 1);
     }
 
     /** Final callback after Recents is finally hidden. */
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java
index ebfc796..abdebf3 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java
@@ -29,6 +29,8 @@
 import android.view.accessibility.AccessibilityEvent;
 import android.view.accessibility.AccessibilityNodeInfo;
 import android.widget.FrameLayout;
+
+import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.R;
 import com.android.systemui.recents.Constants;
 import com.android.systemui.recents.RecentsConfiguration;
@@ -1361,6 +1363,9 @@
     public void onTaskViewAppInfoClicked(TaskView tv) {
         if (mCb != null) {
             mCb.onTaskViewAppInfoClicked(tv.getTask());
+
+            // Keep track of app-info invocations
+            MetricsLogger.count(getContext(), "overview_app_info", 1);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackViewTouchHandler.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackViewTouchHandler.java
index 13bdbd2..78b3512 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackViewTouchHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackViewTouchHandler.java
@@ -23,6 +23,7 @@
 import android.view.View;
 import android.view.ViewConfiguration;
 import android.view.ViewParent;
+import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.recents.Constants;
 import com.android.systemui.recents.Recents;
 import com.android.systemui.recents.RecentsConfiguration;
@@ -452,6 +453,9 @@
         tv.setTouchEnabled(true);
         // Remove the task view from the stack
         mSv.onTaskViewDismissed(tv);
+        // Keep track of deletions by keyboard
+        MetricsLogger.histogram(tv.getContext(), "overview_task_dismissed_source",
+                Constants.Metrics.DismissSourceSwipeGesture);
     }
 
     @Override
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskView.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskView.java
index 5906ef1..cbfe842 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskView.java
@@ -27,6 +27,7 @@
 import android.view.ViewOutlineProvider;
 import android.view.animation.AccelerateInterpolator;
 import android.widget.FrameLayout;
+import com.android.internal.logging.MetricsLogger;
 import com.android.systemui.R;
 import com.android.systemui.recents.Constants;
 import com.android.systemui.recents.RecentsConfiguration;
@@ -741,6 +742,9 @@
                         }
                     } else if (v == mHeaderView.mDismissButton) {
                         dismissTask();
+                        // Keep track of deletions by the dismiss button
+                        MetricsLogger.histogram(getContext(), "overview_task_dismissed_source",
+                                Constants.Metrics.DismissSourceHeaderButton);
                     } else if (v == mHeaderView.mMoveTaskButton) {
                         if (mCb != null) {
                             mCb.onTaskResize(tv);
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 0877ff9..6670ae0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardAffordanceHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardAffordanceHelper.java
@@ -68,25 +68,11 @@
     private View mTargetedView;
     private boolean mTouchSlopExeeded;
     private AnimatorListenerAdapter mFlingEndListener = new AnimatorListenerAdapter() {
-        public boolean mCancelled;
-
         @Override
         public void onAnimationEnd(Animator animation) {
             mSwipeAnimator = null;
             mSwipingInProgress = false;
-            if (!mCancelled) {
-                mTargetedView = null;
-            }
-        }
-
-        @Override
-        public void onAnimationCancel(Animator animation) {
-            mCancelled = true;
-        }
-
-        @Override
-        public void onAnimationStart(Animator animation) {
-            mCancelled = false;
+            mTargetedView = null;
         }
     };
     private Runnable mAnimationEndRunnable = new Runnable() {
@@ -290,7 +276,6 @@
      * Phase 2: Move back.
      */
     private void startUnlockHintAnimationPhase2(boolean right, final Runnable onFinishedListener) {
-        final KeyguardAffordanceView targetView = right ? mRightIcon : mLeftIcon;
         ValueAnimator animator = getAnimatorToRadius(right, 0);
         animator.addListener(new AnimatorListenerAdapter() {
             @Override
@@ -513,9 +498,7 @@
     }
 
     public void reset(boolean animate) {
-        if (mSwipeAnimator != null) {
-            mSwipeAnimator.cancel();
-        }
+        cancelAnimation();
         setTranslation(0.0f, true, animate);
         mMotionCancelled = true;
         if (mSwipingInProgress) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationGroupManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationGroupManager.java
index 7072dcb..950b162 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationGroupManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationGroupManager.java
@@ -25,8 +25,6 @@
 
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
 
 /**
  * A class to handle notifications and their corresponding groups.
@@ -143,7 +141,7 @@
             return true;
         }
         NotificationGroup group = mGroupMap.get(sbn.getGroupKey());
-        if (group != null && group.expanded) {
+        if (group != null && (group.expanded || group.summary == null)) {
             return true;
         }
         return false;
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 a637e24..20f4dc7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -2914,6 +2914,7 @@
         updateRowStates();
         mIconController.updateResources();
         mScreenPinningRequest.onConfigurationChanged();
+        mNetworkController.handleConfigurationChanged();
     }
 
     @Override
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 ff0e8a3..24e3c78 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
@@ -340,7 +340,6 @@
                 action.equals(ConnectivityManager.INET_CONDITION_ACTION)) {
             updateConnectivity();
         } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
-            mConfig = Config.readConfig(mContext);
             handleConfigurationChanged();
         } else if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
             refreshLocale();
@@ -374,8 +373,8 @@
         }
     }
 
-    @VisibleForTesting
-    void handleConfigurationChanged() {
+    public void handleConfigurationChanged() {
+        mConfig = Config.readConfig(mContext);
         for (MobileSignalController mobileSignalController : mMobileSignalControllers.values()) {
             mobileSignalController.setConfiguration(mConfig);
         }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
index 7040864..bde07de 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
@@ -1764,6 +1764,7 @@
     }
 
     private void onViewAddedInternal(View child) {
+        updateHideSensitiveForChild(child);
         mStackScrollAlgorithm.notifyChildrenChanged(this);
         ((ExpandableView) child).setOnHeightChangedListener(this);
         generateAddAnimation(child, false /* fromMoreCard */);
@@ -1776,6 +1777,13 @@
         }
     }
 
+    private void updateHideSensitiveForChild(View child) {
+        if (mAmbientState.isHideSensitive() && child instanceof ExpandableView) {
+            ExpandableView expandableView = (ExpandableView) child;
+            expandableView.setHideSensitiveForIntrinsicHeight(true);
+        }
+    }
+
     public void notifyGroupChildRemoved(View row) {
         onViewRemovedInternal(row);
     }
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialog.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialog.java
index 3964820..a4ccfd1 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialog.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialog.java
@@ -462,6 +462,9 @@
     }
 
     protected void dismissH(int reason) {
+        if (mMotion.isAnimating()) {
+            return;
+        }
         mHandler.removeMessages(H.DISMISS);
         mHandler.removeMessages(H.SHOW);
         if (!mShowing) return;
diff --git a/services/backup/java/com/android/server/backup/BackupManagerService.java b/services/backup/java/com/android/server/backup/BackupManagerService.java
index ed48f91..bf41f0f 100644
--- a/services/backup/java/com/android/server/backup/BackupManagerService.java
+++ b/services/backup/java/com/android/server/backup/BackupManagerService.java
@@ -7514,7 +7514,10 @@
                 // of it is process-local and therefore synchronous.  That means that the
                 // next-state message (RUNNING_QUEUE) is already enqueued.  Only if we're
                 // unable to proceed with running the queue do we remove that pending
-                // message and jump straight to the FINAL state.
+                // message and jump straight to the FINAL state.  Because this was
+                // synchronous we also know that we should cancel the pending timeout
+                // message.
+                mBackupHandler.removeMessages(MSG_TIMEOUT);
 
                 // Verify that the backup set includes metadata.  If not, we can't do
                 // signature/version verification etc, so we simply do not proceed with
diff --git a/services/core/java/com/android/server/DeviceIdleController.java b/services/core/java/com/android/server/DeviceIdleController.java
index c8dc565..fde1490 100644
--- a/services/core/java/com/android/server/DeviceIdleController.java
+++ b/services/core/java/com/android/server/DeviceIdleController.java
@@ -1236,6 +1236,8 @@
         pw.println("    Re-enable device idle mode after it had previously been disabled.");
         pw.println("  enabled");
         pw.println("    Print 1 if device idle mode is currently enabled, else 0.");
+        pw.println("  whitelist");
+        pw.println("    Print currently whitelisted apps.");
         pw.println("  whitelist [package ...]");
         pw.println("    Add (prefix with +) or remove (prefix with -) packages.");
         pw.println("  tempwhitelist [package ..]");
@@ -1314,25 +1316,42 @@
                     long token = Binder.clearCallingIdentity();
                     try {
                         i++;
-                        while (i < args.length) {
-                            arg = args[i];
-                            i++;
-                            if (arg.length() < 1 || (arg.charAt(0) != '-'
-                                    && arg.charAt(0) != '+')) {
-                                pw.println("Package must be prefixed with + or -: " + arg);
-                                return;
-                            }
-                            char op = arg.charAt(0);
-                            String pkg = arg.substring(1);
-                            if (op == '+') {
-                                if (addPowerSaveWhitelistAppInternal(pkg)) {
-                                    pw.println("Added: " + pkg);
-                                } else {
-                                    pw.println("Unknown package: " + pkg);
+                        if (i < args.length) {
+                            while (i < args.length) {
+                                arg = args[i];
+                                i++;
+                                if (arg.length() < 1 || (arg.charAt(0) != '-'
+                                        && arg.charAt(0) != '+')) {
+                                    pw.println("Package must be prefixed with + or -: " + arg);
+                                    return;
                                 }
-                            } else {
-                                if (removePowerSaveWhitelistAppInternal(pkg)) {
-                                    pw.println("Removed: " + pkg);
+                                char op = arg.charAt(0);
+                                String pkg = arg.substring(1);
+                                if (op == '+') {
+                                    if (addPowerSaveWhitelistAppInternal(pkg)) {
+                                        pw.println("Added: " + pkg);
+                                    } else {
+                                        pw.println("Unknown package: " + pkg);
+                                    }
+                                } else {
+                                    if (removePowerSaveWhitelistAppInternal(pkg)) {
+                                        pw.println("Removed: " + pkg);
+                                    }
+                                }
+                            }
+                        } else {
+                            synchronized (this) {
+                                for (int j=0; j<mPowerSaveWhitelistApps.size(); j++) {
+                                    pw.print("system,");
+                                    pw.print(mPowerSaveWhitelistApps.keyAt(j));
+                                    pw.print(",");
+                                    pw.println(mPowerSaveWhitelistApps.valueAt(j));
+                                }
+                                for (int j=0; j<mPowerSaveWhitelistUserApps.size(); j++) {
+                                    pw.print("user,");
+                                    pw.print(mPowerSaveWhitelistUserApps.keyAt(j));
+                                    pw.print(",");
+                                    pw.println(mPowerSaveWhitelistUserApps.valueAt(j));
                                 }
                             }
                         }
diff --git a/services/core/java/com/android/server/NetworkManagementService.java b/services/core/java/com/android/server/NetworkManagementService.java
index 7afb192..0e3134d 100644
--- a/services/core/java/com/android/server/NetworkManagementService.java
+++ b/services/core/java/com/android/server/NetworkManagementService.java
@@ -1473,7 +1473,6 @@
             WifiConfiguration wifiConfig, String wlanIface) {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
         try {
-            wifiFirmwareReload(wlanIface, "AP");
             if (wifiConfig == null) {
                 mConnector.execute("softap", "set", wlanIface);
             } else {
diff --git a/services/core/java/com/android/server/am/BatteryStatsService.java b/services/core/java/com/android/server/am/BatteryStatsService.java
index 6cc1b11..ab47f76 100644
--- a/services/core/java/com/android/server/am/BatteryStatsService.java
+++ b/services/core/java/com/android/server/am/BatteryStatsService.java
@@ -41,6 +41,7 @@
 import android.telephony.DataConnectionRealTimeInfo;
 import android.telephony.SignalStrength;
 import android.telephony.TelephonyManager;
+import android.util.IntArray;
 import android.util.Slog;
 
 import android.util.TimeUtils;
@@ -82,6 +83,7 @@
         public static final int MSG_SYNC_EXTERNAL_STATS = 1;
         public static final int MSG_WRITE_TO_DISK = 2;
         private int mUpdateFlags = 0;
+        private IntArray mUidsToRemove = new IntArray();
 
         public BatteryStatsHandler(Looper looper) {
             super(looper);
@@ -98,6 +100,15 @@
                         mUpdateFlags = 0;
                     }
                     updateExternalStats((String)msg.obj, updateFlags);
+                    synchronized (this) {
+                        synchronized (mStats) {
+                            final int numUidsToRemove = mUidsToRemove.size();
+                            for (int i = 0; i < numUidsToRemove; i++) {
+                                mStats.removeIsolatedUidLocked(mUidsToRemove.get(i));
+                            }
+                        }
+                        mUidsToRemove.clear();
+                    }
                     break;
 
                 case MSG_WRITE_TO_DISK:
@@ -111,22 +122,32 @@
 
         @Override
         public void scheduleSync(String reason) {
-            scheduleSyncImpl(reason, UPDATE_ALL);
+            synchronized (this) {
+                scheduleSyncLocked(reason, UPDATE_ALL);
+            }
         }
 
         @Override
         public void scheduleWifiSync(String reason) {
-            scheduleSyncImpl(reason, UPDATE_WIFI);
+            synchronized (this) {
+                scheduleSyncLocked(reason, UPDATE_WIFI);
+            }
         }
 
-        private void scheduleSyncImpl(String reason, int updateFlags) {
+        @Override
+        public void scheduleCpuSyncDueToRemovedUid(int uid) {
             synchronized (this) {
-                if (mUpdateFlags == 0) {
-                    sendMessage(Message.obtain(this, MSG_SYNC_EXTERNAL_STATS, reason));
-                }
-                mUpdateFlags |= updateFlags;
+                scheduleSyncLocked("remove-uid", UPDATE_CPU);
+                mUidsToRemove.add(uid);
             }
         }
+
+        private void scheduleSyncLocked(String reason, int updateFlags) {
+            if (mUpdateFlags == 0) {
+                sendMessage(Message.obtain(this, MSG_SYNC_EXTERNAL_STATS, reason));
+            }
+            mUpdateFlags |= updateFlags;
+        }
     }
 
     BatteryStatsService(File systemDir, Handler handler) {
@@ -220,7 +241,7 @@
 
     void removeIsolatedUid(int isolatedUid, int appUid) {
         synchronized (mStats) {
-            mStats.removeIsolatedUidLocked(isolatedUid, appUid);
+            mStats.scheduleRemoveIsolatedUidLocked(isolatedUid, appUid);
         }
     }
 
diff --git a/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java
index 453f123..d3ee22a 100644
--- a/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/DefaultPermissionGrantPolicy.java
@@ -429,6 +429,8 @@
             if (contactsProviderPackage != null) {
                 grantRuntimePermissionsLPw(contactsProviderPackage, CONTACTS_PERMISSIONS,
                         true, userId);
+                grantRuntimePermissionsLPw(contactsProviderPackage, PHONE_PERMISSIONS,
+                        true, userId);
                 grantRuntimePermissionsLPw(contactsProviderPackage, ACCOUNTS_PERMISSIONS, userId);
                 grantRuntimePermissionsLPw(contactsProviderPackage, STORAGE_PERMISSIONS, userId);
             }
diff --git a/services/core/java/com/android/server/pm/Installer.java b/services/core/java/com/android/server/pm/Installer.java
index 8dc4bd3..b59b4b2 100644
--- a/services/core/java/com/android/server/pm/Installer.java
+++ b/services/core/java/com/android/server/pm/Installer.java
@@ -264,9 +264,9 @@
         return mInstaller.execute(builder.toString());
     }
 
-    public int moveCompleteApp(String fromUuid, String toUuid, String packageName,
+    public int copyCompleteApp(String fromUuid, String toUuid, String packageName,
             String dataAppName, int appId, String seinfo) {
-        StringBuilder builder = new StringBuilder("mvcompleteapp");
+        StringBuilder builder = new StringBuilder("cpcompleteapp");
         builder.append(' ');
         builder.append(escapeNull(fromUuid));
         builder.append(' ');
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 0240dbb..8fbdfca 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -11278,7 +11278,7 @@
             if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
                     + move.fromUuid + " to " + move.toUuid);
             synchronized (mInstaller) {
-                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
+                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
                         move.dataAppName, move.appId, move.seinfo) != 0) {
                     return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
                 }
@@ -11293,14 +11293,14 @@
 
         int doPreInstall(int status) {
             if (status != PackageManager.INSTALL_SUCCEEDED) {
-                cleanUp();
+                cleanUp(move.toUuid);
             }
             return status;
         }
 
         boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
             if (status != PackageManager.INSTALL_SUCCEEDED) {
-                cleanUp();
+                cleanUp(move.toUuid);
                 return false;
             }
 
@@ -11317,8 +11317,10 @@
         }
 
         int doPostInstall(int status, int uid) {
-            if (status != PackageManager.INSTALL_SUCCEEDED) {
-                cleanUp();
+            if (status == PackageManager.INSTALL_SUCCEEDED) {
+                cleanUp(move.fromUuid);
+            } else {
+                cleanUp(move.toUuid);
             }
             return status;
         }
@@ -11333,32 +11335,28 @@
             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
         }
 
-        private boolean cleanUp() {
-            if (codeFile == null || !codeFile.exists()) {
-                return false;
+        private boolean cleanUp(String volumeUuid) {
+            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
+                    move.dataAppName);
+            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
+            synchronized (mInstallLock) {
+                // Clean up both app data and code
+                removeDataDirsLI(volumeUuid, move.packageName);
+                if (codeFile.isDirectory()) {
+                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
+                } else {
+                    codeFile.delete();
+                }
             }
-
-            if (codeFile.isDirectory()) {
-                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
-            } else {
-                codeFile.delete();
-            }
-
-            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
-                resourceFile.delete();
-            }
-
             return true;
         }
 
         void cleanUpResourcesLI() {
-            cleanUp();
+            throw new UnsupportedOperationException();
         }
 
         boolean doPostDeleteLI(boolean delete) {
-            // XXX err, shouldn't we respect the delete flag?
-            cleanUpResourcesLI();
-            return true;
+            throw new UnsupportedOperationException();
         }
     }
 
diff --git a/services/core/java/com/android/server/wm/AppTransition.java b/services/core/java/com/android/server/wm/AppTransition.java
index 0eee815..a57463c 100644
--- a/services/core/java/com/android/server/wm/AppTransition.java
+++ b/services/core/java/com/android/server/wm/AppTransition.java
@@ -715,7 +715,7 @@
      */
     Animation createAspectScaledThumbnailEnterExitAnimationLocked(int thumbTransitState,
             int appWidth, int appHeight, int orientation, int transit, Rect containingFrame,
-            Rect contentInsets, boolean isFullScreen) {
+            Rect contentInsets) {
         Animation a;
         final int thumbWidthI = mNextAppTransitionStartWidth;
         final float thumbWidth = thumbWidthI > 0 ? thumbWidthI : 1;
@@ -735,9 +735,6 @@
                     scaledTopDecor = (int) (scale * contentInsets.top);
                     int unscaledThumbHeight = (int) (thumbHeight / scale);
                     mTmpFromClipRect.set(containingFrame);
-                    if (isFullScreen) {
-                        mTmpFromClipRect.top = contentInsets.top;
-                    }
                     mTmpFromClipRect.bottom = (mTmpFromClipRect.top + unscaledThumbHeight);
                     mTmpToClipRect.set(containingFrame);
                 } else {
@@ -745,15 +742,13 @@
                     scale = thumbHeight / (appHeight - contentInsets.top);
                     scaledTopDecor = (int) (scale * contentInsets.top);
                     int unscaledThumbWidth = (int) (thumbWidth / scale);
-                    int unscaledThumbHeight = (int) (thumbHeight / scale);
                     mTmpFromClipRect.set(containingFrame);
-                    if (isFullScreen) {
-                        mTmpFromClipRect.top = contentInsets.top;
-                        mTmpFromClipRect.bottom = (mTmpFromClipRect.top + unscaledThumbHeight);
-                    }
                     mTmpFromClipRect.right = (mTmpFromClipRect.left + unscaledThumbWidth);
                     mTmpToClipRect.set(containingFrame);
                 }
+                // exclude top screen decor (status bar) region from the source clip.
+                mTmpFromClipRect.top = contentInsets.top;
+
                 mNextAppTransitionInsets.set(contentInsets);
 
                 Animation scaleAnim = new ScaleAnimation(scale, 1, scale, 1,
@@ -800,24 +795,19 @@
                     int unscaledThumbHeight = (int) (thumbHeight / scale);
                     mTmpFromClipRect.set(containingFrame);
                     mTmpToClipRect.set(containingFrame);
-                    if (isFullScreen) {
-                        mTmpToClipRect.top = contentInsets.top;
-                    }
                     mTmpToClipRect.bottom = (mTmpToClipRect.top + unscaledThumbHeight);
                 } else {
                     // In landscape, we scale the height and clip to the top/left square
                     scale = thumbHeight / (appHeight - contentInsets.top);
                     scaledTopDecor = (int) (scale * contentInsets.top);
                     int unscaledThumbWidth = (int) (thumbWidth / scale);
-                    int unscaledThumbHeight = (int) (thumbHeight / scale);
                     mTmpFromClipRect.set(containingFrame);
                     mTmpToClipRect.set(containingFrame);
-                    if (isFullScreen) {
-                        mTmpToClipRect.top = contentInsets.top;
-                        mTmpToClipRect.bottom = (mTmpToClipRect.top + unscaledThumbHeight);
-                    }
                     mTmpToClipRect.right = (mTmpToClipRect.left + unscaledThumbWidth);
                 }
+                // exclude top screen decor (status bar) region from the destination clip.
+                mTmpToClipRect.top = contentInsets.top;
+
                 mNextAppTransitionInsets.set(contentInsets);
 
                 Animation scaleAnim = new ScaleAnimation(1, scale, 1, scale,
@@ -963,7 +953,7 @@
 
     Animation loadAnimation(WindowManager.LayoutParams lp, int transit, boolean enter,
             int appWidth, int appHeight, int orientation, Rect containingFrame, Rect contentInsets,
-            Rect appFrame, boolean isFullScreen, boolean isVoiceInteraction) {
+            Rect appFrame, boolean isVoiceInteraction) {
         Animation a;
         if (isVoiceInteraction && (transit == TRANSIT_ACTIVITY_OPEN
                 || transit == TRANSIT_TASK_OPEN
@@ -1033,7 +1023,7 @@
                     (mNextAppTransitionType == NEXT_TRANSIT_TYPE_THUMBNAIL_ASPECT_SCALE_UP);
             a = createAspectScaledThumbnailEnterExitAnimationLocked(
                     getThumbnailTransitionState(enter), appWidth, appHeight, orientation,
-                    transit, containingFrame, contentInsets, isFullScreen);
+                    transit, containingFrame, contentInsets);
             if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
                 String animName = mNextAppTransitionScaleUp ?
                         "ANIM_THUMBNAIL_ASPECT_SCALE_UP" : "ANIM_THUMBNAIL_ASPECT_SCALE_DOWN";
diff --git a/services/core/java/com/android/server/wm/WindowAnimator.java b/services/core/java/com/android/server/wm/WindowAnimator.java
index 76baaa7..0bc6d22 100644
--- a/services/core/java/com/android/server/wm/WindowAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowAnimator.java
@@ -272,8 +272,9 @@
 
                 try {
                     if (anyAnimating && !anyWasAnimating) {
-                        win.mClient.onAnimationStarted(
-                                winAnimator.mKeyguardGoingAwayAnimation ? 1 : 0);
+                        win.mClient.onAnimationStarted(winAnimator.mAnimatingMove ? -1
+                                : winAnimator.mKeyguardGoingAwayAnimation ? 1
+                                : 0);
                     } else if (!anyAnimating && anyWasAnimating) {
                         win.mClient.onAnimationStopped();
                     }
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index fc86920..ac4fea8 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -304,11 +304,6 @@
 
     private static final int MAX_SCREENSHOT_RETRIES = 3;
 
-    // The flag describing a full screen app window (where the app takes care of drawing under the
-    // SystemUI bars)
-    private static final int SYSTEM_UI_FLAGS_LAYOUT_STABLE_FULLSCREEN =
-            View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
-
     private static final String PROPERTY_EMULATOR_CIRCULAR = "ro.emulator.circular";
 
     final private KeyguardDisableHandler mKeyguardDisableHandler;
@@ -3457,29 +3452,21 @@
             DisplayInfo displayInfo = getDefaultDisplayInfoLocked();
             final int width = displayInfo.appWidth;
             final int height = displayInfo.appHeight;
-            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG, "applyAnimation: atoken="
-                    + atoken);
+            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) Slog.v(TAG,
+                    "applyAnimation: atoken=" + atoken);
 
             // Determine the visible rect to calculate the thumbnail clip
             WindowState win = atoken.findMainWindow();
             Rect containingFrame = new Rect(0, 0, width, height);
             Rect contentInsets = new Rect();
             Rect appFrame = new Rect(0, 0, width, height);
-            boolean isFullScreen = true;
-            if (win != null) {
-                if (win.mContainingFrame != null) {
-                    containingFrame.set(win.mContainingFrame);
-                }
-                if (win.mContentInsets != null) {
-                    contentInsets.set(win.mContentInsets);
-                }
-                if (win.mFrame != null) {
-                    appFrame.set(win.mFrame);
-                }
-                isFullScreen =
-                        ((win.mSystemUiVisibility & SYSTEM_UI_FLAGS_LAYOUT_STABLE_FULLSCREEN) ==
-                                SYSTEM_UI_FLAGS_LAYOUT_STABLE_FULLSCREEN) ||
-                                ((win.mAttrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0);
+            if (win != null && win.isFullscreen(width, height)) {
+                // For fullscreen windows use the window frames and insets to set the thumbnail
+                // clip. For none-fullscreen windows we use the app display region so the clip
+                // isn't affected by the window insets.
+                containingFrame.set(win.mContainingFrame);
+                contentInsets.set(win.mContentInsets);
+                appFrame.set(win.mFrame);
             }
 
             if (atoken.mLaunchTaskBehind) {
@@ -3490,7 +3477,7 @@
             }
             Animation a = mAppTransition.loadAnimation(lp, transit, enter, width, height,
                     mCurConfiguration.orientation, containingFrame, contentInsets, appFrame,
-                    isFullScreen, isVoiceInteraction);
+                    isVoiceInteraction);
             if (a != null) {
                 if (DEBUG_ANIM) {
                     RuntimeException e = null;
@@ -10002,6 +9989,7 @@
                             winAnimator.mAnimDw = w.mLastFrame.left - left;
                             winAnimator.mAnimDh = w.mLastFrame.top - top;
                             winAnimator.mAnimateMove = true;
+                            winAnimator.mAnimatingMove = true;
                         }
 
                         //TODO (multidisplay): Accessibility supported only for the default display.
@@ -10053,7 +10041,10 @@
                         }
 
                         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) {
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index d818519..96cd14b 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -16,7 +16,6 @@
 
 package com.android.server.wm;
 
-import static android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
 import static com.android.server.wm.WindowManagerService.DEBUG_ANIM;
 import static com.android.server.wm.WindowManagerService.DEBUG_LAYERS;
@@ -122,7 +121,13 @@
     // used.
     int mAnimDw;
     int mAnimDh;
+
+    /** Is the next animation to be started a window move animation? */
     boolean mAnimateMove = false;
+
+    /** Are we currently running a window move animation? */
+    boolean mAnimatingMove = false;
+
     float mDsDx=1, mDtDx=0, mDsDy=0, mDtDy=1;
     float mLastDsDx=1, mLastDtDx=0, mLastDsDy=0, mLastDtDy=1;
 
@@ -361,6 +366,7 @@
 
         mAnimating = false;
         mKeyguardGoingAwayAnimation = false;
+        mAnimatingMove = false;
         mLocalAnimating = false;
         if (mAnimation != null) {
             mAnimation.cancel();
@@ -1231,10 +1237,6 @@
             mDtDx = 0;
             mDsDy = 0;
             mDtDy = mWin.mGlobalScale;
-            if (appTransformation == null) {
-                mHasClipRect = false;
-                mClipRect.setEmpty();
-            }
         }
     }
 
@@ -1306,9 +1308,9 @@
             applyDecorRect(w.mDecorFrame);
         }
 
-        // By default, the clip rect is the system decor.
+        // By default, the clip rect is the system decor if the transformation doesn't specify one.
         final Rect clipRect = mTmpClipRect;
-        clipRect.set(w.mSystemDecorRect);
+        clipRect.set((mHasClipRect) ? mClipRect : w.mSystemDecorRect);
 
         // Expand the clip rect for surface insets.
         final WindowManager.LayoutParams attrs = w.mAttrs;
@@ -1317,28 +1319,6 @@
         clipRect.right += attrs.surfaceInsets.right;
         clipRect.bottom += attrs.surfaceInsets.bottom;
 
-        // If we have an animated clip rect, intersect it with the clip rect.
-        // However, the clip rect animation effect should be applied on app windows that inset
-        // decor only. If applying on non-inset decor one, the top region of this window will
-        // be clipped on the end of animation, e.g. dialog activities.
-        if (mHasClipRect && (w.mAttrs.flags & LayoutParams.FLAG_LAYOUT_INSET_DECOR) != 0) {
-            // NOTE: We are adding a temporary workaround due to the status bar
-            // not always reporting the correct system decor rect. In such
-            // cases, we take into account the specified content insets as well.
-            if ((w.mSystemUiVisibility & SYSTEM_UI_FLAGS_LAYOUT_STABLE_FULLSCREEN)
-                    == SYSTEM_UI_FLAGS_LAYOUT_STABLE_FULLSCREEN
-                    || (w.mAttrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0) {
-                // Don't apply the workaround to apps explicitly requesting
-                // fullscreen layout or when the bars are transparent.
-                clipRect.intersect(mClipRect);
-            } else {
-                final int offsetTop = Math.max(clipRect.top, w.mContentInsets.top);
-                clipRect.offset(0, -offsetTop);
-                clipRect.intersect(mClipRect);
-                clipRect.offset(0, offsetTop);
-            }
-        }
-
         // The clip rect was generated assuming (0,0) as the window origin,
         // so we need to translate to match the actual surface coordinates.
         clipRect.offset(attrs.surfaceInsets.left, attrs.surfaceInsets.top);
diff --git a/services/usb/java/com/android/server/usb/UsbDeviceManager.java b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
index 934ff52..e7716c2 100644
--- a/services/usb/java/com/android/server/usb/UsbDeviceManager.java
+++ b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
@@ -319,6 +319,7 @@
         private String mCurrentFunctions;
         private UsbAccessory mCurrentAccessory;
         private int mUsbNotificationId;
+        private String mDefaultFunctions;
         private boolean mAdbNotificationShown;
         private int mCurrentUser = UserHandle.USER_NULL;
 
@@ -341,12 +342,18 @@
         public UsbHandler(Looper looper) {
             super(looper);
             try {
-                // Special note about persist.sys.usb.config: We only ever look at the adb value
-                // from that property. Other values are ignored. persist.sys.usb.config is now
-                // only used to determine if adb is enabled or not.
                 // TODO: rename persist.sys.usb.config to something more descriptive.
                 // persist.sys.usb.config should never be unset.  But if it is, set it to "adb"
                 // so we have a chance of debugging what happened.
+                mDefaultFunctions = SystemProperties.get("persist.sys.usb.config", "adb");
+
+                // sanity check the sys.usb.config system property
+                // this may be necessary if we crashed while switching USB configurations
+                String config = SystemProperties.get("sys.usb.config", "none");
+                if (!config.equals(mDefaultFunctions)) {
+                    Slog.w(TAG, "resetting config to persistent property: " + mDefaultFunctions);
+                    SystemProperties.set("sys.usb.config", mDefaultFunctions);
+                }
 
                 mAdbEnabled = containsFunction(
                         SystemProperties.get(UsbManager.ADB_PERSISTENT_PROPERTY, "adb"),
@@ -414,11 +421,11 @@
         }
 
         private void updatePersistentProperty() {
-            String newValue = mAdbEnabled ? "adb" : "none";
+            String newValue = getDefaultFunctions();
             String value = SystemProperties.get(UsbManager.ADB_PERSISTENT_PROPERTY);
             if (DEBUG) { Slog.d(TAG, "updatePersistentProperty newValue=" + newValue + " value=" + value); }
             if (!newValue.equals(value)) {
-                SystemProperties.set(UsbManager.ADB_PERSISTENT_PROPERTY, mAdbEnabled ? "adb" : "none");
+                SystemProperties.set(UsbManager.ADB_PERSISTENT_PROPERTY, getDefaultFunctions());
             }
             waitForState(newValue);
         }
@@ -797,7 +804,12 @@
         }
 
         private String getDefaultFunctions() {
-            return mAdbEnabled ? UsbManager.USB_FUNCTION_ADB : UsbManager.USB_FUNCTION_MTP;
+            UserManager userManager = (UserManager)mContext.getSystemService(Context.USER_SERVICE);
+            if(userManager.hasUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER,
+                new UserHandle(mCurrentUser))) {
+               return "none";
+             }
+             return mDefaultFunctions;
         }
 
         public void dump(FileDescriptor fd, PrintWriter pw) {
diff --git a/telephony/java/android/telephony/CellSignalStrength.java b/telephony/java/android/telephony/CellSignalStrength.java
index 9c23f78..2a3ef21 100644
--- a/telephony/java/android/telephony/CellSignalStrength.java
+++ b/telephony/java/android/telephony/CellSignalStrength.java
@@ -21,18 +21,19 @@
  */
 public abstract class CellSignalStrength {
 
-    /** @hide */
     public static final int SIGNAL_STRENGTH_NONE_OR_UNKNOWN = 0;
-    /** @hide */
+
     public static final int SIGNAL_STRENGTH_POOR = 1;
-    /** @hide */
+
     public static final int SIGNAL_STRENGTH_MODERATE = 2;
-    /** @hide */
+
     public static final int SIGNAL_STRENGTH_GOOD = 3;
-    /** @hide */
+
     public static final int SIGNAL_STRENGTH_GREAT = 4;
+
     /** @hide */
     public static final int NUM_SIGNAL_STRENGTH_BINS = 5;
+
     /** @hide */
     public static final String[] SIGNAL_STRENGTH_NAMES = {
         "none", "poor", "moderate", "good", "great"
@@ -47,6 +48,12 @@
 
     /**
      * Get signal level as an int from 0..4
+     * <p>
+     * @see SIGNAL_STRENGTH_NONE_OR_UNKNOWN
+     * @see SIGNAL_STRENGTH_POOR
+     * @see SIGNAL_STRENGTH_MODERATE
+     * @see SIGNAL_STRENGTH_GOOD
+     * @see SIGNAL_STRENGTH_GREAT
      */
     public abstract int getLevel();