OSDN Git Service

Merge tag 'android-7.1.2_r2' into cm-14.1
authorDan Pasanen <dan.pasanen@gmail.com>
Wed, 5 Apr 2017 15:39:43 +0000 (10:39 -0500)
committerDan Pasanen <dan.pasanen@gmail.com>
Wed, 5 Apr 2017 18:21:53 +0000 (13:21 -0500)
Android 7.1.2 Release 2 (N2G47E)

Change-Id: I6ad99831e8b63d43e4824264bd54a5d4da3e21e3

135 files changed:
1  2 
Android.mk
cmds/bootanimation/BootAnimation.cpp
cmds/bootanimation/BootAnimation.h
core/java/android/app/ActivityManager.java
core/java/android/app/ActivityThread.java
core/java/android/app/AppOpsManager.java
core/java/android/app/ApplicationPackageManager.java
core/java/android/app/admin/DevicePolicyManager.java
core/java/android/app/admin/IDevicePolicyManager.aidl
core/java/android/app/backup/BackupAgent.java
core/java/android/bluetooth/BluetoothAdapter.java
core/java/android/bluetooth/BluetoothProfile.java
core/java/android/bluetooth/IBluetooth.aidl
core/java/android/content/Intent.java
core/java/android/content/pm/PackageManager.java
core/java/android/inputmethodservice/InputMethodService.java
core/java/android/net/ConnectivityManager.java
core/java/android/os/PowerManager.java
core/java/android/os/UserManager.java
core/java/android/provider/Settings.java
core/java/android/service/notification/NotificationListenerService.java
core/java/android/view/View.java
core/java/android/view/ViewRootImpl.java
core/java/android/view/Window.java
core/java/android/widget/AbsListView.java
core/java/com/android/internal/app/AlertController.java
core/java/com/android/internal/os/ZygoteInit.java
core/java/com/android/internal/widget/LockPatternView.java
core/jni/Android.mk
core/jni/AndroidRuntime.cpp
core/jni/android_util_AssetManager.cpp
core/jni/fd_utils-inl.h
core/res/AndroidManifest.xml
core/res/res/values-ar/strings.xml
core/res/res/values-de/strings.xml
core/res/res/values-zh-rCN/strings.xml
core/res/res/values-zh-rHK/strings.xml
core/res/res/values/attrs_manifest.xml
core/res/res/values/bools.xml
core/res/res/values/colors_material.xml
core/res/res/values/config.xml
core/res/res/values/strings.xml
core/res/res/values/symbols.xml
include/androidfw/AssetManager.h
libs/androidfw/AssetManager.cpp
media/java/android/media/AudioManager.java
media/java/android/media/MediaRecorder.java
packages/DocumentsUI/AndroidManifest.xml
packages/Keyguard/res/values-zh-rCN/strings.xml
packages/SettingsLib/res/values/strings.xml
packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothEventManager.java
packages/SettingsProvider/res/values/defaults.xml
packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
packages/SystemUI/AndroidManifest.xml
packages/SystemUI/res/values/config.xml
packages/SystemUI/res/values/dimens.xml
packages/SystemUI/res/values/strings.xml
packages/SystemUI/src/com/android/systemui/ExpandHelper.java
packages/SystemUI/src/com/android/systemui/assist/AssistManager.java
packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
packages/SystemUI/src/com/android/systemui/power/PowerUI.java
packages/SystemUI/src/com/android/systemui/qs/QSAnimator.java
packages/SystemUI/src/com/android/systemui/qs/QSPanel.java
packages/SystemUI/src/com/android/systemui/qs/external/CustomTile.java
packages/SystemUI/src/com/android/systemui/recents/ScreenPinningRequest.java
packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java
packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java
packages/SystemUI/src/com/android/systemui/settings/BrightnessController.java
packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
packages/SystemUI/src/com/android/systemui/statusbar/ExpandableNotificationRow.java
packages/SystemUI/src/com/android/systemui/statusbar/NotificationData.java
packages/SystemUI/src/com/android/systemui/statusbar/SignalClusterView.java
packages/SystemUI/src/com/android/systemui/statusbar/phone/ButtonDispatcher.java
packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarInflaterView.java
packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
packages/SystemUI/src/com/android/systemui/statusbar/policy/DeadZone.java
packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java
packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java
packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java
packages/SystemUI/src/com/android/systemui/statusbar/policy/TelephonyIcons.java
packages/SystemUI/src/com/android/systemui/usb/StorageNotification.java
proto/src/metrics_constants.proto
services/appwidget/java/com/android/server/appwidget/AppWidgetServiceImpl.java
services/core/Android.mk
services/core/java/com/android/server/BluetoothManagerService.java
services/core/java/com/android/server/ConnectivityService.java
services/core/java/com/android/server/DeviceIdleController.java
services/core/java/com/android/server/LockSettingsService.java
services/core/java/com/android/server/am/ActiveServices.java
services/core/java/com/android/server/am/ActivityManagerService.java
services/core/java/com/android/server/am/ActivityStarter.java
services/core/java/com/android/server/am/UserController.java
services/core/java/com/android/server/audio/AudioService.java
services/core/java/com/android/server/connectivity/Tethering.java
services/core/java/com/android/server/display/AutomaticBrightnessController.java
services/core/java/com/android/server/display/DisplayPowerController.java
services/core/java/com/android/server/display/LocalDisplayAdapter.java
services/core/java/com/android/server/input/InputManagerService.java
services/core/java/com/android/server/lights/Light.java
services/core/java/com/android/server/lights/LightsService.java
services/core/java/com/android/server/location/GnssLocationProvider.java
services/core/java/com/android/server/net/NetworkPolicyManagerService.java
services/core/java/com/android/server/notification/NotificationManagerService.java
services/core/java/com/android/server/pm/PackageManagerService.java
services/core/java/com/android/server/pm/ShortcutService.java
services/core/java/com/android/server/pm/UserManagerService.java
services/core/java/com/android/server/policy/PhoneWindowManager.java
services/core/java/com/android/server/power/PowerManagerService.java
services/core/java/com/android/server/power/ShutdownThread.java
services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
services/core/java/com/android/server/wm/WallpaperController.java
services/core/jni/com_android_server_input_InputManagerService.cpp
services/core/jni/com_android_server_lights_LightsService.cpp
services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
services/java/com/android/server/SystemServer.java
services/net/java/android/net/dhcp/DhcpPacket.java
services/net/java/android/net/ip/IpManager.java
services/usb/java/com/android/server/usb/UsbDeviceManager.java
telecomm/java/android/telecom/Call.java
telecomm/java/android/telecom/Connection.java
telecomm/java/android/telecom/ConnectionService.java
telecomm/java/android/telecom/ParcelableCall.java
telecomm/java/android/telecom/TelecomManager.java
telephony/java/android/telephony/CarrierConfigManager.java
telephony/java/android/telephony/DisconnectCause.java
telephony/java/android/telephony/PhoneNumberUtils.java
telephony/java/android/telephony/TelephonyManager.java
test-runner/src/android/test/mock/MockPackageManager.java
wifi/java/android/net/wifi/IWifiManager.aidl
wifi/java/android/net/wifi/WifiConfiguration.java
wifi/java/android/net/wifi/WifiManager.java

diff --cc Android.mk
Simple merge
Simple merge
@@@ -108,20 -119,17 +119,24 @@@ private
          String8 audioConf;
          String8 fileName;
          ZipFileRO* zip;
+         Font clockFont;
      };
  
 +    /**
 +     *IMG_OEM: bootanimation file from oem/media
 +     *IMG_SYS: bootanimation file from system/media
 +     *IMG_ENC: encrypted bootanimation file from system/media
 +     */
 +    enum ImageID { IMG_OEM = 0, IMG_SYS = 1, IMG_ENC = 2 };
 +    const char *getAnimationFileName(ImageID image);
      status_t initTexture(Texture* texture, AssetManager& asset, const char* name);
-     status_t initTexture(const Animation::Frame& frame);
+     status_t initTexture(FileMap* map, int* width, int* height);
+     status_t initFont(Font* font, const char* fallback);
      bool android();
      bool movie();
-     void drawTime(const Texture& clockTex, const int yPos);
+     void drawText(const char* str, const Font& font, bool bold, int* x, int* y);
+     void drawClock(const Font& font, const int xPos, const int yPos);
+     bool validClock(const Animation::Part& part);
      Animation* loadAnimation(const String8&);
      bool playAnimation(const Animation&);
      void releaseAnimation(Animation*) const;
@@@ -6626,22 -6636,79 +6636,99 @@@ public class DevicePolicyManager 
      }
  
      /**
+      * Called by a device owner to control the network logging feature. Logging can only be
+      * enabled on single user devices where the sole user is managed by the device owner. If a new
+      * user is added on the device, logging is disabled.
+      *
+      * <p> Network logs contain DNS lookup and connect() library call events.
+      *
+      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
+      * @param enabled whether network logging should be enabled or not.
+      * @throws {@link SecurityException} if {@code admin} is not a device owner.
+      * @see #retrieveNetworkLogs
+      *
+      * @hide
+      */
+     public void setNetworkLoggingEnabled(@NonNull ComponentName admin, boolean enabled) {
+         throwIfParentInstance("setNetworkLoggingEnabled");
+         try {
+             mService.setNetworkLoggingEnabled(admin, enabled);
+         } catch (RemoteException re) {
+             throw re.rethrowFromSystemServer();
+         }
+     }
+     /**
+      * Return whether network logging is enabled by a device owner.
+      *
+      * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Can only
+      * be {@code null} if the caller has MANAGE_USERS permission.
+      * @return {@code true} if network logging is enabled by device owner, {@code false} otherwise.
+      * @throws {@link SecurityException} if {@code admin} is not a device owner and caller has
+      * no MANAGE_USERS permission
+      *
+      * @hide
+      */
+     public boolean isNetworkLoggingEnabled(@Nullable ComponentName admin) {
+         throwIfParentInstance("isNetworkLoggingEnabled");
+         try {
+             return mService.isNetworkLoggingEnabled(admin);
+         } catch (RemoteException re) {
+             throw re.rethrowFromSystemServer();
+         }
+     }
+     /**
+      * Called by device owner to retrieve the most recent batch of network logging events.
+      * A device owner has to provide a batchToken provided as part of
+      * {@link DeviceAdminReceiver#onNetworkLogsAvailable} callback. If the token doesn't match the
+      * token of the most recent available batch of logs, {@code null} will be returned.
+      *
+      * <p> {@link NetworkEvent} can be one of {@link DnsEvent} or {@link ConnectEvent}.
+      *
+      * <p> The list of network events is sorted chronologically, and contains at most 1200 events.
+      *
+      * <p> Access to the logs is rate limited and this method will only return a new batch of logs
+      * after the device device owner has been notified via
+      * {@link DeviceAdminReceiver#onNetworkLogsAvailable}.
+      *
+      * @param admin Which {@link DeviceAdminReceiver} this request is associated with.
+      * @param batchToken A token of the batch to retrieve
+      * @return A new batch of network logs which is a list of {@link NetworkEvent}. Returns
+      *        {@code null} if the batch represented by batchToken is no longer available or if
+      *        logging is disabled.
+      * @throws {@link SecurityException} if {@code admin} is not a device owner.
+      * @see DeviceAdminReceiver#onNetworkLogsAvailable
+      *
+      * @hide
+      */
+     public @Nullable List<NetworkEvent> retrieveNetworkLogs(@NonNull ComponentName admin,
+             long batchToken) {
+         throwIfParentInstance("retrieveNetworkLogs");
+         try {
+             return mService.retrieveNetworkLogs(admin, batchToken);
+         } catch (RemoteException re) {
+             throw re.rethrowFromSystemServer();
+         }
+     }
++
++    /**
 +     * CM: check if secure keyguard is required
 +     * @hide
 +     */
 +    public boolean requireSecureKeyguard() {
 +        return requireSecureKeyguard(UserHandle.myUserId());
 +    }
 +
 +    /** @hide */
 +    public boolean requireSecureKeyguard(int userHandle) {
 +        if (mService != null) {
 +            try {
 +                return mService.requireSecureKeyguard(userHandle);
 +            } catch (RemoteException e) {
 +                Log.w(TAG, "Failed to get secure keyguard requirement");
 +            }
 +        }
 +        return true;
 +    }
  }
@@@ -313,5 -314,7 +314,9 @@@ interface IDevicePolicyManager 
      void setBackupServiceEnabled(in ComponentName admin, boolean enabled);
      boolean isBackupServiceEnabled(in ComponentName admin);
  
+     void setNetworkLoggingEnabled(in ComponentName admin, boolean enabled);
+     boolean isNetworkLoggingEnabled(in ComponentName admin);
+     List<NetworkEvent> retrieveNetworkLogs(in ComponentName admin, long batchToken);
++
 +    boolean requireSecureKeyguard(int userHandle);
  }
@@@ -900,9 -895,8 +900,9 @@@ public final class BluetoothAdapter 
       */
      @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
      public boolean enable() {
-         if (isEnabled() == true) {
-             if (DBG) Log.d(TAG, "enable(): BT is already enabled..!");
 +        android.util.SeempLog.record(56);
+         if (isEnabled()) {
+             if (DBG) Log.d(TAG, "enable(): BT already enabled!");
              return true;
          }
          try {
       */
      @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
      public boolean disable() {
 +        android.util.SeempLog.record(57);
          try {
-             return mManagerService.disable(true);
+             return mManagerService.disable(ActivityThread.currentPackageName(), true);
          } catch (RemoteException e) {Log.e(TAG, "", e);}
          return false;
      }
       * @hide
       */
      public boolean disable(boolean persist) {
 +        android.util.SeempLog.record(57);
  
          try {
-             return mManagerService.disable(persist);
+             return mManagerService.disable(ActivityThread.currentPackageName(), persist);
          } catch (RemoteException e) {Log.e(TAG, "", e);}
          return false;
      }
                              if (cb != null) {
                                  cb.onBluetoothServiceDown();
                              } else {
-                                 Log.d(TAG, "onBluetoothServiceDown: cb is null!!!");
+                                 Log.d(TAG, "onBluetoothServiceDown: cb is null!");
                              }
 -                        } catch (Exception e) {
 -                            Log.e(TAG,"",e);
 -                        }
 +                        } catch (Exception e)  { Log.e(TAG,"",e);}
                      }
                  }
 +                Log.d(TAG, "onBluetoothServiceDown: Finished sending callbacks to registered clients");
              }
  
              public void onBrEdrDown() {
@@@ -137,12 -137,13 +137,19 @@@ public interface BluetoothProfile 
      public static final int PBAP_CLIENT = 17;
  
      /**
+      * Max profile ID. This value should be updated whenever a new profile is added to match
+      * the largest value assigned to a profile.
+      * @hide
+      */
+     public static final int MAX_PROFILE_ID = 17;
+     /**
 +     * DUN
 +     * @hide
 +     */
 +    public static final int DUN = 21;
 +
 +    /**
       * Default priority for devices that we try to auto-connect to and
       * and allow incoming connections for the profile
       * @hide
Simple merge
Simple merge
index dd2a5de,a8209af..c83bd3e
mode 100644,100755..100644
@@@ -6552,18 -6406,12 +6601,24 @@@ public final class Settings 
          public static final String WEB_ACTION_ENABLED = "web_action_enabled";
  
          /**
+          * Has this pairable device been paired or upgraded from a previously paired system.
+          * @hide
+          */
+         public static final String DEVICE_PAIRED = "device_paired";
+         /**
 +         * Whether to include options in power menu for rebooting into recovery or bootloader
 +         * @hide
 +         */
 +        public static final String ADVANCED_REBOOT = "advanced_reboot";
 +
 +        /**
 +         * Boolean value whether to link ringtone and notification volume
 +         * @hide
 +         */
 +        public static final String VOLUME_LINK_NOTIFICATION = "volume_link_notification";
 +
 +        /**
           * This are the settings to be backed up.
           *
           * NOTE: Settings are backed up and restored in the order they appear
              DOZE_ENABLED,
              DOZE_PULSE_ON_PICK_UP,
              DOZE_PULSE_ON_DOUBLE_TAP,
 -            NFC_PAYMENT_DEFAULT_COMPONENT
++            NFC_PAYMENT_DEFAULT_COMPONENT,
 +            ADVANCED_REBOOT,
 +            CAMERA_GESTURE_DISABLED
          };
  
          /**
Simple merge
Simple merge
@@@ -2167,14 -2174,8 +2174,15 @@@ public abstract class AbsListView exten
          // TODO: Move somewhere sane. This doesn't belong in onLayout().
          if (mFastScroll != null) {
              mFastScroll.onItemCountChanged(getChildCount(), mItemCount);
 +            //This may call internalSetPadding and cause children dirty.
 +            //So need to layout children again.
 +            if(isLayoutRequested()){
 +                mInLayout = true;
 +                layoutChildren();
 +                mInLayout = false;
 +            }
          }
+         mInLayout = false;
      }
  
      /**
@@@ -148,10 -144,12 +149,14 @@@ public class LockPatternView extends Vi
      private PatternExploreByTouchHelper mExploreByTouchHelper;
      private AudioManager mAudioManager;
  
+     private Drawable mSelectedDrawable;
+     private Drawable mNotSelectedDrawable;
+     private boolean mUseLockPatternDrawable;
 +    private LockPatternUtils mLockPatternUtils;
 +
      /**
 -     * Represents a cell in the 3 X 3 matrix of the unlock pattern view.
 +     * Represents a cell in the matrix of the unlock pattern view.
       */
      public static final class Cell {
          final int row;
  
          if (DEBUG_A11Y) Log.v(TAG, "onSizeChanged(" + w + "," + h + ")");
          final int height = h - mPaddingTop - mPaddingBottom;
 -        mSquareHeight = height / 3.0f;
 +        mSquareHeight = height / (float) mPatternSize;
          mExploreByTouchHelper.invalidateRoot();
+         if (mUseLockPatternDrawable) {
+             mNotSelectedDrawable.setBounds(mPaddingLeft, mPaddingTop, width, height);
+             mSelectedDrawable.setBounds(mPaddingLeft, mPaddingTop, width, height);
+         }
      }
  
      private int resolveMeasured(int measureSpec, int desired)
          currentPath.rewind();
  
          // draw the circles
 -        for (int i = 0; i < 3; i++) {
 -            float centerY = getCenterYForRow(i);
 -            for (int j = 0; j < 3; j++) {
 -                CellState cellState = mCellStates[i][j];
 -                float centerX = getCenterXForColumn(j);
 -                float translationY = cellState.translationY;
 -
 -                if (mUseLockPatternDrawable) {
 -                    drawCellDrawable(canvas, i, j, cellState.radius, drawLookup[i][j]);
 -                } else {
 -                    if (isHardwareAccelerated() && cellState.hwAnimating) {
 -                        DisplayListCanvas displayListCanvas = (DisplayListCanvas) canvas;
 -                        displayListCanvas.drawCircle(cellState.hwCenterX, cellState.hwCenterY,
 -                                cellState.hwRadius, cellState.hwPaint);
 +        if (mVisibleDots) {
 +            for (int i = 0; i < mPatternSize; i++) {
 +                float centerY = getCenterYForRow(i);
 +                for (int j = 0; j < mPatternSize; j++) {
 +                    CellState cellState = mCellStates[i][j];
 +                    float centerX = getCenterXForColumn(j);
 +                    float translationY = cellState.translationY;
-                     if (isHardwareAccelerated() && cellState.hwAnimating) {
-                         DisplayListCanvas displayListCanvas = (DisplayListCanvas) canvas;
-                         displayListCanvas.drawCircle(cellState.hwCenterX, cellState.hwCenterY,
-                                 cellState.hwRadius, cellState.hwPaint);
++                    if (mUseLockPatternDrawable) {
++                        drawCellDrawable(canvas, i, j, cellState.radius, drawLookup[i][j]);
                      } else {
--                        drawCircle(canvas, (int) centerX, (int) centerY + translationY,
--                                cellState.radius, drawLookup[i][j], cellState.alpha);
++                        if (isHardwareAccelerated() && cellState.hwAnimating) {
++                            DisplayListCanvas displayListCanvas = (DisplayListCanvas) canvas;
++                            displayListCanvas.drawCircle(cellState.hwCenterX, cellState.hwCenterY,
++                                    cellState.hwRadius, cellState.hwPaint);
++                        } else {
++                            drawCircle(canvas, (int) centerX, (int) centerY + translationY,
++                                    cellState.radius, drawLookup[i][j], cellState.alpha);
++                        }
                      }
                  }
              }
Simple merge
Simple merge
  #include <sys/types.h>
  #include <sys/wait.h>
  #include <sys/stat.h>
+ #include <sys/system_properties.h>
  
  #include <private/android_filesystem_config.h> // for AID_SYSTEM
 +#include <private/regionalization/Environment.h>
  
  #include "androidfw/Asset.h"
  #include "androidfw/AssetManager.h"
Simple merge
Simple merge
Simple merge
Simple merge
      <bool name="show_ongoing_ime_switcher">true</bool>
      <bool name="action_bar_expanded_action_views_exclusive">true</bool>
      <bool name="target_honeycomb_needs_options_menu">true</bool>
+     <!-- Whether or not to use the drawable/lockscreen_notselected and
+          drawable/lockscreen_selected instead of the generic dots when displaying
+          the LockPatternView.
+          <p>The main purpose is for OEMs to customize the rendering of the
+          lockscreen, setting this to true should come with customized drawables. -->
+     <bool name="use_lock_pattern_drawable">false</bool>
 +
 +    <!-- Whether to enable softap extention feature -->
 +    <bool name="config_softap_extention">true</bool>
  </resources>
index 95d8f8e,7baed78..b74ec03
mode 100755,100644..100755
      <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">false</bool>
 +    <bool translatable="false" name="config_wifi_hotspot2_enabled">true</bool>
  
+     <!-- Boolean indicating whether 802.11r Fast BSS Transition is enabled on this platform -->
+     <bool translatable="false" name="config_wifi_fast_bss_transition_enabled">false</bool>
      <!-- Device type information conforming to Annex B format in WiFi Direct specification.
           The default represents a dual-mode smartphone -->
      <string translatable="false" name="config_wifi_p2p_device_type">10-0050F204-5</string>
      <integer-array name="config_autoBrightnessKeyboardBacklightValues">
      </integer-array>
  
 +    <integer name="config_buttonBrightnessSettingDefault">255</integer>
 +    <integer name="config_keyboardBrightnessSettingDefault">0</integer>
 +    <bool name="config_deviceHasVariableButtonBrightness">false</bool>
 +
+     <!-- Array of hysteresis constraint values for brightening, represented as tenths of a
+          percent. The length of this array is assumed to be one greater than
+          config_dynamicHysteresisLuxLevels. The brightening threshold is calculated as
+          lux * (1.0f + CONSTRAINT_VALUE). When the current lux is higher than this threshold,
+          the screen brightness is recalculated. See the config_dynamicHysteresisLuxLevels
+          description for how the constraint value is chosen. -->
+     <integer-array name="config_dynamicHysteresisBrightLevels">
+         <item>100</item>
+     </integer-array>
+     <!-- Array of hysteresis constraint values for darkening, represented as tenths of a
+          percent. The length of this array is assumed to be one greater than
+          config_dynamicHysteresisLuxLevels. The darkening threshold is calculated as
+          lux * (1.0f - CONSTRAINT_VALUE). When the current lux is lower than this threshold,
+          the screen brightness is recalculated. See the config_dynamicHysteresisLuxLevels
+          description for how the constraint value is chosen. -->
+     <integer-array name="config_dynamicHysteresisDarkLevels">
+         <item>200</item>
+     </integer-array>
+     <!-- Array of ambient lux threshold values. This is used for determining hysteresis constraint
+          values by calculating the index to use for lookup and then setting the constraint value
+          to the corresponding value of the array. The new brightening hysteresis constraint value
+          is the n-th element of config_dynamicHysteresisBrightLevels, and the new darkening
+          hysteresis constraint value is the n-th element of config_dynamicHysteresisDarkLevels.
+          The (zero-based) index is calculated as follows: (MAX is the largest index of the array)
+          condition                      calculated index
+          value < lux[0]                 0
+          lux[n] <= value < lux[n+1]     n+1
+          lux[MAX] <= value              MAX+1 -->
+     <integer-array name="config_dynamicHysteresisLuxLevels">
+     </integer-array>
+     <!-- Array of ambient light sensor lux threshold values for determining screen brightness for
+          devices that have both an ambient light sensor and the screen on while dozing. This is
+          used to determine the screen brightness while dozing by calculating the index to use for
+          lookup and then setting the screen brightness value to the corresponding value of
+          config_dozeBrightnessBacklightValues.
+          The (zero-based) index is calculated as follows: (MAX is the largest index of the array)
+          condition                      calculated index
+          value < lux[0]                 0
+          lux[n] <= value < lux[n+1]     n+1
+          lux[MAX] <= value              MAX+1 -->
+     <integer-array name="config_dozeSensorLuxLevels">
+     </integer-array>
+     <!-- Array of values for determining screen brightness for devices that have both an ambient
+          light sensor and the screen on while dozing. The length of this array is assumed to be one
+          greater than config_dozeModeSensorLuxLevels if they are not both empty. See the
+          config_dozeModeSensorLuxLevels description for how the backlight value is chosen. -->
+     <integer-array name="config_dozeBrightnessBacklightValues">
+     </integer-array>
      <!-- Amount of time it takes for the light sensor to warm up in milliseconds.
           For this time after the screen turns on, the Power Manager
           will not debounce light sensor readings -->
      <!-- An array of packages for which notifications cannot be blocked. -->
      <string-array translatable="false" name="config_nonBlockableNotificationPackages" />
  
 +    <!-- Timeout in MS for how long you have to long-press the back key to
 +         kill the foreground app. -->
 +    <integer name="config_backKillTimeout">2000</integer>
 +
 +    <!-- Setting to false will disable CM's IME switcher implementation for tablets -->
 +    <bool name="config_show_cmIMESwitcher">true</bool>
 +
 +    <!-- The list of components which should be automatically disabled. -->
 +    <string-array name="config_disabledComponents" translatable="false">
 +    </string-array>
 +
 +    <!-- The list of components which should be forced to be enabled. -->
 +    <string-array name="config_forceEnabledComponents" translatable="false">
 +    </string-array>
 +
 +    <!-- Whether to persist the notification for when a usb drive device is plugged in -->
 +    <bool name="config_persistUsbDriveNotification">false</bool>
 +
 +    <!-- Older rotation sensors are not setting event.timestamp correctly. Setting to
 +         true will use SystemClock.elapsedRealtimeNanos() to set timestamp. -->
 +    <bool name="config_useSystemClockforRotationSensor">false</bool>
 +
 +    <!-- Boolean to enable stk functionality on Samsung phones -->
 +    <bool name="config_samsung_stk">false</bool>
 +
 +    <!-- Certain sensor firmwares break with having a batch
 +         size set. By setting this to false, devices can opt
 +         out of setting a batch size, which fixes rotation. -->
 +    <bool name="config_useDefaultBatchingForAccel">true</bool>
 +
 +    <!-- Support in Surfaceflinger for blur layers.
 +         NOTE: This requires additional hardware-specific code. -->
 +    <bool name="config_uiBlurEnabled">false</bool>
 +
 +    <!-- Whether to enable HumanInteractionController by default -->
 +    <bool name="config_HICEnabledDefault">true</bool>
 +
 +    <!-- Allow the flashlight to use wakelocks -->
 +    <bool name="config_useWakeLockForFlashlight">false</bool>
++
+     <!-- Specifies whether the permissions needed by a legacy app should be
+          reviewed before any of its components can run. A legacy app is one
+          with targetSdkVersion < 23, i.e apps using the old permission model.
+          If review is not required, permissions are reviewed before the app
+          is installed. -->
+     <bool name="config_permissionReviewRequired">false</bool>
  </resources>
index bab166a,08ac043..7154e94
mode 100755,100644..100755
    <java-symbol type="bool" name="config_goToSleepOnButtonPressTheaterMode" />
    <java-symbol type="bool" name="config_supportLongPressPowerWhenNonInteractive" />
    <java-symbol type="bool" name="config_wifi_background_scan_support" />
 +  <java-symbol type="bool" name="wifi_autocon" />
    <java-symbol type="bool" name="config_wifi_dual_band_support" />
    <java-symbol type="bool" name="config_wifi_hotspot2_enabled" />
+   <java-symbol type="bool" name="config_wifi_fast_bss_transition_enabled" />
    <java-symbol type="bool" name="config_wimaxEnabled" />
    <java-symbol type="bool" name="show_ongoing_ime_switcher" />
    <java-symbol type="color" name="config_defaultNotificationColor" />
    <!-- Screen-size-dependent modes for picker dialogs. -->
    <java-symbol type="integer" name="time_picker_mode" />
    <java-symbol type="integer" name="date_picker_mode" />
 +
 +  <!-- Gesture Sensor -->
 +  <java-symbol type="bool" name="config_enableGestureService" />
 +
 +  <!-- Config.xml entries -->
 +  <java-symbol type="bool" name="config_show_cmIMESwitcher"/>
 +  <java-symbol type="bool" name="config_samsung_stk" />
 +
 +  <!-- Developer settings - Kill app back press -->
 +  <java-symbol type="string" name="app_killed_message" />
 +
 +  <!-- Config.xml entries -->
 +  <java-symbol type="integer" name="config_backKillTimeout" />
 +
 +  <!-- Power menu -->
 +  <java-symbol type="drawable" name="ic_lock_screenshot" />
 +  <java-symbol type="string" name="global_action_screenshot" />
 +  <java-symbol type="drawable" name="ic_lock_settings" />
 +  <java-symbol type="drawable" name="ic_lock_user" />
 +
 +  <!-- ADB notification -->
 +  <java-symbol type="string" name="adb_net_active_notification_title" />
 +  <java-symbol type="string" name="adb_both_active_notification_title" />
 +  <java-symbol type="string" name="adb_active_generic_notification_message" />
 +
 +  <java-symbol type="bool" name="config_useSystemClockforRotationSensor" />
 +
 +  <!-- Last app switch animations -->
 +  <java-symbol type="anim" name="last_app_in" />
 +  <java-symbol type="anim" name="last_app_out" />
 +
 +  <!-- config softap extention feature -->
 +  <java-symbol type="bool" name="config_softap_extention" />
 +
 +  <!-- Accelerometer batching -->
 +  <java-symbol type="bool" name="config_useDefaultBatchingForAccel" />
 +
 +  <!-- Allow devices to use wakelock for flashlight -->
 +  <java-symbol type="bool" name="config_useWakeLockForFlashlight" />
++
+   <java-symbol type="bool" name="config_permissionReviewRequired" />
+   <java-symbol type="bool" name="use_lock_pattern_drawable" />
+   <java-symbol type="drawable" name="lockscreen_notselected" />
+   <java-symbol type="drawable" name="lockscreen_selected" />
  </resources>
Simple merge
@@@ -814,17 -805,9 +815,17 @@@ void AssetManager::addSystemOverlays(co
              sharedRes->add(oass, oidmap, offset + 1, false);
              const_cast<AssetManager*>(this)->mAssetPaths.add(oap);
              const_cast<AssetManager*>(this)->mZipSet.addOverlay(targetPackagePath, oap);
 +
 +            oidmap->close();
              delete oidmap;
-       }
-   }
 +            ALOGD("close idmap=%s pid=%d\n", oap.idmap.string(), getpid());
 +       }
 +
 +        if (oap.path.find(OVERLAY_DIR) != -1) {
 +           const_cast<AssetManager*>(this)->mZipSet.closeZipFromPath(oap.path);
 +           ALOGD("close: %s and reset entry\n", oap.path.string());
+         }
+     }
  
  #ifndef _WIN32
      TEMP_FAILURE_RETRY(flock(fileno(fin), LOCK_UN));
Simple merge
  
      <bool name="quick_settings_show_full_alarm">false</bool>
  
+     <!-- Whether to show a warning notification when the device reaches a certain temperature. -->
+     <integer name="config_showTemperatureWarning">0</integer>
+     <!-- Temp at which to show a warning notification if config_showTemperatureWarning is true.
+          If < 0, uses the value from HardwarePropertiesManager#getDeviceTemperatures. -->
+     <integer name="config_warningTemperature">-1</integer>
 +    <bool name="config_show4gForIWlan">false</bool>
 +    <bool name="config_showSignalForIWlan">false</bool>
++
  </resources>
index 9e0406a,c7b621b..e438347
mode 100755,100644..100755
@@@ -63,9 -65,8 +65,11 @@@ import android.view.WindowManagerPolicy
  import android.view.animation.Animation;
  import android.view.animation.AnimationUtils;
  
 +import cyanogenmod.app.Profile;
 +import cyanogenmod.app.ProfileManager;
 +
+ import com.android.internal.logging.MetricsLogger;
+ import com.android.internal.logging.MetricsProto.MetricsEvent;
  import com.android.internal.policy.IKeyguardDrawnCallback;
  import com.android.internal.policy.IKeyguardExitCallback;
  import com.android.internal.policy.IKeyguardStateCallback;
@@@ -640,10 -665,12 +668,13 @@@ public class KeyguardViewMediator exten
  
          mShowKeyguardWakeLock = mPM.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "show keyguard");
          mShowKeyguardWakeLock.setReferenceCounted(false);
-         mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));
-         mContext.registerReceiver(
-                 mBroadcastReceiver, new IntentFilter(DELAYED_LOCK_PROFILE_ACTION));
 +        mProfileManager = ProfileManager.getInstance(mContext);
+         IntentFilter filter = new IntentFilter();
+         filter.addAction(DELAYED_KEYGUARD_ACTION);
+         filter.addAction(DELAYED_LOCK_PROFILE_ACTION);
+         filter.addAction(Intent.ACTION_SHUTDOWN);
+         mContext.registerReceiver(mBroadcastReceiver, filter);
  
          mKeyguardDisplayManager = new KeyguardDisplayManager(mContext);
  
@@@ -21,20 -21,20 +21,24 @@@ import android.content.ContentResolver
  import android.content.Context;
  import android.content.Intent;
  import android.content.IntentFilter;
+ import android.content.res.Resources;
  import android.database.ContentObserver;
 +import android.media.Ringtone;
 +import android.media.RingtoneManager;
 +import android.net.Uri;
  import android.os.BatteryManager;
  import android.os.Handler;
+ import android.os.HardwarePropertiesManager;
  import android.os.PowerManager;
  import android.os.SystemClock;
  import android.os.UserHandle;
 +import android.os.Vibrator;
  import android.provider.Settings;
+ import android.text.format.DateUtils;
  import android.util.Log;
  import android.util.Slog;
+ import com.android.internal.logging.MetricsLogger;
+ import com.android.systemui.R;
  import com.android.systemui.SystemUI;
  import com.android.systemui.statusbar.phone.PhoneStatusBar;
  
@@@ -63,11 -65,15 +71,18 @@@ public class PowerUI extends SystemUI 
  
      private long mScreenOffTime = -1;
  
+     private float mThresholdTemp;
+     private float[] mRecentTemps = new float[MAX_RECENT_TEMPS];
+     private int mNumTemps;
+     private long mNextLogTime;
 +    // For filtering ACTION_POWER_DISCONNECTED on boot
 +    private boolean mIgnoredFirstPowerBroadcast;
 +
      public void start() {
          mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
+         mHardwarePropertiesManager = (HardwarePropertiesManager)
+                 mContext.getSystemService(Context.HARDWARE_PROPERTIES_SERVICE);
          mScreenOffTime = mPowerManager.isScreenOn() ? -1 : SystemClock.elapsedRealtime();
          mWarnings = new PowerNotificationWarnings(mContext, getComponent(PhoneStatusBar.class));
  
          }
      };
  
 +    private void playPowerNotificationSound() {
 +        String soundPath = CMSettings.Global.getString(mContext.getContentResolver(),
 +                CMSettings.Global.POWER_NOTIFICATIONS_RINGTONE);
 +
 +        if (soundPath != null && !soundPath.equals("silent")) {
 +            Ringtone powerRingtone = RingtoneManager.getRingtone(mContext, Uri.parse(soundPath));
 +            if (powerRingtone != null) {
 +                powerRingtone.play();
 +            }
 +        }
 +
 +        if (CMSettings.Global.getInt(mContext.getContentResolver(),
 +                CMSettings.Global.POWER_NOTIFICATIONS_VIBRATE, 0) == 1) {
 +            Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
 +            if (vibrator != null) {
 +                vibrator.vibrate(250);
 +            }
 +        }
 +    }
 +
+     private void initTemperatureWarning() {
+         ContentResolver resolver = mContext.getContentResolver();
+         Resources resources = mContext.getResources();
+         if (Settings.Global.getInt(resolver, Settings.Global.SHOW_TEMPERATURE_WARNING,
+                 resources.getInteger(R.integer.config_showTemperatureWarning)) == 0) {
+             return;
+         }
+         mThresholdTemp = Settings.Global.getFloat(resolver, Settings.Global.WARNING_TEMPERATURE,
+                 resources.getInteger(R.integer.config_warningTemperature));
+         if (mThresholdTemp < 0f) {
+             // Get the throttling temperature. No need to check if we're not throttling.
+             float[] throttlingTemps = mHardwarePropertiesManager.getDeviceTemperatures(
+                     HardwarePropertiesManager.DEVICE_TEMPERATURE_SKIN,
+                     HardwarePropertiesManager.TEMPERATURE_THROTTLING);
+             if (throttlingTemps == null
+                     || throttlingTemps.length == 0
+                     || throttlingTemps[0] == HardwarePropertiesManager.UNDEFINED_TEMPERATURE) {
+                 return;
+             }
+             mThresholdTemp = throttlingTemps[0];
+         }
+         setNextLogTime();
+         // We have passed all of the checks, start checking the temp
+         updateTemperatureWarning();
+     }
+     private void updateTemperatureWarning() {
+         float[] temps = mHardwarePropertiesManager.getDeviceTemperatures(
+                 HardwarePropertiesManager.DEVICE_TEMPERATURE_SKIN,
+                 HardwarePropertiesManager.TEMPERATURE_CURRENT);
+         if (temps.length != 0) {
+             float temp = temps[0];
+             mRecentTemps[mNumTemps++] = temp;
+             PhoneStatusBar phoneStatusBar = getComponent(PhoneStatusBar.class);
+             if (phoneStatusBar != null && !phoneStatusBar.isDeviceInVrMode()
+                     && temp >= mThresholdTemp) {
+                 logAtTemperatureThreshold(temp);
+                 mWarnings.showTemperatureWarning();
+             } else {
+                 mWarnings.dismissTemperatureWarning();
+             }
+         }
+         logTemperatureStats();
+         mHandler.postDelayed(this::updateTemperatureWarning, TEMPERATURE_INTERVAL);
+     }
+     private void logAtTemperatureThreshold(float temp) {
+         StringBuilder sb = new StringBuilder();
+         sb.append("currentTemp=").append(temp)
+                 .append(",thresholdTemp=").append(mThresholdTemp)
+                 .append(",batteryStatus=").append(mBatteryStatus)
+                 .append(",recentTemps=");
+         for (int i = 0; i < mNumTemps; i++) {
+             sb.append(mRecentTemps[i]).append(',');
+         }
+         Slog.i(TAG, sb.toString());
+     }
+     /**
+      * Calculates and logs min, max, and average
+      * {@link HardwarePropertiesManager#DEVICE_TEMPERATURE_SKIN} over the past
+      * {@link #TEMPERATURE_LOGGING_INTERVAL}.
+      */
+     private void logTemperatureStats() {
+         if (mNextLogTime > System.currentTimeMillis() && mNumTemps != MAX_RECENT_TEMPS) {
+             return;
+         }
+         if (mNumTemps > 0) {
+             float sum = mRecentTemps[0], min = mRecentTemps[0], max = mRecentTemps[0];
+             for (int i = 1; i < mNumTemps; i++) {
+                 float temp = mRecentTemps[i];
+                 sum += temp;
+                 if (temp > max) {
+                     max = temp;
+                 }
+                 if (temp < min) {
+                     min = temp;
+                 }
+             }
+             float avg = sum / mNumTemps;
+             Slog.i(TAG, "avg=" + avg + ",min=" + min + ",max=" + max);
+             MetricsLogger.histogram(mContext, "device_skin_temp_avg", (int) avg);
+             MetricsLogger.histogram(mContext, "device_skin_temp_min", (int) min);
+             MetricsLogger.histogram(mContext, "device_skin_temp_max", (int) max);
+         }
+         setNextLogTime();
+         mNumTemps = 0;
+     }
+     private void setNextLogTime() {
+         mNextLogTime = System.currentTimeMillis() + TEMPERATURE_LOGGING_INTERVAL;
+     }
      public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
          pw.print("mLowBatteryAlertCloseLevel=");
          pw.println(mLowBatteryAlertCloseLevel);
@@@ -234,21 -230,15 +234,21 @@@ public class ScreenPinningRequest imple
                          .setVisibility(View.INVISIBLE);
              }
  
-             final int description;
 -            boolean touchExplorationEnabled = mAccessibilityService.isTouchExplorationEnabled();
 -            ((TextView) mLayout.findViewById(R.id.screen_pinning_description))
 +            if (hasNavigationBar()) {
-                 description = R.string.screen_pinning_description;
-                 final int backBgVisibility =
-                         mAccessibilityService.isEnabled() ? View.INVISIBLE : View.VISIBLE;
++                boolean touchExplorationEnabled = mAccessibilityService.isTouchExplorationEnabled();
++                ((TextView) mLayout.findViewById(R.id.screen_pinning_description))
+                     .setText(touchExplorationEnabled
+                             ? R.string.screen_pinning_description_accessible
+                             : R.string.screen_pinning_description);
 -            final int backBgVisibility = touchExplorationEnabled ? View.INVISIBLE : View.VISIBLE;
 -            mLayout.findViewById(R.id.screen_pinning_back_bg).setVisibility(backBgVisibility);
 -            mLayout.findViewById(R.id.screen_pinning_back_bg_light).setVisibility(backBgVisibility);
++                final int backBgVisibility = touchExplorationEnabled ? View.INVISIBLE : View.VISIBLE;
 +                mLayout.findViewById(R.id.screen_pinning_back_bg).setVisibility(backBgVisibility);
 +                mLayout.findViewById(R.id.screen_pinning_back_bg_light).setVisibility(backBgVisibility);
 +            } else {
-                 description = R.string.screen_pinning_description_no_navbar;
 +                ((ViewGroup) buttons.getParent()).removeView(buttons);
++                ((TextView) mLayout.findViewById(R.id.screen_pinning_description))
++                        .setText(R.string.screen_pinning_description_no_navbar);
 +            }
  
-             ((TextView) mLayout.findViewById(R.id.screen_pinning_description))
-                     .setText(description);
              addView(mLayout, getRequestLayoutParams(isLandscape));
          }
  
@@@ -119,11 -120,9 +121,12 @@@ import java.util.HashSet
  import java.util.List;
  import java.util.Locale;
  import java.util.Set;
+ import java.util.Stack;
  
  import static android.service.notification.NotificationListenerService.Ranking.IMPORTANCE_HIGH;
 +import static android.service.notification.NotificationListenerService.Ranking.IMPORTANCE_MIN;
 +import static android.service.notification.NotificationListenerService.Ranking.IMPORTANCE_VERY_LOW;
 +import static android.service.notification.NotificationListenerService.Ranking.importanceToLevel;
  
  public abstract class BaseStatusBar extends SystemUI implements
          CommandQueue.Callbacks, ActivatableNotificationView.OnActivatedListener,
@@@ -74,8 -68,11 +68,12 @@@ public class ButtonDispatcher implement
              ((ButtonInterface) view).setImageResource(mImageResource);
          } else if (mImageDrawable != null) {
              ((ButtonInterface) view).setImageDrawable(mImageDrawable);
 +            updateDrawable();
          }
+         if (view instanceof  ButtonInterface) {
+             ((ButtonInterface) view).setVertical(mVertical);
+         }
      }
  
      public int getId() {
          }
      }
  
 +    private void updateDrawable() {
 +        mImageDrawable.setCallback(this);
 +        // one of our buttons will always be visible
 +        mImageDrawable.setVisible(true, false);
 +    }
 +
 +    @Override
 +    public void invalidateDrawable(Drawable who) {
 +        final int N = mViews.size();
 +        for (int i = 0; i < N; i++) {
 +            mViews.get(i).invalidateDrawable(who);
 +        }
 +    }
 +
 +    @Override
 +    public void scheduleDrawable(Drawable who, Runnable what, long when) {
 +        final int N = mViews.size();
 +        for (int i = 0; i < N; i++) {
 +            mViews.get(i).scheduleDrawable(who, what, when);
 +        }
 +    }
 +
 +    @Override
 +    public void unscheduleDrawable(Drawable who, Runnable what) {
 +        final int N = mViews.size();
 +        for (int i = 0; i < N; i++) {
 +            mViews.get(i).unscheduleDrawable(who, what);
 +        }
 +    }
 +
+     public void setVertical(boolean vertical) {
+         mVertical = vertical;
+         final int N = mViews.size();
+         for (int i = 0; i < N; i++) {
+             final View view = mViews.get(i);
+             if (view instanceof ButtonInterface) {
+                 ((ButtonInterface) view).setVertical(vertical);
+             }
+         }
+     }
      /**
       * Interface for button actions.
       */
@@@ -246,25 -250,12 +252,16 @@@ public class NavigationBarInflaterView 
          View v = null;
          if (HOME.equals(button)) {
              v = inflater.inflate(R.layout.home, parent, false);
-             if (landscape && isSw600Dp()) {
-                 setupLandButton(v);
-             }
          } else if (BACK.equals(button)) {
              v = inflater.inflate(R.layout.back, parent, false);
-             if (landscape && isSw600Dp()) {
-                 setupLandButton(v);
-             }
          } else if (RECENT.equals(button)) {
              v = inflater.inflate(R.layout.recent_apps, parent, false);
-             if (landscape && isSw600Dp()) {
-                 setupLandButton(v);
-             }
          } else if (MENU_IME.equals(button)) {
              v = inflater.inflate(R.layout.menu_ime, parent, false);
 +        } else if (MENU_IME_ALWAYS_SHOW.equals(button)) {
 +            v = inflater.inflate(R.layout.menu_ime_always_show, parent, false);
 +        } else if (SEARCH.equals(button)) {
 +            v = inflater.inflate(R.layout.search, parent, false);
          } else if (NAVSPACE.equals(button)) {
              v = inflater.inflate(R.layout.nav_key_space, parent, false);
          } else if (CLIPBOARD.equals(button)) {
@@@ -592,7 -565,7 +592,8 @@@ public class NavigationBarView extends 
          getImeSwitchButton().setOnClickListener(mImeSwitcherClickListener);
  
          mDeadZone = (DeadZone) mCurrentView.findViewById(R.id.deadzone);
+         mDeadZone.setDisplayRotation(mCurrentRotation);
 +        mDeadZone.setStartFromRight(mLeftInLandscape);
  
          // force the low profile & disabled states into compliance
          mBarTransitions.init();
@@@ -63,14 -61,9 +63,15 @@@ import com.android.systemui.statusbar.S
  import com.android.systemui.statusbar.notification.NotificationUtils;
  import com.android.systemui.statusbar.policy.HeadsUpManager;
  import com.android.systemui.statusbar.policy.KeyguardUserSwitcher;
+ import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener;
 +import com.android.systemui.statusbar.policy.WeatherController;
 +import com.android.systemui.statusbar.policy.WeatherControllerImpl;
  import com.android.systemui.statusbar.stack.NotificationStackScrollLayout;
  import com.android.systemui.statusbar.stack.StackStateAnimator;
 +import com.android.systemui.tuner.TunerService;
 +
 +import cyanogenmod.providers.CMSettings;
 +import cyanogenmod.weather.util.WeatherUtils;
  
  import java.util.List;
  
@@@ -80,7 -71,7 +81,7 @@@ public class NotificationPanelView exte
          ExpandableView.OnHeightChangedListener,
          View.OnClickListener, NotificationStackScrollLayout.OnOverscrollTopChangedListener,
          KeyguardAffordanceHelper.Callback, NotificationStackScrollLayout.OnEmptySpaceClickListener,
-         HeadsUpManager.OnHeadsUpChangedListener, WeatherController.Callback, TunerService.Tunable {
 -        OnHeadsUpChangedListener {
++        OnHeadsUpChangedListener, WeatherController.Callback, TunerService.Tunable {
  
      private static final boolean DEBUG = false;
  
@@@ -117,9 -113,9 +118,10 @@@ import android.view.ViewStub
  import android.view.ViewTreeObserver;
  import android.view.WindowManager;
  import android.view.WindowManagerGlobal;
+ import android.view.accessibility.AccessibilityEvent;
  import android.view.animation.AccelerateInterpolator;
  import android.view.animation.Interpolator;
 +import android.widget.FrameLayout;
  import android.widget.ImageView;
  import android.widget.TextView;
  
@@@ -176,7 -168,7 +178,8 @@@ import com.android.systemui.statusbar.R
  import com.android.systemui.statusbar.ScrimView;
  import com.android.systemui.statusbar.SignalClusterView;
  import com.android.systemui.statusbar.StatusBarState;
 +import com.android.systemui.statusbar.VisualizerView;
+ import com.android.systemui.statusbar.notification.VisualStabilityManager;
  import com.android.systemui.statusbar.phone.UnlockMethodCache.OnUnlockMethodChangedListener;
  import com.android.systemui.statusbar.policy.AccessibilityController;
  import com.android.systemui.statusbar.policy.BatteryController;
@@@ -207,8 -199,6 +212,7 @@@ import com.android.systemui.statusbar.s
  import com.android.systemui.statusbar.stack.NotificationStackScrollLayout
          .OnChildLocationsChangedListener;
  import com.android.systemui.statusbar.stack.StackStateAnimator;
- import com.android.systemui.statusbar.stack.StackViewState;
 +import com.android.systemui.tuner.TunerService;
  import com.android.systemui.volume.VolumeComponent;
  
  import java.io.FileDescriptor;
@@@ -221,13 -211,9 +225,13 @@@ import java.util.HashMap
  import java.util.List;
  import java.util.Map;
  
 +import cyanogenmod.providers.CMSettings;
 +
 +import static android.service.notification.NotificationListenerService.Ranking.importanceToLevel;
 +
  public class PhoneStatusBar extends BaseStatusBar implements DemoMode,
          DragDownHelper.DragDownCallback, ActivityStarter, OnUnlockMethodChangedListener,
-         HeadsUpManager.OnHeadsUpChangedListener, TunerService.Tunable {
 -        OnHeadsUpChangedListener, VisualStabilityManager.Callback {
++        OnHeadsUpChangedListener, VisualStabilityManager.Callback, TunerService.Tunable {
      static final String TAG = "PhoneStatusBar";
      public static final boolean DEBUG = BaseStatusBar.DEBUG;
      public static final boolean SPEW = false;
          filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
          filter.addAction(Intent.ACTION_SCREEN_OFF);
          filter.addAction(Intent.ACTION_SCREEN_ON);
+         filter.addAction(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
 +        filter.addAction(cyanogenmod.content.Intent.ACTION_SCREEN_CAMERA_GESTURE);
          context.registerReceiverAsUser(mBroadcastReceiver, UserHandle.ALL, filter, null, null);
  
          IntentFilter demoFilter = new IntentFilter();
                  resetUserExpandedStates();
              }
              else if (Intent.ACTION_SCREEN_ON.equals(action)) {
 +                mScreenOn = true;
                  notifyNavigationBarScreenOn(true);
 +            } else if (cyanogenmod.content.Intent.ACTION_SCREEN_CAMERA_GESTURE.equals(action)) {
 +                boolean userSetupComplete = Settings.Secure.getInt(mContext.getContentResolver(),
 +                        Settings.Secure.USER_SETUP_COMPLETE, 0) != 0;
 +                if (!userSetupComplete) {
 +                    if (DEBUG) Log.d(TAG, String.format(
 +                            "userSetupComplete = %s, ignoring camera launch gesture.",
 +                            userSetupComplete));
 +                    return;
 +                }
 +
 +                onCameraLaunchGestureDetected(StatusBarManager.CAMERA_LAUNCH_SOURCE_SCREEN_GESTURE);
              }
+             else if (DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG.equals(action)) {
+                 mQSPanel.showDeviceMonitoringDialog();
+             }
          }
      };
  
              maybeEscalateHeadsUp();
          }
          mState = state;
 +        mVisualizerView.setStatusBarState(state);
          mGroupManager.setStatusBarState(state);
+         mHeadsUpManager.setStatusBarState(state);
          mFalsingManager.setStatusBarState(state);
          mStatusBarWindowManager.setStatusBarState(state);
          updateReportRejectedTouchVisibility();
@@@ -24,11 -23,9 +24,12 @@@ import android.content.Intent
  import android.content.res.Configuration;
  import android.graphics.drawable.Drawable;
  import android.graphics.drawable.RippleDrawable;
 +import android.net.Uri;
  import android.os.UserManager;
 +import android.provider.AlarmClock;
 +import android.provider.CalendarContract;
  import android.util.AttributeSet;
+ import android.util.SparseBooleanArray;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.view.ViewGroup;
@@@ -281,9 -273,10 +289,9 @@@ public class QuickStatusBarHeader exten
      protected void updateVisibilities() {
          updateAlarmVisibilities();
          updateDateTimePosition();
-         mEmergencyOnly.setVisibility(mExpanded && mShowEmergencyCallsOnly
+         mEmergencyOnly.setVisibility(mExpanded && (mShowEmergencyCallsOnly || mIsRoaming)
                  ? View.VISIBLE : View.INVISIBLE);
 -        mSettingsContainer.findViewById(R.id.tuner_icon).setVisibility(
 -                TunerService.isTunerEnabled(mContext) ? View.VISIBLE : View.INVISIBLE);
 +        mSettingsContainer.findViewById(R.id.tuner_icon).setVisibility(View.INVISIBLE);
          final boolean isDemo = UserManager.isDeviceInDemoMode(mContext);
          mMultiUserSwitch.setVisibility(mExpanded && mMultiUserSwitch.hasMultipleUsers() && !isDemo
                  ? View.VISIBLE : View.INVISIBLE);
@@@ -53,8 -54,8 +54,9 @@@ public class DeadZone extends View 
      // mHold ms, then move back over the course of mDecay ms
      private int mHold, mDecay;
      private boolean mVertical;
 +    private boolean mStartFromRight;
      private long mLastPokeTime;
+     private int mDisplayRotation;
  
      private final Runnable mDebugFlash = new Runnable() {
          @Override
@@@ -785,12 -785,13 +785,14 @@@ public class NetworkControllerImpl exte
                              datatype.equals("e") ? TelephonyIcons.E :
                              datatype.equals("g") ? TelephonyIcons.G :
                              datatype.equals("h") ? TelephonyIcons.H :
 +                            datatype.equals("h+") ? TelephonyIcons.HP :
                              datatype.equals("lte") ? TelephonyIcons.LTE :
                              datatype.equals("lte+") ? TelephonyIcons.LTE_PLUS :
-                             datatype.equals("roam") ? TelephonyIcons.ROAMING :
                              TelephonyIcons.UNKNOWN;
                  }
+                 if (args.containsKey("roam")) {
+                     controller.getState().roaming = "show".equals(args.getString("roam"));
+                 }
                  int[][] icons = TelephonyIcons.TELEPHONY_SIGNAL_STRENGTH;
                  String level = args.getString("level");
                  if (level != null) {
@@@ -2213,10 -2213,39 +2213,44 @@@ message MetricsEvent 
  
      // ---- End N-MR1 Constants, all N-MR1 constants go above this line ----
  
-     QS_NFC = 497;
+     // ACTION: The lockscreen gets shown because the SIM card was removed
+     // SUBTYPE: false: device was previously unlocked, true: device was previously locked
+     // CATEGORY: GLOBAL_SYSTEM_UI
+     // OS: N-MR2
+     ACTION_LOCK_BECAUSE_SIM_REMOVED = 497;
+     // ACTION: QS Brightness Slider (with auto brightness disabled, and VR enabled)
+     //   SUBTYPE: slider value
+     // CATEGORY: QUICK_SETTINGS
+     // OS: 6.0
+     ACTION_BRIGHTNESS_FOR_VR = 498;
 +    // OPEN: QS NFC tile shown
 +    // ACTION: QS NFC tile tapped
 +    // CATEGORY: QUICK_SETTINGS
++    QS_NFC = 499;
++
+     // ACTION: A captive portal was detected during network validation
+     // CATEGORY: NOTIFICATION
+     // OS: N-MR2
+     NOTIFICATION_NETWORK_SIGN_IN = 740;
+     // ACTION: An unvalidated network without Internet was selected by the user
+     // CATEGORY: NOTIFICATION
+     // OS: N-MR2
+     NOTIFICATION_NETWORK_NO_INTERNET = 741;
+     // ACTION: A validated network failed revalidation and lost Internet access
+     // CATEGORY: NOTIFICATION
+     // OS: N-MR2
+     NOTIFICATION_NETWORK_LOST_INTERNET = 742;
+     // ACTION: The system default network switched to a different network
+     // CATEGORY: NOTIFICATION
+     // OS: N-MR2
+     NOTIFICATION_NETWORK_SWITCH = 743;
+     // ---- End N-MR2 Constants, all N-MR2 constants go above this line ----
  
      // Add new aosp constants above this line.
      // END OF AOSP CONSTANTS
Simple merge
@@@ -659,27 -707,32 +712,39 @@@ class BluetoothManagerService extends I
          return true;
      }
  
-     public boolean enable(String callingPackage) {
-         if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
-             (!checkIfCallerIsForegroundUser())) {
-             Slog.w(TAG,"enable(): not allowed for non-active and non system user");
-             return false;
+     public boolean enable(String packageName) throws RemoteException {
+         final int callingUid = Binder.getCallingUid();
+         final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
+         if (!callerSystem) {
+             if (!checkIfCallerIsForegroundUser()) {
+                 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
+                 return false;
+             }
+             mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
+                     "Need BLUETOOTH ADMIN permission");
+             if (!isEnabled() && mPermissionReviewRequired
+                     && startConsentUiIfNeeded(packageName, callingUid,
+                             BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
+                 return false;
+             }
          }
  
-         mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
-                                                 "Need BLUETOOTH ADMIN permission");
          if (DBG) {
-             Slog.d(TAG,"enable():  mBluetooth =" + mBluetooth +
-                     " mBinding = " + mBinding + " mState = " + mState);
+             Slog.d(TAG,"enable(" + packageName + "):  mBluetooth =" + mBluetooth +
+                     " mBinding = " + mBinding + " mState = " +
+                     BluetoothAdapter.nameForState(mState));
          }
  
-         int callingUid = Binder.getCallingUid();
 +        AppOpsManager appOps = (AppOpsManager) mContext
 +                .getSystemService(Context.APP_OPS_SERVICE);
-                 callingPackage) != AppOpsManager.MODE_ALLOWED)
++
 +        if (appOps.noteOp(AppOpsManager.OP_BLUETOOTH_CHANGE, callingUid,
++                packageName) != AppOpsManager.MODE_ALLOWED)
 +            return false;
 +
          synchronized(mReceiver) {
              mQuietEnableExternal = false;
              mEnableExternal = true;
                      if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
                              (newState == BluetoothAdapter.STATE_OFF) &&
                              (mBluetooth != null) && mEnable) {
-                         recoverBluetoothServiceFromError();
+                         recoverBluetoothServiceFromError(false);
                      }
                      if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
 -                            (newState == BluetoothAdapter.STATE_BLE_ON) &&
 +                            (newState == BluetoothAdapter.STATE_OFF) &&
                              (mBluetooth != null) && mEnable) {
-                         recoverBluetoothServiceFromError();
 +                         persistBluetoothSetting(BLUETOOTH_OFF);
 +                    }
 +                    if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
 +                           (newState == BluetoothAdapter.STATE_BLE_ON) &&
 +                           (mBluetooth != null) && mEnable) {
+                         recoverBluetoothServiceFromError(true);
                      }
                      // If we tried to enable BT while BT was in the process of shutting down,
                      // wait for the BT process to fully tear down and then force a restart
          return false;
      }
  
-     private void sendDisableMsg() {
 +    /**
 +     *  if on is true, wait for state become ON
 +     *  if off is true, wait for state become OFF
 +     *  if both on and off are false, wait for state not ON
 +     */
 +    private boolean waitForMonitoredOnOff(boolean on, boolean off) {
 +        int i = 0;
 +        while (i < 16) {
 +            synchronized(mConnection) {
 +                try {
 +                    if (mBluetooth == null) break;
 +                    if (on) {
 +                        if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
 +                        if (mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
 +                            bluetoothStateChangeHandler(BluetoothAdapter.STATE_BLE_TURNING_ON,
 +                                                        BluetoothAdapter.STATE_BLE_ON);
 +                        }
 +                    } else if (off) {
 +                        if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
 +                        if (mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON)
 +                            bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
 +                                                        BluetoothAdapter.STATE_BLE_ON);
 +                    } else {
 +                        if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
 +                    }
 +                } catch (RemoteException e) {
 +                    Slog.e(TAG, "getState()", e);
 +                    break;
 +                }
 +            }
 +            if (on || off) {
 +                SystemClock.sleep(500);
 +            } else {
 +                SystemClock.sleep(30);
 +            }
 +            i++;
 +        }
 +        Slog.e(TAG,"waitForOnOff time out");
 +        return false;
 +    }
 +
+     private void sendDisableMsg(String packageName) {
          mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
+         addActiveLog(packageName, false);
      }
  
-     private void sendEnableMsg(boolean quietMode) {
+     private void sendEnableMsg(boolean quietMode, String packageName) {
          mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
                               quietMode ? 1 : 0, 0));
+         addActiveLog(packageName, true);
      }
  
-     private void recoverBluetoothServiceFromError() {
+     private void addActiveLog(String packageName, boolean enable) {
+         synchronized (mActiveLogs) {
+             if (mActiveLogs.size() > 10) {
+                 mActiveLogs.remove();
+             }
+             mActiveLogs.add(new ActiveLog(packageName, enable, System.currentTimeMillis()));
+         }
+     }
+     private void recoverBluetoothServiceFromError(boolean clearBle) {
          Slog.e(TAG,"recoverBluetoothServiceFromError");
          try {
              mBluetoothLock.readLock().lock();
@@@ -1551,14 -1546,9 +1560,14 @@@ public final class ActivityManagerServi
      static final int NOTIFY_PINNED_STACK_ANIMATION_ENDED_LISTENERS_MSG = 66;
      static final int NOTIFY_FORCED_RESIZABLE_MSG = 67;
      static final int NOTIFY_ACTIVITY_DISMISSING_DOCKED_STACK_MSG = 68;
-     static final int VR_MODE_APPLY_IF_NEEDED_MSG = 69;
-     static final int SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG = 70;
+     static final int SHOW_UNSUPPORTED_DISPLAY_SIZE_DIALOG_MSG = 69;
+     static final int NOTIFY_VR_SLEEPING_MSG = 70;
  
 +    static final int POST_PRIVACY_NOTIFICATION_MSG = 90;
 +    static final int CANCEL_PRIVACY_NOTIFICATION_MSG = 91;
 +    static final int POST_COMPONENT_PROTECTED_MSG = 92;
 +    static final int CANCEL_PROTECTED_APP_NOTIFICATION = 93;
 +
      static final int FIRST_ACTIVITY_STACK_MSG = 100;
      static final int FIRST_BROADCAST_QUEUE_MSG = 200;
      static final int FIRST_COMPAT_MODE_MSG = 300;
                      }
                  }
                  vrService.setVrMode(vrMode, requestedPackage, userId, callingPackage);
-             } break;
-             case VR_MODE_APPLY_IF_NEEDED_MSG: {
-                 final ActivityRecord r = (ActivityRecord) msg.obj;
-                 final boolean needsVrMode = r != null && r.requestedVrComponent != null;
-                 if (needsVrMode) {
-                     applyVrMode(msg.arg1 == 1, r.requestedVrComponent, r.userId,
-                             r.info.getComponentName(), false);
-                 }
+             } case NOTIFY_VR_SLEEPING_MSG: {
+                 notifyVrManagerOfSleepState(msg.arg1 != 0);
              } break;
 +            case POST_COMPONENT_PROTECTED_MSG: {
 +                INotificationManager inm = NotificationManager.getService();
 +                if (inm == null) {
 +                    return;
 +                }
 +
 +                Intent targetIntent = (Intent) msg.obj;
 +                if (targetIntent == null) {
 +                    return;
 +                }
 +
 +                int currentUserId = mUserController.getCurrentUserIdLocked();
 +                int targetUserId = targetIntent.getIntExtra(
 +                        "com.android.settings.PROTECTED_APPS_USER_ID", currentUserId);
 +                // Resolve for labels and whatnot
 +                ActivityInfo root = resolveActivityInfo(targetIntent, targetIntent.getFlags(),
 +                        targetUserId);
 +
 +                try {
 +                    Intent protectedAppIntent = new Intent();
 +                    protectedAppIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
 +                    protectedAppIntent.setComponent(
 +                            new ComponentName("com.android.settings",
 +                                    "com.android.settings.applications.ProtectedAppsActivity"));
 +                    protectedAppIntent.putExtra(
 +                            "com.android.settings.PROTECTED_APP_TARGET_INTENT",
 +                            targetIntent);
 +                    Context context = mContext.createPackageContext("com.android.settings", 0);
 +                    String title = mContext.getString(
 +                            com.android.internal.R.string
 +                                    .notify_package_component_protected_title);
 +                    String text = mContext.getString(
 +                            com.android.internal.R.string
 +                                    .notify_package_component_protected_text,
 +                            root.applicationInfo.loadLabel(mContext.getPackageManager()));
 +                    Notification notification = new Notification.Builder(context)
 +                            .setSmallIcon(com.android.internal.R.drawable.stat_notify_protected)
 +                            .setWhen(0)
 +                            .setTicker(title)
 +                            .setColor(mContext.getColor(
 +                                    com.android.internal.R.color
 +                                            .system_notification_accent_color))
 +                            .setContentTitle(title)
 +                            .setContentText(text)
 +                            .setDefaults(Notification.DEFAULT_VIBRATE)
 +                            .setPriority(Notification.PRIORITY_MAX)
 +                            .setStyle(new Notification.BigTextStyle().bigText(text))
 +                            .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0,
 +                                    protectedAppIntent, PendingIntent.FLAG_CANCEL_CURRENT, null,
 +                                    new UserHandle(currentUserId)))
 +                            .build();
 +                    try {
 +                        int[] outId = new int[1];
 +                        inm.cancelNotificationWithTag("android", null,
 +                                R.string.notify_package_component_protected_title, msg.arg1);
 +                        inm.enqueueNotificationWithTag("android", "android", null,
 +                                R.string.notify_package_component_protected_title,
 +                                notification, outId, currentUserId);
 +                    } catch (RuntimeException e) {
 +                        Slog.w(ActivityManagerService.TAG,
 +                                "Error showing notification for protected app component", e);
 +                    } catch (RemoteException e) {
 +                    }
 +                } catch (NameNotFoundException e) {
 +                    Slog.w(TAG, "Unable to create context for protected app notification", e);
 +                }
 +            } break;
 +            case CANCEL_PROTECTED_APP_NOTIFICATION: {
 +                INotificationManager inm = NotificationManager.getService();
 +                if (inm == null) {
 +                    return;
 +                }
 +                try {
 +                    inm.cancelNotificationWithTag("android", null,
 +                            R.string.notify_package_component_protected_title, msg.arg1);
 +                } catch (RuntimeException e) {
 +                    Slog.w(ActivityManagerService.TAG,
 +                            "Error canceling notification for service", e);
 +                } catch (RemoteException e) {
 +                }
 +            } break;
              }
          }
      };
          int nextCachedAdj = curCachedAdj+1;
          int curEmptyAdj = ProcessList.CACHED_APP_MIN_ADJ;
          int nextEmptyAdj = curEmptyAdj+2;
 +        ProcessRecord selectedAppRecord = null;
 +        long serviceLastActivity = 0;
 +        int numBServices = 0;
          for (int i=N-1; i>=0; i--) {
              ProcessRecord app = mLruProcesses.get(i);
+             if (app == null) {
+                 continue;
+             }
 +            if (mEnableBServicePropagation && app.serviceb
 +                    && (app.curAdj == ProcessList.SERVICE_B_ADJ)) {
 +                numBServices++;
 +                for (int s = app.services.size() - 1; s >= 0; s--) {
 +                    ServiceRecord sr = app.services.valueAt(s);
 +                    if (DEBUG_OOM_ADJ) Slog.d(TAG,"app.processName = " + app.processName
 +                            + " serviceb = " + app.serviceb + " s = " + s + " sr.lastActivity = "
 +                            + sr.lastActivity + " packageName = " + sr.packageName
 +                            + " processName = " + sr.processName);
 +                    if (SystemClock.uptimeMillis() - sr.lastActivity
 +                            < mMinBServiceAgingTime) {
 +                        if (DEBUG_OOM_ADJ) {
 +                            Slog.d(TAG,"Not aged enough!!!");
 +                        }
 +                        continue;
 +                    }
 +                    if (serviceLastActivity == 0) {
 +                        serviceLastActivity = sr.lastActivity;
 +                        selectedAppRecord = app;
 +                    } else if (sr.lastActivity < serviceLastActivity) {
 +                        serviceLastActivity = sr.lastActivity;
 +                        selectedAppRecord = app;
 +                    }
 +                }
 +            }
 +            if (DEBUG_OOM_ADJ && selectedAppRecord != null) Slog.d(TAG,
 +                    "Identified app.processName = " + selectedAppRecord.processName
 +                    + " app.pid = " + selectedAppRecord.pid);
              if (!app.killedByAm && app.thread != null) {
                  app.procStateChanged = false;
                  computeOomAdjLocked(app, ProcessList.UNKNOWN_ADJ, TOP_APP, true, now);
@@@ -192,23 -188,22 +200,24 @@@ class AutomaticBrightnessController 
      public AutomaticBrightnessController(Callbacks callbacks, Looper looper,
              SensorManager sensorManager, Spline autoBrightnessSpline, int lightSensorWarmUpTime,
              int brightnessMin, int brightnessMax, float dozeScaleFactor,
-             int lightSensorRate, long brighteningLightDebounceConfig,
+             int lightSensorRate, int initialLightSensorRate, long brighteningLightDebounceConfig,
 +            long brighteningLightFastDebounceConfig,
              long darkeningLightDebounceConfig, boolean resetAmbientLuxAfterWarmUpConfig,
-             int ambientLightHorizon, float autoBrightnessAdjustmentMaxGamma ) {
+             int ambientLightHorizon, float autoBrightnessAdjustmentMaxGamma,
+             boolean activeDozeLightSensor, boolean useNewSensorSamplesForDoze,
+             LuxLevels luxLevels) {
          mCallbacks = callbacks;
-         mTwilight = LocalServices.getService(TwilightManager.class);
          mSensorManager = sensorManager;
          mScreenAutoBrightnessSpline = autoBrightnessSpline;
          mScreenBrightnessRangeMinimum = brightnessMin;
          mScreenBrightnessRangeMaximum = brightnessMax;
          mLightSensorWarmUpTimeConfig = lightSensorWarmUpTime;
          mDozeScaleFactor = dozeScaleFactor;
-         mLightSensorRate = lightSensorRate;
+         mNormalLightSensorRate = lightSensorRate;
+         mInitialLightSensorRate = initialLightSensorRate;
+         mCurrentLightSensorRate = -1;
          mBrighteningLightDebounceConfig = brighteningLightDebounceConfig;
 +        mBrighteningLightFastDebounceConfig = brighteningLightFastDebounceConfig;
          mDarkeningLightDebounceConfig = darkeningLightDebounceConfig;
          mResetAmbientLuxAfterWarmUpConfig = resetAmbientLuxAfterWarmUpConfig;
          mAmbientLightHorizon = ambientLightHorizon;
      private void handleLightSensorEvent(long time, float lux) {
          mHandler.removeMessages(MSG_UPDATE_AMBIENT_LUX);
  
 +        if (DEBUG) Slog.d(TAG, "handleLightSensorEvent: time=" + time + ", lux=" + lux);
+         if (mAmbientLightRingBuffer.size() == 0) {
+             // switch to using the steady-state sample rate after grabbing the initial light sample
+             adjustLightSensorRate(mNormalLightSensorRate);
+         }
          applyLightSensorMeasurement(time, lux);
          updateAmbientLux(time);
+         if (mUseActiveDozeLightSensorConfig && mDozing) {
+             // disable the ambient light sensor and update the screen brightness
+             if (DEBUG) {
+                 Slog.d(TAG, "handleLightSensorEvent: doze ambient light sensor reading: " + lux);
+             }
+             setLightSensorEnabled(false);
+             updateAutoBrightness(true /*sendUpdate*/);
+         }
      }
  
      private void applyLightSensorMeasurement(long time, float lux) {
@@@ -315,10 -313,17 +318,19 @@@ final class DisplayPowerController impl
  
          int lightSensorRate = resources.getInteger(
                  com.android.internal.R.integer.config_autoBrightnessLightSensorRate);
+         int initialLightSensorRate = resources.getInteger(
+                 com.android.internal.R.integer.config_autoBrightnessInitialLightSensorRate);
+         if (initialLightSensorRate == -1) {
+           initialLightSensorRate = lightSensorRate;
+         } else if (initialLightSensorRate > lightSensorRate) {
+           Slog.w(TAG, "Expected config_autoBrightnessInitialLightSensorRate ("
+                   + initialLightSensorRate + ") to be less than or equal to "
+                   + "config_autoBrightnessLightSensorRate (" + lightSensorRate + ").");
+         }
          long brighteningLightDebounce = resources.getInteger(
                  com.android.internal.R.integer.config_autoBrightnessBrighteningLightDebounce);
 +        long brighteningLightFastDebounce = resources.getInteger(
 +                com.android.internal.R.integer.config_autoBrightnessBrighteningLightFastDebounce);
          long darkeningLightDebounce = resources.getInteger(
                  com.android.internal.R.integer.config_autoBrightnessDarkeningLightDebounce);
          boolean autoBrightnessResetAmbientLuxAfterWarmUp = resources.getBoolean(
                          handler.getLooper(), sensorManager, screenAutoBrightnessSpline,
                          lightSensorWarmUpTimeConfig, screenBrightnessRangeMinimum,
                          mScreenBrightnessRangeMaximum, dozeScaleFactor, lightSensorRate,
-                         brighteningLightDebounce, brighteningLightFastDebounce,
 -                        initialLightSensorRate, brighteningLightDebounce, darkeningLightDebounce,
 -                        autoBrightnessResetAmbientLuxAfterWarmUp, ambientLightHorizon,
 -                        autoBrightnessAdjustmentMaxGamma, mUseActiveDozeLightSensorConfig,
++                        initialLightSensorRate, brighteningLightDebounce, brighteningLightFastDebounce,
 +                        darkeningLightDebounce, autoBrightnessResetAmbientLuxAfterWarmUp,
-                         ambientLightHorizon, autoBrightnessAdjustmentMaxGamma);
++                        ambientLightHorizon, autoBrightnessAdjustmentMaxGamma, mUseActiveDozeLightSensorConfig,
+                         useNewSensorSamplesForDoze, luxLevels);
++
              }
          }
  
@@@ -137,8 -123,14 +142,14 @@@ public class LightsService extends Syst
          }
  
          private void setLightLocked(int color, int mode, int onMS, int offMS, int brightnessMode) {
-             if (!mLocked && (mModesUpdate || color != mColor || mode != mMode || onMS != mOnMS ||
-                     offMS != mOffMS || mBrightnessMode != brightnessMode || mReset)) {
+             if (shouldBeInLowPersistenceMode()) {
+                 brightnessMode = BRIGHTNESS_MODE_LOW_PERSISTENCE;
+             } else if (brightnessMode == BRIGHTNESS_MODE_LOW_PERSISTENCE) {
+                 brightnessMode = mLastBrightnessMode;
+             }
 -            if ((color != mColor || mode != mMode || onMS != mOnMS || offMS != mOffMS ||
++            if ((mModesUpdate || color != mColor || mode != mMode || onMS != mOnMS || offMS != mOffMS ||
+                     mBrightnessMode != brightnessMode)) {
                  if (DEBUG) Slog.v(TAG, "setLight #" + mId + ": color=#"
                          + Integer.toHexString(color) + ": brightnessMode=" + brightnessMode);
                  mLastColor = mColor;
                  mMode = mode;
                  mOnMS = onMS;
                  mOffMS = offMS;
-                 mLastBrightnessMode = mBrightnessMode;
                  mBrightnessMode = brightnessMode;
 +                mModesUpdate = false;
                  Trace.traceBegin(Trace.TRACE_TAG_POWER, "setLight(" + mId + ", 0x"
                          + Integer.toHexString(color) + ")");
                  try {
          private int mBrightnessMode;
          private int mLastBrightnessMode;
          private int mLastColor;
-         private boolean mLocked;
 +        private boolean mModesUpdate;
 +        private boolean mMultipleLeds;
 +        private boolean mReset = true;
+         private boolean mVrModeEnabled;
+         private boolean mUseLowPersistenceForVR;
      }
  
      public LightsService(Context context) {
@@@ -146,13 -140,8 +146,12 @@@ import com.android.server.lights.Lights
  import com.android.server.notification.ManagedServices.ManagedServiceInfo;
  import com.android.server.policy.PhoneWindowManager;
  import com.android.server.statusbar.StatusBarManagerInternal;
- import com.android.server.vr.VrManagerInternal;
  import com.android.server.notification.ManagedServices.UserProfiles;
  
 +import cyanogenmod.providers.CMSettings;
 +import cyanogenmod.util.ColorUtils;
 +
 +import cyanogenmod.providers.CMSettings;
  import libcore.io.IoUtils;
  
  import org.json.JSONException;
@@@ -759,10 -657,9 +767,13 @@@ public class PhoneWindowManager impleme
      // (See Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR.)
      int mIncallPowerBehavior;
  
 +    // Behavior of HOME button during an incoming call.
 +    // (See CMSettings.Secure.RING_HOME_BUTTON_BEHAVIOR.)
 +    private int mRingHomeBehavior;
 +
+     // Behavior of Back button while in-call and screen on
+     int mIncallBackBehavior;
      Display mDisplay;
  
      private int mDisplayRotation;
      private static final int MSG_SHOW_TV_PICTURE_IN_PICTURE_MENU = 17;
      private static final int MSG_BACK_LONG_PRESS = 18;
      private static final int MSG_DISPOSE_INPUT_CONSUMER = 19;
 -    private static final int MSG_BACK_DELAYED_PRESS = 20;
 +    private static final int MSG_DISPATCH_VOLKEY_WITH_WAKE_LOCK = 20;
 +    private static final int MSG_CAMERA_LONG_PRESS = 21;
 +    private static final int MSG_TOGGLE_TORCH = 22;
++    private static final int MSG_BACK_DELAYED_PRESS = 23;
  
      private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_STATUS = 0;
      private static final int MSG_REQUEST_TRANSIENT_BARS_ARG_NAVIGATION = 1;
                  case MSG_DISPOSE_INPUT_CONSUMER:
                      disposeInputConsumer((InputConsumer) msg.obj);
                      break;
 +                case MSG_DISPATCH_VOLKEY_WITH_WAKE_LOCK: {
 +                    KeyEvent event = (KeyEvent) msg.obj;
 +                    mIsLongPress = true;
 +                    dispatchMediaKeyWithWakeLockToAudioService(event);
 +                    dispatchMediaKeyWithWakeLockToAudioService(
 +                            KeyEvent.changeAction(event, KeyEvent.ACTION_UP));
 +                    break;
 +                }
 +                case MSG_CAMERA_LONG_PRESS: {
 +                    KeyEvent event = (KeyEvent) msg.obj;
 +                    mIsLongPress = true;
 +                    break;
 +                }
 +                case MSG_TOGGLE_TORCH: {
 +                    try {
 +                        final String rearFlashCameraId = getRearFlashCameraId();
 +                        if (rearFlashCameraId != null) {
 +                            mCameraManager.setTorchMode(rearFlashCameraId, !mTorchEnabled);
 +                            mTorchEnabled = !mTorchEnabled;
 +                        }
 +                    } catch (CameraAccessException e) {
 +                        // Ignore
 +                    }
 +                    break;
 +                }
+                 case MSG_BACK_DELAYED_PRESS:
+                     backMultiPressAction((Long) msg.obj, msg.arg1);
+                     finishBackKeyPress();
+                     break;
              }
          }
      }
              resolver.registerContentObserver(Settings.Secure.getUriFor(
                      Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR), false, this,
                      UserHandle.USER_ALL);
 +            resolver.registerContentObserver(CMSettings.Secure.getUriFor(
 +                    CMSettings.Secure.RING_HOME_BUTTON_BEHAVIOR), false, this,
 +                    UserHandle.USER_ALL);
 +            resolver.registerContentObserver(CMSettings.System.getUriFor(
 +                    CMSettings.System.TORCH_LONG_PRESS_POWER_GESTURE), false, this,
 +                    UserHandle.USER_ALL);
              resolver.registerContentObserver(Settings.Secure.getUriFor(
+                     Settings.Secure.INCALL_BACK_BUTTON_BEHAVIOR), false, this,
+                     UserHandle.USER_ALL);
+             resolver.registerContentObserver(Settings.Secure.getUriFor(
                      Settings.Secure.WAKE_GESTURE_ENABLED), false, this,
                      UserHandle.USER_ALL);
              resolver.registerContentObserver(Settings.System.getUriFor(
                      Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
                      Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT,
                      UserHandle.USER_CURRENT);
 +            mRingHomeBehavior = CMSettings.Secure.getIntForUser(resolver,
 +                    CMSettings.Secure.RING_HOME_BUTTON_BEHAVIOR,
 +                    CMSettings.Secure.RING_HOME_BUTTON_BEHAVIOR_DEFAULT,
 +                    UserHandle.USER_CURRENT);
 +            mTorchLongPressPowerEnabled = CMSettings.System.getIntForUser(
 +                    resolver, CMSettings.System.TORCH_LONG_PRESS_POWER_GESTURE, 0,
 +                    UserHandle.USER_CURRENT) == 1;
 +            mHomeWakeScreen = (CMSettings.System.getIntForUser(resolver,
 +                    CMSettings.System.HOME_WAKE_SCREEN, 1, UserHandle.USER_CURRENT) == 1) &&
 +                    ((mDeviceHardwareWakeKeys & KEY_MASK_HOME) != 0);
 +            mBackWakeScreen = (CMSettings.System.getIntForUser(resolver,
 +                    CMSettings.System.BACK_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1) &&
 +                    ((mDeviceHardwareWakeKeys & KEY_MASK_BACK) != 0);
 +            mMenuWakeScreen = (CMSettings.System.getIntForUser(resolver,
 +                    CMSettings.System.MENU_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1) &&
 +                    ((mDeviceHardwareWakeKeys & KEY_MASK_MENU) != 0);
 +            mAssistWakeScreen = (CMSettings.System.getIntForUser(resolver,
 +                    CMSettings.System.ASSIST_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1) &&
 +                    ((mDeviceHardwareWakeKeys & KEY_MASK_ASSIST) != 0);
 +            mAppSwitchWakeScreen = (CMSettings.System.getIntForUser(resolver,
 +                    CMSettings.System.APP_SWITCH_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1) &&
 +                    ((mDeviceHardwareWakeKeys & KEY_MASK_APP_SWITCH) != 0);
 +            mCameraWakeScreen = (CMSettings.System.getIntForUser(resolver,
 +                    CMSettings.System.CAMERA_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1) &&
 +                    ((mDeviceHardwareWakeKeys & KEY_MASK_CAMERA) != 0);
 +            mCameraSleepOnRelease = (CMSettings.System.getIntForUser(resolver,
 +                    CMSettings.System.CAMERA_SLEEP_ON_RELEASE, 0, UserHandle.USER_CURRENT) == 1);
 +            mCameraLaunch = (CMSettings.System.getIntForUser(resolver,
 +                    CMSettings.System.CAMERA_LAUNCH, 0, UserHandle.USER_CURRENT) == 1);
 +            mVolumeWakeScreen = (CMSettings.System.getIntForUser(resolver,
 +                    CMSettings.System.VOLUME_WAKE_SCREEN, 0, UserHandle.USER_CURRENT) == 1) &&
 +                    ((mDeviceHardwareWakeKeys & KEY_MASK_VOLUME) != 0);
 +            mVolBtnMusicControls = (CMSettings.System.getIntForUser(resolver,
 +                    CMSettings.System.VOLBTN_MUSIC_CONTROLS, 1, UserHandle.USER_CURRENT) == 1);
 +            mVolumeAnswerCall = CMSettings.System.getIntForUser(resolver,
 +                    CMSettings.System.VOLUME_ANSWER_CALL, 0, UserHandle.USER_CURRENT) == 1;
+             mIncallBackBehavior = Settings.Secure.getIntForUser(resolver,
+                     Settings.Secure.INCALL_BACK_BUTTON_BEHAVIOR,
+                     Settings.Secure.INCALL_BACK_BUTTON_BEHAVIOR_DEFAULT,
+                     UserHandle.USER_CURRENT);
  
              // Configure wake gesture.
              boolean wakeGestureEnabledSetting = Settings.Secure.getIntForUser(resolver,
@@@ -638,8 -588,7 +644,9 @@@ public final class PowerManagerService 
              mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
              mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
              mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
 +            mButtonBrightnessSettingDefault = pm.getDefaultButtonBrightness();
 +            mKeyboardBrightnessSettingDefault = pm.getDefaultKeyboardBrightness();
+             mScreenBrightnessForVrSettingDefault = pm.getDefaultScreenBrightnessForVrSetting();
  
              SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
  
              resolver.registerContentObserver(Settings.Secure.getUriFor(
                      Settings.Secure.DOUBLE_TAP_TO_WAKE),
                      false, mSettingsObserver, UserHandle.USER_ALL);
-             resolver.registerContentObserver(Settings.Secure.getUriFor(
-                     Secure.BRIGHTNESS_USE_TWILIGHT),
-                     false, mSettingsObserver, UserHandle.USER_ALL);
              IVrManager vrManager =
                      (IVrManager) getBinderService(VrManagerService.VR_MANAGER_BINDER_SERVICE);
-             try {
-                 vrManager.registerListener(mVrStateCallbacks);
-             } catch (RemoteException e) {
-                 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
+             if (vrManager != null) {
+                 try {
+                     vrManager.registerListener(mVrStateCallbacks);
+                 } catch (RemoteException e) {
+                     Slog.e(TAG, "Failed to register VR mode state listener: " + e);
+                 }
              }
 +
 +            resolver.registerContentObserver(CMSettings.Secure.getUriFor(
 +                    CMSettings.Secure.BUTTON_BRIGHTNESS),
 +                    false, mSettingsObserver, UserHandle.USER_ALL);
 +            resolver.registerContentObserver(CMSettings.Secure.getUriFor(
 +                    CMSettings.Secure.KEYBOARD_BRIGHTNESS),
 +                    false, mSettingsObserver, UserHandle.USER_ALL);
 +            resolver.registerContentObserver(CMSettings.Secure.getUriFor(
 +                    CMSettings.Secure.BUTTON_BACKLIGHT_TIMEOUT),
 +                    false, mSettingsObserver, UserHandle.USER_ALL);
 +            resolver.registerContentObserver(CMSettings.Global.getUriFor(
 +                    CMSettings.Global.WAKE_WHEN_PLUGGED_OR_UNPLUGGED),
 +                    false, mSettingsObserver, UserHandle.USER_ALL);
 +            resolver.registerContentObserver(CMSettings.Global.getUriFor(
 +                    CMSettings.Global.DEV_FORCE_SHOW_NAVBAR),
 +                    false, mSettingsObserver, UserHandle.USER_ALL);
 +            resolver.registerContentObserver(CMSettings.System.getUriFor(
 +                    CMSettings.System.PROXIMITY_ON_WAKE),
 +                    false, mSettingsObserver, UserHandle.USER_ALL);
 +
              // Go.
              readConfigurationLocked();
              updateSettingsLocked();
@@@ -155,9 -133,8 +154,10 @@@ static void setLight_native(JNIEnv* /* 
          state.flashOffMS = offMS;
      }
  
+     state.color = colorARGB;
      state.brightnessMode = brightnessMode;
 +    state.ledsModes = 0 |
 +                      (multipleLeds ? LIGHT_MODE_MULTIPLE_LEDS : 0);
  
      {
          ALOGD_IF_SLOW(50, "Excessive delay setting light");
@@@ -220,7 -208,7 +222,8 @@@ public final class SystemServer 
  
      private boolean mOnlyCore;
      private boolean mFirstBoot;
 +    private boolean mIsAlarmBoot;
+     private final boolean mRuntimeRestart;
  
      /**
       * Start the sensor service.
      public SystemServer() {
          // Check for factory test mode.
          mFactoryTestMode = FactoryTest.getMode();
+         // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot
+         mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));
      }
  
 +    private class AdbPortObserver extends ContentObserver {
 +        public AdbPortObserver() {
 +            super(null);
 +        }
 +        @Override
 +        public void onChange(boolean selfChange) {
 +            int adbPort = CMSettings.Secure.getInt(mContentResolver,
 +                CMSettings.Secure.ADB_PORT, 0);
 +            // setting this will control whether ADB runs on TCP/IP or USB
 +            SystemProperties.set("adb.network.port", Integer.toString(adbPort));
 +        }
 +    }
 +
      private void run() {
          try {
              Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitBeforeStartServices");
                  false);
          boolean disableTrustManager = SystemProperties.getBoolean("config.disable_trustmanager",
                  false);
-         boolean disableTextServices = SystemProperties.getBoolean("config.disable_textservices", false);
+         boolean disableTextServices = SystemProperties.getBoolean("config.disable_textservices",
+                 false);
          boolean disableSamplingProfiler = SystemProperties.getBoolean("config.disable_samplingprof",
                  false);
+         boolean disableConsumerIr = SystemProperties.getBoolean("config.disable_consumerir", false);
+         boolean disableVrManager = SystemProperties.getBoolean("config.disable_vrmanager", false);
+         boolean disableCameraService = SystemProperties.getBoolean("config.disable_cameraservice",
+                 false);
          boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1");
 +        boolean enableWigig = SystemProperties.getBoolean("persist.wigig.enable", false);
 +
 +        String externalServer = context.getResources().getString(
 +                org.cyanogenmod.platform.internal.R.string.config_externalSystemServer);
 +        boolean disableAtlas = SystemProperties.getBoolean("config.disable_atlas", false);
  
          try {
              Slog.i(TAG, "Reading configuration...");
          }
  
          if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {
 +            //#Fixme:mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS);
              mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS);
              mSystemServiceManager.startService(WEAR_WIFI_MEDIATOR_SERVICE_CLASS);
+             if (SystemProperties.getBoolean("config.enable_cellmediator", false)) {
+                 mSystemServiceManager.startService(WEAR_CELLULAR_MEDIATOR_SERVICE_CLASS);
+             }
            if (!disableNonCoreServices) {
                mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
            }
@@@ -329,8 -340,9 +341,9 @@@ public class UsbDeviceManager 
          private boolean mCurrentFunctionsApplied;
          private UsbAccessory mCurrentAccessory;
          private int mUsbNotificationId;
 -        private boolean mAdbNotificationShown;
 +        private int mAdbNotificationId;
          private int mCurrentUser = UserHandle.USER_NULL;
+         private boolean mUsbCharging;
  
          public UsbHandler(Looper looper) {
              super(looper);
                          SystemProperties.get(USB_STATE_PROPERTY));
                  mAdbEnabled = UsbManager.containsFunction(getDefaultFunctions(),
                          UsbManager.USB_FUNCTION_ADB);
-                 setEnabledFunctions(null, false);
+                 /**
+                  * Remove MTP from persistent config, to bring usb to a good state
+                  * after fixes to b/31814300. This block can be removed after the update
+                  */
+                 String persisted = SystemProperties.get(USB_PERSISTENT_CONFIG_PROPERTY);
+                 if (UsbManager.containsFunction(persisted, UsbManager.USB_FUNCTION_MTP)) {
+                     SystemProperties.set(USB_PERSISTENT_CONFIG_PROPERTY,
+                             UsbManager.removeFunction(persisted, UsbManager.USB_FUNCTION_MTP));
+                 }
+                 setEnabledFunctions(null, false, false);
 +                if (mContext.getResources().getBoolean(
 +                        com.android.internal.R.bool.config_usb_data_unlock)) {
 +                    boolean mtpEnable = UsbManager.containsFunction(getDefaultFunctions(),
 +                            UsbManager.USB_FUNCTION_MTP);
 +                    boolean ptpEnable = UsbManager.containsFunction(getDefaultFunctions(),
 +                            UsbManager.USB_FUNCTION_PTP);
 +                    if (mtpEnable || ptpEnable) mUsbDataUnlocked = true;
 +                }
++
                  String state = FileUtils.readTextFile(new File(STATE_PATH), 0, null).trim();
                  updateState(state);
  
@@@ -366,8 -324,8 +366,9 @@@ public final class Call 
          private final PhoneAccountHandle mAccountHandle;
          private final int mCallCapabilities;
          private final int mCallProperties;
+         private final int mSupportedAudioRoutes = CallAudioState.ROUTE_ALL;
          private final DisconnectCause mDisconnectCause;
 +        private final long mCreateTimeMillis;
          private final long mConnectTimeMillis;
          private final GatewayInfo mGatewayInfo;
          private final int mVideoState;
@@@ -39,7 -39,7 +39,8 @@@ public final class ParcelableCall imple
      private final List<String> mCannedSmsResponses;
      private final int mCapabilities;
      private final int mProperties;
 +    private final long mCreateTimeMillis;
+     private final int mSupportedAudioRoutes;
      private final long mConnectTimeMillis;
      private final Uri mHandle;
      private final int mHandlePresentation;
@@@ -65,7 -65,7 +66,8 @@@
              List<String> cannedSmsResponses,
              int capabilities,
              int properties,
 +            long createTimeMillis,
+             int supportedAudioRoutes,
              long connectTimeMillis,
              Uri handle,
              int handlePresentation,
@@@ -88,7 -88,7 +90,8 @@@
          mCannedSmsResponses = cannedSmsResponses;
          mCapabilities = capabilities;
          mProperties = properties;
 +        mCreateTimeMillis = createTimeMillis;
+         mSupportedAudioRoutes = supportedAudioRoutes;
          mConnectTimeMillis = connectTimeMillis;
          mHandle = handle;
          mHandlePresentation = handlePresentation;
      /** Bitmask of properties of the call. */
      public int getProperties() { return mProperties; }
  
 +    /** The time that the call object was created */
 +    public long getCreateTimeMillis() {
 +        return mCreateTimeMillis;
 +    }
 +
+     /** Bitmask of supported routes of the call */
+     public int getSupportedAudioRoutes() {
+         return mSupportedAudioRoutes;
+     }
      /** The time that the call switched to the active state. */
      public long getConnectTimeMillis() {
          return mConnectTimeMillis;
                      cannedSmsResponses,
                      capabilities,
                      properties,
 +                    createTimeMillis,
+                     supportedAudioRoutes,
                      connectTimeMillis,
                      handle,
                      handlePresentation,
@@@ -1054,9 -1127,10 +1151,10 @@@ public class CarrierConfigManager 
          sDefaults.putBoolean(KEY_HIDE_CARRIER_NETWORK_SETTINGS_BOOL, false);
          sDefaults.putBoolean(KEY_HIDE_SIM_LOCK_SETTINGS_BOOL, false);
          sDefaults.putBoolean(KEY_IGNORE_SIM_NETWORK_LOCKED_EVENTS_BOOL, false);
+         sDefaults.putBoolean(KEY_MDN_IS_ADDITIONAL_VOICEMAIL_NUMBER_BOOL, false);
          sDefaults.putBoolean(KEY_OPERATOR_SELECTION_EXPAND_BOOL, true);
          sDefaults.putBoolean(KEY_PREFER_2G_BOOL, true);
 -        sDefaults.putBoolean(KEY_SHOW_APN_SETTING_CDMA_BOOL, false);
 +        sDefaults.putBoolean(KEY_SHOW_APN_SETTING_CDMA_BOOL, true);
          sDefaults.putBoolean(KEY_SHOW_CDMA_CHOICES_BOOL, false);
          sDefaults.putBoolean(KEY_SHOW_ONSCREEN_DIAL_BUTTON_BOOL, true);
          sDefaults.putBoolean(KEY_SIM_NETWORK_UNLOCK_ALLOW_DISMISS_BOOL, true);
          sDefaults.putStringArray(FILTERED_CNAP_NAMES_STRING_ARRAY, null);
          sDefaults.putBoolean(KEY_EDITABLE_WFC_ROAMING_MODE_BOOL, false);
          sDefaults.putBoolean(KEY_STK_DISABLE_LAUNCH_BROWSER_BOOL, false);
 +        sDefaults.putBoolean(KEY_MAP_ANONYMOUS_TO_RESTRICTED_BOOL, true);
+         sDefaults.putStringArray(KEY_CARRIER_WIFI_STRING_ARRAY, null);
+         sDefaults.putInt(KEY_PREF_NETWORK_NOTIFICATION_DELAY_INT, -1);
+         sDefaults.putBoolean(KEY_EDITABLE_TETHER_APN_BOOL, false);
+         sDefaults.putBoolean(KEY_SUPPORT_3GPP_CALL_FORWARDING_WHILE_ROAMING_BOOL, true);
+         sDefaults.putStringArray(KEY_CALL_FORWARDING_BLOCKS_WHILE_ROAMING_STRING_ARRAY, null);
      }
  
      /**
@@@ -232,62 -232,14 +232,69 @@@ public class DisconnectCause 
       * {@hide}
       */
      public static final int DIALED_ON_WRONG_SLOT = 56;
 +    public static final int NO_CIRCUIT_AVAIL = 57;
 +    public static final int NO_ROUTE_TO_DESTINAON = 58;
 +    public static final int OPERATOR_DETERMINED_BARRING = 59;
 +    public static final int CALL_FAIL_NO_USER_RESPONDING = 60;
 +    public static final int CALL_FAIL_NO_ANSWER_FROM_USER = 61;
 +    public static final int CALL_FAIL_DESTINATION_OUT_OF_ORDER = 62;
 +    public static final int BEARER_CAPABILITY_NOT_AUTHORIZED = 63;
 +    public static final int CHANNEL_UNACCEPTABLE = 64;
 +    public static final int CALL_REJECTED = 65;
 +    public static final int NUMBER_CHANGED = 66;
 +    public static final int PREEMPTION = 67;
 +    public static final int FACILITY_REJECTED = 68;
 +    public static final int RESP_TO_STATUS_ENQUIRY = 69;
 +    public static final int NORMAL_UNSPECIFIED = 70;
 +    public static final int NETWORK_OUT_OF_ORDER = 71;
 +    public static final int TEMPORARY_FAILURE = 72;
 +    public static final int SWITCHING_EQUIPMENT_CONGESTION = 73;
 +    public static final int ACCESS_INFORMATION_DISCARDED = 74;
 +    public static final int REQUESTED_CIRCUIT_OR_CHANNEL_NOT_AVAILABLE = 75;
 +    public static final int RESOURCES_UNAVAILABLE_OR_UNSPECIFIED = 76;
 +    public static final int QOS_UNAVAILABLE = 77;
 +    public static final int REQUESTED_FACILITY_NOT_SUBSCRIBED = 78;
 +    public static final int INCOMING_CALLS_BARRED_WITHIN_CUG = 79;
 +    public static final int BEARER_CAPABILITY_UNAVAILABLE = 80;
 +    public static final int SERVICE_OPTION_NOT_AVAILABLE = 81;
 +    public static final int BEARER_SERVICE_NOT_IMPLEMENTED = 82;
 +    public static final int REQUESTED_FACILITY_NOT_IMPLEMENTED = 83;
 +    public static final int ONLY_DIGITAL_INFORMATION_BEARER_AVAILABLE = 84;
 +    public static final int SERVICE_OR_OPTION_NOT_IMPLEMENTED = 85;
 +    public static final int INVALID_TRANSACTION_IDENTIFIER = 86;
 +    public static final int USER_NOT_MEMBER_OF_CUG = 87;
 +    public static final int INCOMPATIBLE_DESTINATION = 88;
 +    public static final int INVALID_TRANSIT_NW_SELECTION = 89;
 +    public static final int SEMANTICALLY_INCORRECT_MESSAGE = 90;
 +    public static final int INVALID_MANDATORY_INFORMATION = 91;
 +    public static final int MESSAGE_TYPE_NON_IMPLEMENTED = 92;
 +    public static final int MESSAGE_TYPE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE = 93;
 +    public static final int INFORMATION_ELEMENT_NON_EXISTENT = 94;
 +    public static final int CONDITIONAL_IE_ERROR = 95;
 +    public static final int MESSAGE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE = 96;
 +    public static final int RECOVERY_ON_TIMER_EXPIRED = 97;
 +    public static final int PROTOCOL_ERROR_UNSPECIFIED = 98;
 +    public static final int INTERWORKING_UNSPECIFIED = 99;
 +    public static final int LOCAL_LOW_BATTERY = 100;
 +    public static final int LOW_BATTERY = 101;
 +
 +    /** EMERGENCY call failed with temporary fail cause */
 +    public static final int EMERGENCY_TEMP_FAILURE         = 102;
 +    /** EMERGENCY call failed with permanent fail cause */
 +    public static final int EMERGENCY_PERM_FAILURE         = 103;
 +
 +    /** call failed due to LTE to 3G/2G handover not feasible */
 +    public static final int HO_NOT_FEASIBLE = 104;
 +
 +    public static final int NON_SELECTED_USER_CLEARING = 105;
  
 -    public static final int DIALED_CALL_FORWARDING_WHILE_ROAMING = 57;
+     /**
+      * The call being placed was detected as a call forwarding number and was being dialed while
+      * roaming on a carrier that does not allow this.
+      * @hide
+      */
++    public static final int DIALED_CALL_FORWARDING_WHILE_ROAMING = 106;
      //*********************************************************************************************
      // When adding a disconnect type:
      // 1) Please assign the new type the next id value below.
      // 4) Update toString() with the newly added disconnect type.
      // 5) Update android.telecom.DisconnectCauseUtil with any mappings to a telecom.DisconnectCause.
      //
-     // NextId: 106
 -    // NextId: 58
++    // NextId: 107
      //*********************************************************************************************
  
      /** Smallest valid value for call disconnect codes. */
              return "DATA_LIMIT_REACHED";
          case DIALED_ON_WRONG_SLOT:
              return "DIALED_ON_WRONG_SLOT";
 +        case NO_CIRCUIT_AVAIL:
 +            return "NO_CIRCUIT_AVAIL";
 +        case NO_ROUTE_TO_DESTINAON:
 +            return "NO_ROUTE_TO_DESTINAON";
 +        case OPERATOR_DETERMINED_BARRING:
 +            return "OPERATOR_DETERMINED_BARRING";
 +        case CALL_FAIL_NO_USER_RESPONDING:
 +            return "CALL_FAIL_NO_USER_RESPONDING";
 +        case CALL_FAIL_NO_ANSWER_FROM_USER:
 +            return "CALL_FAIL_NO_ANSWER_FROM_USER";
 +        case CALL_FAIL_DESTINATION_OUT_OF_ORDER:
 +            return "CALL_FAIL_DESTINATION_OUT_OF_ORDER";
 +        case BEARER_CAPABILITY_NOT_AUTHORIZED:
 +            return "BEARER_CAPABILITY_NOT_AUTHORIZED";
 +        case CHANNEL_UNACCEPTABLE:
 +            return "CHANNEL_UNACCEPTABLE";
 +        case CALL_REJECTED:
 +            return "CALL_REJECTED";
 +        case NUMBER_CHANGED:
 +            return "NUMBER_CHANGED";
 +        case PREEMPTION:
 +            return "PREEMPTION";
 +        case FACILITY_REJECTED:
 +            return "FACILITY_REJECTED";
 +        case RESP_TO_STATUS_ENQUIRY:
 +            return "RESP_TO_STATUS_ENQUIRY";
 +        case NORMAL_UNSPECIFIED:
 +            return "NORMAL_UNSPECIFIED";
 +        case NETWORK_OUT_OF_ORDER:
 +            return "NETWORK_OUT_OF_ORDER";
 +        case TEMPORARY_FAILURE:
 +            return "TEMPORARY_FAILURE";
 +        case SWITCHING_EQUIPMENT_CONGESTION:
 +            return "SWITCHING_EQUIPMENT_CONGESTION";
 +        case ACCESS_INFORMATION_DISCARDED:
 +            return "ACCESS_INFORMATION_DISCARDED";
 +        case REQUESTED_CIRCUIT_OR_CHANNEL_NOT_AVAILABLE:
 +            return "REQUESTED_CIRCUIT_OR_CHANNEL_NOT_AVAILABLE";
 +        case RESOURCES_UNAVAILABLE_OR_UNSPECIFIED:
 +            return "RESOURCES_UNAVAILABLE_OR_UNSPECIFIED";
 +        case QOS_UNAVAILABLE:
 +            return "QOS_UNAVAILABLE";
 +        case REQUESTED_FACILITY_NOT_SUBSCRIBED:
 +            return "REQUESTED_FACILITY_NOT_SUBSCRIBED";
 +        case INCOMING_CALLS_BARRED_WITHIN_CUG:
 +            return "INCOMING_CALLS_BARRED_WITHIN_CUG";
 +        case BEARER_CAPABILITY_UNAVAILABLE:
 +            return "BEARER_CAPABILITY_UNAVAILABLE";
 +        case SERVICE_OPTION_NOT_AVAILABLE:
 +            return "SERVICE_OPTION_NOT_AVAILABLE";
 +        case BEARER_SERVICE_NOT_IMPLEMENTED:
 +            return "BEARER_SERVICE_NOT_IMPLEMENTED";
 +        case REQUESTED_FACILITY_NOT_IMPLEMENTED:
 +            return "REQUESTED_FACILITY_NOT_IMPLEMENTED";
 +        case ONLY_DIGITAL_INFORMATION_BEARER_AVAILABLE:
 +            return "ONLY_DIGITAL_INFORMATION_BEARER_AVAILABLE";
 +        case SERVICE_OR_OPTION_NOT_IMPLEMENTED:
 +            return "SERVICE_OR_OPTION_NOT_IMPLEMENTED";
 +        case INVALID_TRANSACTION_IDENTIFIER:
 +            return "INVALID_TRANSACTION_IDENTIFIER";
 +        case USER_NOT_MEMBER_OF_CUG:
 +            return "USER_NOT_MEMBER_OF_CUG";
 +        case INCOMPATIBLE_DESTINATION:
 +            return "INCOMPATIBLE_DESTINATION";
 +        case INVALID_TRANSIT_NW_SELECTION:
 +            return "INVALID_TRANSIT_NW_SELECTION";
 +        case SEMANTICALLY_INCORRECT_MESSAGE:
 +            return "SEMANTICALLY_INCORRECT_MESSAGE";
 +        case INVALID_MANDATORY_INFORMATION:
 +            return "INVALID_MANDATORY_INFORMATION";
 +        case MESSAGE_TYPE_NON_IMPLEMENTED:
 +            return "MESSAGE_TYPE_NON_IMPLEMENTED";
 +        case MESSAGE_TYPE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE:
 +            return "MESSAGE_TYPE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE";
 +        case INFORMATION_ELEMENT_NON_EXISTENT:
 +            return "INFORMATION_ELEMENT_NON_EXISTENT";
 +        case CONDITIONAL_IE_ERROR:
 +            return "CONDITIONAL_IE_ERROR";
 +        case MESSAGE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE:
 +            return "MESSAGE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE";
 +        case RECOVERY_ON_TIMER_EXPIRED:
 +            return "RECOVERY_ON_TIMER_EXPIRED";
 +        case PROTOCOL_ERROR_UNSPECIFIED:
 +            return "PROTOCOL_ERROR_UNSPECIFIED";
 +        case INTERWORKING_UNSPECIFIED:
 +            return "INTERWORKING_UNSPECIFIED";
 +        case LOCAL_LOW_BATTERY:
 +            return "LOCAL_LOW_BATTERY";
 +        case LOW_BATTERY:
 +            return "LOW_BATTERY";
 +        case EMERGENCY_TEMP_FAILURE:
 +            return "EMERGENCY_TEMP_FAILURE";
 +        case EMERGENCY_PERM_FAILURE:
 +            return "EMERGENCY_PERM_FAILURE";
 +        case HO_NOT_FEASIBLE:
 +            return "HO_NOT_FEASIBLE";
 +        case NON_SELECTED_USER_CLEARING:
 +            return "NON_SELECTED_USER_CLEARING";
+         case DIALED_CALL_FORWARDING_WHILE_ROAMING:
+             return "DIALED_CALL_FORWARDING_WHILE_ROAMING";
          default:
              return "INVALID: " + cause;
          }
@@@ -1608,13 -1591,9 +1613,9 @@@ public class TelephonyManager 
       * @see #NETWORK_TYPE_LTE
       * @see #NETWORK_TYPE_EHRPD
       * @see #NETWORK_TYPE_HSPAP
-      *
-      * <p>
-      * Requires Permission:
-      *   {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
       */
      public int getDataNetworkType() {
 -        return getDataNetworkType(getSubId());
 +        return getDataNetworkType(getDefaultDataSubscriptionId());
      }
  
      /**
@@@ -1998,10 -1996,9 +2018,11 @@@ public class WifiConfiguration implemen
          dest.writeInt(userApproved);
          dest.writeInt(numNoInternetAccessReports);
          dest.writeInt(noInternetAccessExpected ? 1 : 0);
+         dest.writeInt(isCarrierNetwork ? 1 : 0);
          dest.writeInt(shared ? 1 : 0);
          dest.writeString(mPasspointManagementObjectTree);
 +        dest.writeInt(SIMNum);
 +        dest.writeLong(wifiApInactivityTimeout);
      }
  
      /** Implement the Parcelable interface {@hide} */
                  config.userApproved = in.readInt();
                  config.numNoInternetAccessReports = in.readInt();
                  config.noInternetAccessExpected = in.readInt() != 0;
+                 config.isCarrierNetwork = in.readInt() != 0;
                  config.shared = in.readInt() != 0;
                  config.mPasspointManagementObjectTree = in.readString();
 +                config.SIMNum = in.readInt();
 +                config.wifiApInactivityTimeout = in.readLong();
                  return config;
              }