Merge "fix dumpsys wording for h/w composer"
diff --git a/Android.mk b/Android.mk
index 91850d5..be8c25b 100644
--- a/Android.mk
+++ b/Android.mk
@@ -381,7 +381,7 @@
     -since ./frameworks/base/api/11.xml 11 \
     -since ./frameworks/base/api/12.xml 12 \
     -since ./frameworks/base/api/13.xml 13 \
-    -since ./frameworks/base/api/current.txt ICS \
+    -since ./frameworks/base/api/14.txt 14 \
 		-werror -hide 113 \
 		-overview $(LOCAL_PATH)/core/java/overview.html
 
@@ -473,7 +473,7 @@
 
 ## SDK version identifiers used in the published docs
   # major[.minor] version for current SDK. (full releases only)
-framework_docs_SDK_VERSION:=3.2
+framework_docs_SDK_VERSION:=4.0
   # release version (ie "Release x")  (full releases only)
 framework_docs_SDK_REL_ID:=1
 
diff --git a/api/14.txt b/api/14.txt
index 45bb882..9f2a6df 100644
--- a/api/14.txt
+++ b/api/14.txt
@@ -759,6 +759,7 @@
     field public static final int prompt = 16843131; // 0x101017b
     field public static final int propertyName = 16843489; // 0x10102e1
     field public static final int protectionLevel = 16842761; // 0x1010009
+    field public static final int publicKey = 16843686; // 0x10103a6
     field public static final int queryActionMsg = 16843227; // 0x10101db
     field public static final int queryAfterZeroResults = 16843394; // 0x1010282
     field public static final int queryHint = 16843608; // 0x1010358
@@ -4566,6 +4567,7 @@
     field public static final java.lang.String EXTRA_PREVIOUS_STATE = "android.bluetooth.profile.extra.PREVIOUS_STATE";
     field public static final java.lang.String EXTRA_STATE = "android.bluetooth.profile.extra.STATE";
     field public static final int HEADSET = 1; // 0x1
+    field public static final int HEALTH = 3; // 0x3
     field public static final int STATE_CONNECTED = 2; // 0x2
     field public static final int STATE_CONNECTING = 1; // 0x1
     field public static final int STATE_DISCONNECTED = 0; // 0x0
@@ -5454,6 +5456,7 @@
     field public static final java.lang.String ACTION_PACKAGE_FIRST_LAUNCH = "android.intent.action.PACKAGE_FIRST_LAUNCH";
     field public static final java.lang.String ACTION_PACKAGE_FULLY_REMOVED = "android.intent.action.PACKAGE_FULLY_REMOVED";
     field public static final deprecated java.lang.String ACTION_PACKAGE_INSTALL = "android.intent.action.PACKAGE_INSTALL";
+    field public static final java.lang.String ACTION_PACKAGE_NEEDS_VERIFICATION = "android.intent.action.PACKAGE_NEEDS_VERIFICATION";
     field public static final java.lang.String ACTION_PACKAGE_REMOVED = "android.intent.action.PACKAGE_REMOVED";
     field public static final java.lang.String ACTION_PACKAGE_REPLACED = "android.intent.action.PACKAGE_REPLACED";
     field public static final java.lang.String ACTION_PACKAGE_RESTARTED = "android.intent.action.PACKAGE_RESTARTED";
@@ -6207,11 +6210,13 @@
     method public abstract void setApplicationEnabledSetting(java.lang.String, int, int);
     method public abstract void setComponentEnabledSetting(android.content.ComponentName, int, int);
     method public abstract void setInstallerPackageName(java.lang.String, java.lang.String);
+    method public abstract void verifyPendingInstall(int, int);
     field public static final int COMPONENT_ENABLED_STATE_DEFAULT = 0; // 0x0
     field public static final int COMPONENT_ENABLED_STATE_DISABLED = 2; // 0x2
     field public static final int COMPONENT_ENABLED_STATE_DISABLED_USER = 3; // 0x3
     field public static final int COMPONENT_ENABLED_STATE_ENABLED = 1; // 0x1
     field public static final int DONT_KILL_APP = 1; // 0x1
+    field public static final java.lang.String EXTRA_VERIFICATION_ID = "android.content.pm.extra.VERIFICATION_ID";
     field public static final java.lang.String FEATURE_AUDIO_LOW_LATENCY = "android.hardware.audio.low_latency";
     field public static final java.lang.String FEATURE_BLUETOOTH = "android.hardware.bluetooth";
     field public static final java.lang.String FEATURE_CAMERA = "android.hardware.camera";
@@ -6273,6 +6278,8 @@
     field public static final int SIGNATURE_NO_MATCH = -3; // 0xfffffffd
     field public static final int SIGNATURE_SECOND_NOT_SIGNED = -2; // 0xfffffffe
     field public static final int SIGNATURE_UNKNOWN_PACKAGE = -4; // 0xfffffffc
+    field public static final int VERIFICATION_ALLOW = 1; // 0x1
+    field public static final int VERIFICATION_REJECT = -1; // 0xffffffff
   }
 
   public static class PackageManager.NameNotFoundException extends android.util.AndroidException {
@@ -19834,6 +19841,7 @@
     method public void setApplicationEnabledSetting(java.lang.String, int, int);
     method public void setComponentEnabledSetting(android.content.ComponentName, int, int);
     method public void setInstallerPackageName(java.lang.String, java.lang.String);
+    method public void verifyPendingInstall(int, int);
   }
 
   public class MockResources extends android.content.res.Resources {
diff --git a/api/current.txt b/api/current.txt
index 45bb882..9f2a6df 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -759,6 +759,7 @@
     field public static final int prompt = 16843131; // 0x101017b
     field public static final int propertyName = 16843489; // 0x10102e1
     field public static final int protectionLevel = 16842761; // 0x1010009
+    field public static final int publicKey = 16843686; // 0x10103a6
     field public static final int queryActionMsg = 16843227; // 0x10101db
     field public static final int queryAfterZeroResults = 16843394; // 0x1010282
     field public static final int queryHint = 16843608; // 0x1010358
@@ -4566,6 +4567,7 @@
     field public static final java.lang.String EXTRA_PREVIOUS_STATE = "android.bluetooth.profile.extra.PREVIOUS_STATE";
     field public static final java.lang.String EXTRA_STATE = "android.bluetooth.profile.extra.STATE";
     field public static final int HEADSET = 1; // 0x1
+    field public static final int HEALTH = 3; // 0x3
     field public static final int STATE_CONNECTED = 2; // 0x2
     field public static final int STATE_CONNECTING = 1; // 0x1
     field public static final int STATE_DISCONNECTED = 0; // 0x0
@@ -5454,6 +5456,7 @@
     field public static final java.lang.String ACTION_PACKAGE_FIRST_LAUNCH = "android.intent.action.PACKAGE_FIRST_LAUNCH";
     field public static final java.lang.String ACTION_PACKAGE_FULLY_REMOVED = "android.intent.action.PACKAGE_FULLY_REMOVED";
     field public static final deprecated java.lang.String ACTION_PACKAGE_INSTALL = "android.intent.action.PACKAGE_INSTALL";
+    field public static final java.lang.String ACTION_PACKAGE_NEEDS_VERIFICATION = "android.intent.action.PACKAGE_NEEDS_VERIFICATION";
     field public static final java.lang.String ACTION_PACKAGE_REMOVED = "android.intent.action.PACKAGE_REMOVED";
     field public static final java.lang.String ACTION_PACKAGE_REPLACED = "android.intent.action.PACKAGE_REPLACED";
     field public static final java.lang.String ACTION_PACKAGE_RESTARTED = "android.intent.action.PACKAGE_RESTARTED";
@@ -6207,11 +6210,13 @@
     method public abstract void setApplicationEnabledSetting(java.lang.String, int, int);
     method public abstract void setComponentEnabledSetting(android.content.ComponentName, int, int);
     method public abstract void setInstallerPackageName(java.lang.String, java.lang.String);
+    method public abstract void verifyPendingInstall(int, int);
     field public static final int COMPONENT_ENABLED_STATE_DEFAULT = 0; // 0x0
     field public static final int COMPONENT_ENABLED_STATE_DISABLED = 2; // 0x2
     field public static final int COMPONENT_ENABLED_STATE_DISABLED_USER = 3; // 0x3
     field public static final int COMPONENT_ENABLED_STATE_ENABLED = 1; // 0x1
     field public static final int DONT_KILL_APP = 1; // 0x1
+    field public static final java.lang.String EXTRA_VERIFICATION_ID = "android.content.pm.extra.VERIFICATION_ID";
     field public static final java.lang.String FEATURE_AUDIO_LOW_LATENCY = "android.hardware.audio.low_latency";
     field public static final java.lang.String FEATURE_BLUETOOTH = "android.hardware.bluetooth";
     field public static final java.lang.String FEATURE_CAMERA = "android.hardware.camera";
@@ -6273,6 +6278,8 @@
     field public static final int SIGNATURE_NO_MATCH = -3; // 0xfffffffd
     field public static final int SIGNATURE_SECOND_NOT_SIGNED = -2; // 0xfffffffe
     field public static final int SIGNATURE_UNKNOWN_PACKAGE = -4; // 0xfffffffc
+    field public static final int VERIFICATION_ALLOW = 1; // 0x1
+    field public static final int VERIFICATION_REJECT = -1; // 0xffffffff
   }
 
   public static class PackageManager.NameNotFoundException extends android.util.AndroidException {
@@ -19834,6 +19841,7 @@
     method public void setApplicationEnabledSetting(java.lang.String, int, int);
     method public void setComponentEnabledSetting(android.content.ComponentName, int, int);
     method public void setInstallerPackageName(java.lang.String, java.lang.String);
+    method public void verifyPendingInstall(int, int);
   }
 
   public class MockResources extends android.content.res.Resources {
diff --git a/cmds/ip-up-vpn/ip-up-vpn.c b/cmds/ip-up-vpn/ip-up-vpn.c
index e9ee95d..0e6286f 100644
--- a/cmds/ip-up-vpn/ip-up-vpn.c
+++ b/cmds/ip-up-vpn/ip-up-vpn.c
@@ -40,6 +40,7 @@
 
 static int set_address(struct sockaddr *sa, const char *address) {
     sa->sa_family = AF_INET;
+    errno = EINVAL;
     return inet_pton(AF_INET, address, &((struct sockaddr_in *)sa)->sin_addr);
 }
 
@@ -124,10 +125,11 @@
         }
 
         /* Set the netmask. */
-        if (!set_address(&ifr.ifr_netmask, env("INTERNAL_NETMASK4")) ||
-                ioctl(s, SIOCSIFNETMASK, &ifr)) {
-            LOGE("Cannot set netmask: %s", strerror(errno));
-            return 1;
+        if (set_address(&ifr.ifr_netmask, env("INTERNAL_NETMASK4"))) {
+            if (ioctl(s, SIOCSIFNETMASK, &ifr)) {
+                LOGE("Cannot set netmask: %s", strerror(errno));
+                return 1;
+            }
         }
 
         /* TODO: Send few packets to trigger phase 2? */
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index bd42e34..8ed7481 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -954,9 +954,9 @@
     }
 
     @Override
-    public void verifyPendingInstall(int id, boolean verified, String failureMessage) {
+    public void verifyPendingInstall(int id, int response) {
         try {
-            mPM.verifyPendingInstall(id, verified, failureMessage);
+            mPM.verifyPendingInstall(id, response);
         } catch (RemoteException e) {
             // Should never happen!
         }
diff --git a/core/java/android/bluetooth/BluetoothProfile.java b/core/java/android/bluetooth/BluetoothProfile.java
index 58b3868..f7ccfbd 100644
--- a/core/java/android/bluetooth/BluetoothProfile.java
+++ b/core/java/android/bluetooth/BluetoothProfile.java
@@ -66,7 +66,6 @@
 
     /**
      * Health Profile
-     * @hide
      */
     public static final int HEALTH = 3;
 
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index c7698bf..72cf26a 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -1535,8 +1535,6 @@
      * <p class="note">
      * This is a protected intent that can only be sent by the system.
      * </p>
-     *
-     * @hide
      */
     @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
     public static final String ACTION_PACKAGE_NEEDS_VERIFICATION = "android.intent.action.PACKAGE_NEEDS_VERIFICATION";
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index 5e6e768..a3bcc28 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -359,7 +359,7 @@
             int flags, in String installerPackageName, in Uri verificationURI,
             in ManifestDigest manifestDigest);
 
-    void verifyPendingInstall(int id, boolean verified, in String message);
+    void verifyPendingInstall(int id, int verificationCode);
 
     VerifierDeviceIdentity getVerifierDeviceIdentity();
 }
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index dcb6776..ef7e233 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -725,7 +725,22 @@
     public static final int MOVE_EXTERNAL_MEDIA = 0x00000002;
 
     /**
+     * Used as the {@code verificationCode} argument for
+     * {@link PackageManager#verifyPendingInstall} to indicate that the calling
+     * package verifier allows the installation to proceed.
+     */
+    public static final int VERIFICATION_ALLOW = 1;
+
+    /**
+     * Used as the {@code verificationCode} argument for
+     * {@link PackageManager#verifyPendingInstall} to indicate the calling
+     * package verifier does not vote to allow the installation to proceed.
+     */
+    public static final int VERIFICATION_REJECT = -1;
+
+    /**
      * Range of IDs allocated for a user.
+     *
      * @hide
      */
     public static final int PER_USER_RANGE = 100000;
@@ -1045,9 +1060,7 @@
     /**
      * Extra field name for the ID of a package pending verification. Passed to
      * a package verifier and is used to call back to
-     * {@link PackageManager#verifyPendingInstall(int, boolean)}
-     *
-     * @hide
+     * {@link PackageManager#verifyPendingInstall(int, int)}
      */
     public static final String EXTRA_VERIFICATION_ID = "android.content.pm.extra.VERIFICATION_ID";
 
@@ -2156,16 +2169,17 @@
     /**
      * Allows a package listening to the
      * {@link Intent#ACTION_PACKAGE_NEEDS_VERIFICATION package verification
-     * broadcast} to respond to the package manager.
+     * broadcast} to respond to the package manager. The response must include
+     * the {@code verificationCode} which is one of
+     * {@link PackageManager#VERIFICATION_ALLOW} or
+     * {@link PackageManager#VERIFICATION_REJECT}.
      *
      * @param id pending package identifier as passed via the
      *            {@link PackageManager#EXTRA_VERIFICATION_ID} Intent extra
-     * @param verified whether the package was verified as valid
-     * @param failureMessage if verification was false, this is the error
-     *            message that may be shown to the user
-     * @hide
+     * @param verificationCode either {@link PackageManager#VERIFICATION_ALLOW}
+     *            or {@link PackageManager#VERIFICATION_REJECT}.
      */
-    public abstract void verifyPendingInstall(int id, boolean verified, String failureMessage);
+    public abstract void verifyPendingInstall(int id, int verificationCode);
 
     /**
      * Change the installer associated with a given package.  There are limitations
diff --git a/core/java/android/inputmethodservice/Keyboard.java b/core/java/android/inputmethodservice/Keyboard.java
index 10386f8..4fe54c0 100644
--- a/core/java/android/inputmethodservice/Keyboard.java
+++ b/core/java/android/inputmethodservice/Keyboard.java
@@ -144,6 +144,8 @@
     /** Number of key widths from current touch point to search for nearest keys. */
     private static float SEARCH_DISTANCE = 1.8f;
 
+    private ArrayList<Row> rows = new ArrayList<Row>();
+
     /**
      * Container for keys in the keyboard. All keys in a row are at the same Y-coordinate. 
      * Some of the key size defaults can be overridden per row from what the {@link Keyboard}
@@ -164,6 +166,9 @@
         public int defaultHorizontalGap;
         /** Vertical gap following this row. */
         public int verticalGap;
+
+        ArrayList<Key> mKeys = new ArrayList<Key>();
+
         /**
          * Edge flags for this row of keys. Possible values that can be assigned are
          * {@link Keyboard#EDGE_TOP EDGE_TOP} and {@link Keyboard#EDGE_BOTTOM EDGE_BOTTOM}  
@@ -256,7 +261,7 @@
         public CharSequence text;
         /** Popup characters */
         public CharSequence popupCharacters;
-        
+
         /** 
          * Flags that specify the anchoring to edges of the keyboard for detecting touch events
          * that are just out of the boundary of the key. This is a bit mask of 
@@ -596,11 +601,44 @@
             column++;
             x += key.width + key.gap;
             mKeys.add(key);
+            row.mKeys.add(key);
             if (x > mTotalWidth) {
                 mTotalWidth = x;
             }
         }
-        mTotalHeight = y + mDefaultHeight; 
+        mTotalHeight = y + mDefaultHeight;
+        rows.add(row);
+    }
+
+    final void resize(int newWidth, int newHeight) {
+        int numRows = rows.size();
+        for (int rowIndex = 0; rowIndex < numRows; ++rowIndex) {
+            Row row = rows.get(rowIndex);
+            int numKeys = row.mKeys.size();
+            int totalGap = 0;
+            int totalWidth = 0;
+            for (int keyIndex = 0; keyIndex < numKeys; ++keyIndex) {
+                Key key = row.mKeys.get(keyIndex);
+                if (keyIndex > 0) {
+                    totalGap += key.gap;
+                }
+                totalWidth += key.width;
+            }
+            if (totalGap + totalWidth > newWidth) {
+                int x = 0;
+                float scaleFactor = (float)(newWidth - totalGap) / totalWidth;
+                for (int keyIndex = 0; keyIndex < numKeys; ++keyIndex) {
+                    Key key = row.mKeys.get(keyIndex);
+                    key.width *= scaleFactor;
+                    key.x = x;
+                    x += key.width + key.gap;
+                }
+            }
+        }
+        mTotalWidth = newWidth;
+        // TODO: This does not adjust the vertical placement according to the new size.
+        // The main problem in the previous code was horizontal placement/size, but we should
+        // also recalculate the vertical sizes/positions when we get this resize call.
     }
     
     public List<Key> getKeys() {
@@ -749,7 +787,7 @@
         Row currentRow = null;
         Resources res = context.getResources();
         boolean skipRow = false;
-        
+
         try {
             int event;
             while ((event = parser.next()) != XmlResourceParser.END_DOCUMENT) {
@@ -759,6 +797,7 @@
                         inRow = true;
                         x = 0;
                         currentRow = createRowFromXml(res, parser);
+                        rows.add(currentRow);
                         skipRow = currentRow.mode != 0 && currentRow.mode != mKeyboardMode;
                         if (skipRow) {
                             skipToEndOfRow(parser);
@@ -781,6 +820,7 @@
                         } else if (key.codes[0] == KEYCODE_ALT) {
                             mModifierKeys.add(key);
                         }
+                        currentRow.mKeys.add(key);
                     } else if (TAG_KEYBOARD.equals(tag)) {
                         parseKeyboardAttributes(res, parser);
                     }
diff --git a/core/java/android/inputmethodservice/KeyboardView.java b/core/java/android/inputmethodservice/KeyboardView.java
index 05444f6..1119c1e 100644
--- a/core/java/android/inputmethodservice/KeyboardView.java
+++ b/core/java/android/inputmethodservice/KeyboardView.java
@@ -376,6 +376,7 @@
         initGestureDetector();
     }
 
+
     private void initGestureDetector() {
         mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
             @Override
@@ -615,6 +616,9 @@
     @Override
     public void onSizeChanged(int w, int h, int oldw, int oldh) {
         super.onSizeChanged(w, h, oldw, oldh);
+        if (mKeyboard != null) {
+            mKeyboard.resize(w, h);
+        }
         // Release the buffer, if any and it will be reallocated on the next draw
         mBuffer = null;
     }
diff --git a/core/java/android/net/MobileDataStateTracker.java b/core/java/android/net/MobileDataStateTracker.java
index bcf6239..62bb965 100644
--- a/core/java/android/net/MobileDataStateTracker.java
+++ b/core/java/android/net/MobileDataStateTracker.java
@@ -56,7 +56,7 @@
 public class MobileDataStateTracker implements NetworkStateTracker {
 
     private static final String TAG = "MobileDataStateTracker";
-    private static final boolean DBG = true;
+    private static final boolean DBG = false;
     private static final boolean VDBG = false;
 
     private Phone.DataState mMobileDataState;
diff --git a/core/java/android/net/ProxyProperties.java b/core/java/android/net/ProxyProperties.java
index 44dbec1..cd799da 100644
--- a/core/java/android/net/ProxyProperties.java
+++ b/core/java/android/net/ProxyProperties.java
@@ -137,6 +137,8 @@
             if (mExclusionList != null) {
                     sb.append(" xl=").append(mExclusionList);
             }
+        } else {
+            sb.append("[ProxyProperties.mHost == null]");
         }
         return sb.toString();
     }
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index bc5994e..bc05078 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -1882,6 +1882,11 @@
         /**
          * Settings to backup. This is here so that it's in the same place as the settings
          * keys and easy to update.
+         *
+         * NOTE: Settings are backed up and restored in the order they appear
+         *       in this array. If you have one setting depending on another,
+         *       make sure that they are ordered appropriately.
+         *
          * @hide
          */
         public static final String[] SETTINGS_TO_BACKUP = {
@@ -4048,6 +4053,12 @@
         public static final String PACKAGE_VERIFIER_TIMEOUT = "verifier_timeout";
 
         /**
+         * This are the settings to be backed up.
+         *
+         * NOTE: Settings are backed up and restored in the order they appear
+         *       in this array. If you have one setting depending on another,
+         *       make sure that they are ordered appropriately.
+         *
          * @hide
          */
         public static final String[] SETTINGS_TO_BACKUP = {
@@ -4056,11 +4067,11 @@
             PARENTAL_CONTROL_ENABLED,
             PARENTAL_CONTROL_REDIRECT_URL,
             USB_MASS_STORAGE_ENABLED,
-            ACCESSIBILITY_ENABLED,
             ACCESSIBILITY_SCRIPT_INJECTION,
             BACKUP_AUTO_RESTORE,
             ENABLED_ACCESSIBILITY_SERVICES,
             TOUCH_EXPLORATION_ENABLED,
+            ACCESSIBILITY_ENABLED,
             TTS_USE_DEFAULTS,
             TTS_DEFAULT_RATE,
             TTS_DEFAULT_PITCH,
diff --git a/core/java/android/text/method/Touch.java b/core/java/android/text/method/Touch.java
index 3f9b945..106a801 100644
--- a/core/java/android/text/method/Touch.java
+++ b/core/java/android/text/method/Touch.java
@@ -35,44 +35,39 @@
      * Y position.
      */
     public static void scrollTo(TextView widget, Layout layout, int x, int y) {
-        int padding = widget.getTotalPaddingTop() +
-                      widget.getTotalPaddingBottom();
-        int top = layout.getLineForVertical(y);
-        int bottom = layout.getLineForVertical(y + widget.getHeight() -
-                                               padding);
+        final int verticalPadding = widget.getTotalPaddingTop() + widget.getTotalPaddingBottom();
+        final int top = layout.getLineForVertical(y);
+        final int bottom = layout.getLineForVertical(y + widget.getHeight() - verticalPadding);
 
         int left = Integer.MAX_VALUE;
         int right = 0;
-        Alignment a = null;
-        boolean ltr = true;
+        Alignment a = layout.getParagraphAlignment(top);
+        boolean ltr = layout.getParagraphDirection(top) > 0;
 
         for (int i = top; i <= bottom; i++) {
             left = (int) Math.min(left, layout.getLineLeft(i));
             right = (int) Math.max(right, layout.getLineRight(i));
-
-            if (a == null) {
-                a = layout.getParagraphAlignment(i);
-                ltr = layout.getParagraphDirection(i) > 0;
-            }
         }
 
-        padding = widget.getTotalPaddingLeft() + widget.getTotalPaddingRight();
-        int width = widget.getWidth();
-        int diff = 0;
+        final int hoizontalPadding = widget.getTotalPaddingLeft() + widget.getTotalPaddingRight();
+        final int availableWidth = widget.getWidth() - hoizontalPadding;
+        final int actualWidth = right - left;
 
-        // align_opposite does NOT mean align_right, we need the paragraph
-        // direction to resolve it to left or right
-        if (right - left < width - padding) {
+        if (actualWidth < availableWidth) {
             if (a == Alignment.ALIGN_CENTER) {
-                diff = (width - padding - (right - left)) / 2;
-            } else if (ltr == (a == Alignment.ALIGN_OPPOSITE)) {
-                diff = width - padding - (right - left);
+                x = left - ((availableWidth - actualWidth) / 2);
+            } else if ((ltr && (a == Alignment.ALIGN_OPPOSITE)) || (a == Alignment.ALIGN_RIGHT)) {
+                // align_opposite does NOT mean align_right, we need the paragraph
+                // direction to resolve it to left or right
+                x = left - (availableWidth - actualWidth);
+            } else {
+                x = left;
             }
+        } else {
+            x = Math.min(x, right - availableWidth);
+            x = Math.max(x, left);
         }
 
-        x = Math.min(x, right - (width - padding) - diff);
-        x = Math.max(x, left - diff);
-
         widget.scrollTo(x, y);
     }
 
diff --git a/core/java/android/view/ActionProvider.java b/core/java/android/view/ActionProvider.java
index 5601dc5..ed976ab 100644
--- a/core/java/android/view/ActionProvider.java
+++ b/core/java/android/view/ActionProvider.java
@@ -58,6 +58,7 @@
  * @see MenuItem#getActionProvider()
  */
 public abstract class ActionProvider {
+    private SubUiVisibilityListener mSubUiVisibilityListener;
 
     /**
      * Creates a new instance.
@@ -138,4 +139,31 @@
      */
     public void onPrepareSubMenu(SubMenu subMenu) {
     }
+
+    /**
+     * Notify the system that the visibility of an action view's sub-UI such as
+     * an anchored popup has changed. This will affect how other system
+     * visibility notifications occur.
+     *
+     * @hide Pending future API approval
+     */
+    public void subUiVisibilityChanged(boolean isVisible) {
+        if (mSubUiVisibilityListener != null) {
+            mSubUiVisibilityListener.onSubUiVisibilityChanged(isVisible);
+        }
+    }
+
+    /**
+     * @hide Internal use only
+     */
+    public void setSubUiVisibilityListener(SubUiVisibilityListener listener) {
+        mSubUiVisibilityListener = listener;
+    }
+
+    /**
+     * @hide Internal use only
+     */
+    public interface SubUiVisibilityListener {
+        public void onSubUiVisibilityChanged(boolean isVisible);
+    }
 }
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index 335c66b..55c821d 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -163,15 +163,13 @@
 
     // These can only be called with the SET_ORIENTATION permission.
     /**
-     * Change the current screen rotation, constants as per
-     * {@link android.view.Surface}.
-     * @param rotation the intended rotation.
+     * Update the current screen rotation based on the current state of
+     * the world.
      * @param alwaysSendConfiguration Flag to force a new configuration to
      * be evaluated.  This can be used when there are other parameters in
      * configuration that are changing.
-     * @param animFlags Animation flags as per {@link android.view.Surface}.
      */
-    void setRotation(int rotation, boolean alwaysSendConfiguration, int animFlags);
+    void updateRotation(boolean alwaysSendConfiguration);
 
     /**
      * Retrieve the current screen orientation, constants as per
diff --git a/core/java/android/view/Surface.java b/core/java/android/view/Surface.java
index 3880bc45..64d3d31 100644
--- a/core/java/android/view/Surface.java
+++ b/core/java/android/view/Surface.java
@@ -207,9 +207,6 @@
 
     /** Enable dithering when compositing this surface @hide */
     public static final int SURFACE_DITHER    = 0x04;
-    
-    /** Disable the orientation animation @hide */
-    public static final int FLAGS_ORIENTATION_ANIMATION_DISABLE = 0x000000001;
 
     // The mSurfaceControl will only be present for Surfaces used by the window
     // server or system processes. When this class is parceled we defer to the
@@ -393,7 +390,7 @@
      * set the orientation of the given display.
      * @param display
      * @param orientation
-     * @param flags
+     * @param flags Currently unused, set to 0.
      * @hide
      */
     public static native   void setOrientation(int display, int orientation, int flags);
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index ca06b9c..f993160 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -12969,15 +12969,13 @@
      * Request that the visibility of the status bar be changed.
      * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
      * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
-     *
-     * This value will be re-applied immediately, even if the flags have not changed, so a view may
-     * easily reassert a particular SystemUiVisibility condition even if the system UI itself has
-     * since countermanded the original request.
      */
     public void setSystemUiVisibility(int visibility) {
-        mSystemUiVisibility = visibility;
-        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
-            mParent.recomputeViewAttributes(this);
+        if (visibility != mSystemUiVisibility) {
+            mSystemUiVisibility = visibility;
+            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
+                mParent.recomputeViewAttributes(this);
+            }
         }
     }
 
diff --git a/core/java/android/view/WindowManagerPolicy.java b/core/java/android/view/WindowManagerPolicy.java
index c07faf6..1dbb083 100644
--- a/core/java/android/view/WindowManagerPolicy.java
+++ b/core/java/android/view/WindowManagerPolicy.java
@@ -375,12 +375,6 @@
     /** Screen turned off because of proximity sensor */
     public final int OFF_BECAUSE_OF_PROX_SENSOR = 4;
 
-    /**
-     * Magic constant to {@link IWindowManager#setRotation} to not actually
-     * modify the rotation.
-     */
-    public final int USE_LAST_ROTATION = -1000;
-
     /** When not otherwise specified by the activity's screenOrientation, rotation should be
      * determined by the system (that is, using sensors). */
     public final int USER_ROTATION_FREE = 0;
@@ -856,22 +850,30 @@
     public boolean inKeyguardRestrictedKeyInputMode();
 
     /**
-     * Given an orientation constant
-     * ({@link android.content.pm.ActivityInfo#SCREEN_ORIENTATION_LANDSCAPE
-     * ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE} or
-     * {@link android.content.pm.ActivityInfo#SCREEN_ORIENTATION_PORTRAIT
-     * ActivityInfo.SCREEN_ORIENTATION_PORTRAIT}), return a surface
-     * rotation.
+     * Given an orientation constant, returns the appropriate surface rotation,
+     * taking into account sensors, docking mode, rotation lock, and other factors.
+     *
+     * @param orientation An orientation constant, such as
+     * {@link android.content.pm.ActivityInfo#SCREEN_ORIENTATION_LANDSCAPE}.
+     * @param lastRotation The most recently used rotation.
+     * @return The surface rotation to use.
      */
-    public int rotationForOrientationLw(int orientation, int lastRotation,
-            boolean displayEnabled);
-    
+    public int rotationForOrientationLw(int orientation, int lastRotation);
+
     /**
-     * Return the currently locked screen rotation, if any.  Return
-     * Surface.ROTATION_0, Surface.ROTATION_90, Surface.ROTATION_180, or
-     * Surface.ROTATION_270 if locked; return -1 if not locked.
+     * Given an orientation constant and a rotation, returns true if the rotation
+     * has compatible metrics to the requested orientation.  For example, if
+     * the application requested landscape and got seascape, then the rotation
+     * has compatible metrics; if the application requested portrait and got landscape,
+     * then the rotation has incompatible metrics; if the application did not specify
+     * a preference, then anything goes.
+     *
+     * @param orientation An orientation constant, such as
+     * {@link android.content.pm.ActivityInfo#SCREEN_ORIENTATION_LANDSCAPE}.
+     * @param rotation The rotation to check.
+     * @return True if the rotation is compatible with the requested orientation.
      */
-    public int getLockedRotationLw();
+    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation);
 
     /**
      * Called when the system is mostly done booting to determine whether
diff --git a/core/java/android/view/WindowOrientationListener.java b/core/java/android/view/WindowOrientationListener.java
index 76b47ca..726bf4a 100755
--- a/core/java/android/view/WindowOrientationListener.java
+++ b/core/java/android/view/WindowOrientationListener.java
@@ -118,14 +118,13 @@
 
     /**
      * Gets the current orientation.
-     * @param lastRotation
-     * @return
+     * @return The current rotation, or -1 if unknown.
      */
-    public int getCurrentRotation(int lastRotation) {
+    public int getCurrentRotation() {
         if (mEnabled) {
-            return mSensorEventListener.getCurrentRotation(lastRotation);
+            return mSensorEventListener.getCurrentRotation();
         }
-        return lastRotation;
+        return -1;
     }
 
     /**
@@ -342,8 +341,8 @@
             mOrientationListener = orientationListener;
         }
 
-        public int getCurrentRotation(int lastRotation) {
-            return mRotation != ROTATION_UNKNOWN ? mRotation : lastRotation;
+        public int getCurrentRotation() {
+            return mRotation; // may be -1, if unknown
         }
 
         @Override
diff --git a/core/java/android/view/textservice/TextServicesManager.java b/core/java/android/view/textservice/TextServicesManager.java
index 01587aa..b06c112 100644
--- a/core/java/android/view/textservice/TextServicesManager.java
+++ b/core/java/android/view/textservice/TextServicesManager.java
@@ -223,7 +223,7 @@
         try {
             sService.setSpellCheckerEnabled(enabled);
         } catch (RemoteException e) {
-            Log.e(TAG, "Error in setSpellCheckerSubtype:" + e);
+            Log.e(TAG, "Error in setSpellCheckerEnabled:" + e);
         }
     }
 
@@ -234,7 +234,7 @@
         try {
             return sService.isSpellCheckerEnabled();
         } catch (RemoteException e) {
-            Log.e(TAG, "Error in setSpellCheckerSubtype:" + e);
+            Log.e(TAG, "Error in isSpellCheckerEnabled:" + e);
             return false;
         }
     }
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index 122a717..47629c4 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -7170,6 +7170,14 @@
     }
 
     /**
+     * Return the overview scale of the WebView
+     * @return The overview scale.
+     */
+    float getZoomOverviewScale() {
+        return mZoomManager.getZoomOverviewScale();
+    }
+
+    /**
      * @return TRUE if the WebView can be zoomed in.
      */
     public boolean canZoomIn() {
diff --git a/core/java/android/webkit/WebViewCore.java b/core/java/android/webkit/WebViewCore.java
index 48359d44..470e843 100644
--- a/core/java/android/webkit/WebViewCore.java
+++ b/core/java/android/webkit/WebViewCore.java
@@ -2512,10 +2512,13 @@
     // called by JNI
     private void restoreScale(float scale, float textWrapScale) {
         if (mBrowserFrame.firstLayoutDone() == false) {
-            final float defaultScale = mWebView.getDefaultZoomScale();
-            mRestoredScale = (scale <= 0.0) ? defaultScale : scale;
+            // If restored scale and textWrapScale are 0, set them to
+            // overview and reading level scale respectively.
+            mRestoredScale = (scale <= 0.0)
+                ? mWebView.getZoomOverviewScale() : scale;
             if (mSettings.getUseWideViewPort()) {
-                mRestoredTextWrapScale = (textWrapScale <= 0.0) ? defaultScale : textWrapScale;
+                mRestoredTextWrapScale = (textWrapScale <= 0.0)
+                    ? mWebView.getReadingLevelScale() : textWrapScale;
             }
         }
     }
diff --git a/core/java/android/webkit/ZoomManager.java b/core/java/android/webkit/ZoomManager.java
index 7ca6aeb..7f526e7 100644
--- a/core/java/android/webkit/ZoomManager.java
+++ b/core/java/android/webkit/ZoomManager.java
@@ -1128,12 +1128,6 @@
                     mTextWrapScale = Math.max(mTextWrapScale, overviewScale);
                 }
                 reflowText = exceedsMinScaleIncrement(mTextWrapScale, scale);
-            } else {
-                // In case of restored scale, treat defaultScale as overview since
-                // it usually means the previous scale is not saved.
-                if (scale == mDefaultScale && settings.getLoadWithOverviewMode()) {
-                    scale = overviewScale;
-                }
             }
             mInitialZoomOverview = settings.getLoadWithOverviewMode() &&
                     !exceedsMinScaleIncrement(scale, overviewScale);
diff --git a/core/java/android/widget/ActivityChooserView.java b/core/java/android/widget/ActivityChooserView.java
index 25af3fa..c6e63c3 100644
--- a/core/java/android/widget/ActivityChooserView.java
+++ b/core/java/android/widget/ActivityChooserView.java
@@ -16,6 +16,8 @@
 
 package android.widget;
 
+import com.android.internal.R;
+
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
@@ -25,6 +27,7 @@
 import android.database.DataSetObserver;
 import android.graphics.drawable.Drawable;
 import android.util.AttributeSet;
+import android.view.ActionProvider;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
@@ -32,8 +35,6 @@
 import android.view.ViewTreeObserver.OnGlobalLayoutListener;
 import android.widget.ActivityChooserModel.ActivityChooserModelClient;
 
-import com.android.internal.R;
-
 /**
  * This class is a view for choosing an activity for handling a given {@link Intent}.
  * <p>
@@ -105,6 +106,11 @@
     private final int mListPopupMaxWidth;
 
     /**
+     * The ActionProvider hosting this view, if applicable.
+     */
+    ActionProvider mProvider;
+
+    /**
      * Observer for the model data.
      */
     private final DataSetObserver mModelDataSetOberver = new DataSetObserver() {
@@ -129,6 +135,9 @@
                     getListPopupWindow().dismiss();
                 } else {
                     getListPopupWindow().show();
+                    if (mProvider != null) {
+                        mProvider.subUiVisibilityChanged(true);
+                    }
                 }
             }
         }
@@ -260,6 +269,14 @@
     }
 
     /**
+     * Set the provider hosting this view, if applicable.
+     * @hide Internal use only
+     */
+    public void setProvider(ActionProvider provider) {
+        mProvider = provider;
+    }
+
+    /**
      * Shows the popup window with activities.
      *
      * @return True if the popup was shown, false if already showing.
@@ -287,9 +304,13 @@
 
         mAdapter.setMaxActivityCount(maxActivityCount);
 
+        final boolean defaultActivityButtonShown =
+            mDefaultActivityButton.getVisibility() == VISIBLE;
+
         final int activityCount = mAdapter.getActivityCount();
+        final int maxActivityCountOffset = defaultActivityButtonShown ? 1 : 0;
         if (maxActivityCount != ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_UNLIMITED
-                && activityCount > maxActivityCount + 1) {
+                && activityCount > maxActivityCount + maxActivityCountOffset) {
             mAdapter.setShowFooterView(true);
         } else {
             mAdapter.setShowFooterView(false);
@@ -297,8 +318,6 @@
 
         ListPopupWindow popupWindow = getListPopupWindow();
         if (!popupWindow.isShowing()) {
-            final boolean defaultActivityButtonShown =
-                mDefaultActivityButton.getVisibility() == VISIBLE;
             if (mIsSelectingDefaultActivity || !defaultActivityButtonShown) {
                 mAdapter.setShowDefaultActivity(true, defaultActivityButtonShown);
             } else {
@@ -307,6 +326,9 @@
             final int contentWidth = Math.min(mAdapter.measureContentWidth(), mListPopupMaxWidth);
             popupWindow.setContentWidth(contentWidth);
             popupWindow.show();
+            if (mProvider != null) {
+                mProvider.subUiVisibilityChanged(true);
+            }
         }
     }
 
@@ -525,6 +547,9 @@
         // PopUpWindow.OnDismissListener#onDismiss
         public void onDismiss() {
             notifyOnDismissListener();
+            if (mProvider != null) {
+                mProvider.subUiVisibilityChanged(false);
+            }
         }
 
         private void notifyOnDismissListener() {
diff --git a/core/java/android/widget/PopupMenu.java b/core/java/android/widget/PopupMenu.java
index 17512d8..6a6d767 100644
--- a/core/java/android/widget/PopupMenu.java
+++ b/core/java/android/widget/PopupMenu.java
@@ -157,6 +157,8 @@
      * @hide
      */
     public boolean onOpenSubMenu(MenuBuilder subMenu) {
+        if (subMenu == null) return false;
+
         if (!subMenu.hasVisibleItems()) {
             return true;
         }
diff --git a/core/java/android/widget/ShareActionProvider.java b/core/java/android/widget/ShareActionProvider.java
index 6e29024..3627890 100644
--- a/core/java/android/widget/ShareActionProvider.java
+++ b/core/java/android/widget/ShareActionProvider.java
@@ -169,6 +169,7 @@
         mContext.getTheme().resolveAttribute(R.attr.actionModeShareDrawable, outTypedValue, true);
         Drawable drawable = mContext.getResources().getDrawable(outTypedValue.resourceId);
         activityChooserView.setExpandActivityOverflowButtonDrawable(drawable);
+        activityChooserView.setProvider(this);
 
         return activityChooserView;
     }
diff --git a/core/java/com/android/internal/view/menu/ActionMenuPresenter.java b/core/java/com/android/internal/view/menu/ActionMenuPresenter.java
index fba6a5a..0db1ccc 100644
--- a/core/java/com/android/internal/view/menu/ActionMenuPresenter.java
+++ b/core/java/com/android/internal/view/menu/ActionMenuPresenter.java
@@ -24,6 +24,7 @@
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.util.SparseBooleanArray;
+import android.view.ActionProvider;
 import android.view.MenuItem;
 import android.view.SoundEffectConstants;
 import android.view.View;
@@ -40,7 +41,8 @@
 /**
  * MenuPresenter for building action menus as seen in the action bar and action modes.
  */
-public class ActionMenuPresenter extends BaseMenuPresenter {
+public class ActionMenuPresenter extends BaseMenuPresenter
+        implements ActionProvider.SubUiVisibilityListener {
     private static final String TAG = "ActionMenuPresenter";
 
     private View mOverflowButton;
@@ -187,6 +189,17 @@
     public void updateMenuView(boolean cleared) {
         super.updateMenuView(cleared);
 
+        if (mMenu != null) {
+            final ArrayList<MenuItemImpl> actionItems = mMenu.getActionItems();
+            final int count = actionItems.size();
+            for (int i = 0; i < count; i++) {
+                final ActionProvider provider = actionItems.get(i).getActionProvider();
+                if (provider != null) {
+                    provider.setSubUiVisibilityListener(this);
+                }
+            }
+        }
+
         final boolean hasOverflow = mReserveOverflow && mMenu != null &&
                 mMenu.getNonActionItems().size() > 0;
         if (hasOverflow) {
@@ -483,6 +496,16 @@
         }
     }
 
+    @Override
+    public void onSubUiVisibilityChanged(boolean isVisible) {
+        if (isVisible) {
+            // Not a submenu, but treat it like one.
+            super.onSubMenuSelected(null);
+        } else {
+            mMenu.close(false);
+        }
+    }
+
     private static class SavedState implements Parcelable {
         public int openSubMenuId;
 
@@ -590,7 +613,6 @@
         @Override
         public void onDismiss() {
             super.onDismiss();
-            mSubMenu.close();
             mActionButtonPopup = null;
             mOpenSubMenuId = 0;
         }
@@ -600,12 +622,17 @@
 
         @Override
         public boolean onOpenSubMenu(MenuBuilder subMenu) {
+            if (subMenu == null) return false;
+
             mOpenSubMenuId = ((SubMenuBuilder) subMenu).getItem().getItemId();
             return false;
         }
 
         @Override
         public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
+            if (menu instanceof SubMenuBuilder) {
+                ((SubMenuBuilder) menu).getRootMenu().close(false);
+            }
         }
     }
 
diff --git a/core/java/com/android/internal/view/menu/IconMenuPresenter.java b/core/java/com/android/internal/view/menu/IconMenuPresenter.java
index d1b1dae..24ddad6 100644
--- a/core/java/com/android/internal/view/menu/IconMenuPresenter.java
+++ b/core/java/com/android/internal/view/menu/IconMenuPresenter.java
@@ -187,7 +187,9 @@
 
         @Override
         public boolean onOpenSubMenu(MenuBuilder subMenu) {
-            mOpenSubMenuId = ((SubMenuBuilder) subMenu).getItem().getItemId();
+            if (subMenu != null) {
+                mOpenSubMenuId = ((SubMenuBuilder) subMenu).getItem().getItemId();
+            }
             return false;
         }
 
diff --git a/core/res/res/layout/keyguard_screen_password_landscape.xml b/core/res/res/layout/keyguard_screen_password_landscape.xml
index 694db50..3343d8b 100644
--- a/core/res/res/layout/keyguard_screen_password_landscape.xml
+++ b/core/res/res/layout/keyguard_screen_password_landscape.xml
@@ -170,6 +170,7 @@
     <com.android.internal.widget.PasswordEntryKeyboardView android:id="@+id/keyboard"
         android:layout_width="270dip"
         android:layout_height="wrap_content"
+        android:layout_marginLeft="4dip"
         android:layout_marginRight="4dip"
         android:background="#40000000"
         android:layout_marginTop="5dip"
diff --git a/core/res/res/layout/keyguard_screen_password_portrait.xml b/core/res/res/layout/keyguard_screen_password_portrait.xml
index 27a51da..2a66d7d 100644
--- a/core/res/res/layout/keyguard_screen_password_portrait.xml
+++ b/core/res/res/layout/keyguard_screen_password_portrait.xml
@@ -132,7 +132,7 @@
     <!-- Numeric keyboard -->
     <com.android.internal.widget.PasswordEntryKeyboardView android:id="@+id/keyboard"
         android:layout_width="match_parent"
-        android:layout_height="wrap_content"
+        android:layout_marginLeft="4dip"
         android:layout_marginRight="4dip"
         android:paddingTop="4dip"
         android:paddingBottom="4dip"
diff --git a/core/res/res/values-sw600dp/config.xml b/core/res/res/values-sw600dp/config.xml
index 13bbac6..7fa7658 100644
--- a/core/res/res/values-sw600dp/config.xml
+++ b/core/res/res/values-sw600dp/config.xml
@@ -32,5 +32,8 @@
     <!-- see comment in values/config.xml -->
     <dimen name="config_prefDialogWidth">580dp</dimen>
     
+    <!-- If true, the screen can be rotated via the accelerometer in all 4
+         rotations as the default behavior. -->
+    <bool name="config_allowAllRotations">true</bool>
 </resources>
 
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index 847afa0..11531fc 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -1561,8 +1561,21 @@
             <enum name="xhdpi" value="320" />
         </attr>
     </declare-styleable>
-    
-    
+
+    <!-- The attribute that holds a Base64-encoded public key. -->
+    <attr name="publicKey" format="string" />
+
+    <!-- Attributes relating to a package verifier -->
+    <declare-styleable name="AndroidManifestPackageVerifier" parent="AndroidManifest">
+        <!-- Specifies the Java-style package name that defines this
+             package verifier. -->
+        <attr name="name" />
+
+        <!-- The Base64 encoded public key of the package verifier's
+             signature. -->
+        <attr name="publicKey" />
+    </declare-styleable>
+
     <!-- Declaration of an {@link android.content.Intent} object in XML.  May
          also include zero or more {@link #IntentCategory <category> and
          {@link #Extra <extra>} tags. -->
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 1e5358e..5eb3e5a 100755
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -231,7 +231,7 @@
 
     <!-- If true, the screen can be rotated via the accelerometer in all 4
          rotations as the default behavior. -->
-    <bool name="config_allowAllRotations">true</bool>
+    <bool name="config_allowAllRotations">false</bool>
 
     <!-- If true, the direction rotation is applied to get to an application's requested
          orientation is reversed.  Normally, the model is that landscape is
@@ -400,9 +400,9 @@
     <!-- Diable lockscreen rotation by default -->
     <bool name="config_enableLockScreenRotation">false</bool>
 
-    <!-- Diable puk unlockscreen by default.
+    <!-- Enable puk unlockscreen by default.
          If unlock screen is disabled, the puk should be unlocked through Emergency Dialer -->
-    <bool name="config_enable_puk_unlock_screen">false</bool>
+    <bool name="config_enable_puk_unlock_screen">true</bool>
 
     <!-- Control the behavior when the user long presses the home button.
             0 - Nothing
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 848fb8b..97d5afe 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -1768,6 +1768,7 @@
   <public type="attr" name="listPreferredItemPaddingLeft" id="0x010103a3" />
   <public type="attr" name="listPreferredItemPaddingRight" id="0x010103a4" />
   <public type="attr" name="requiresFadingEdge" id="0x010103a5" />
+  <public type="attr" name="publicKey" id="0x010103a6" />
 
   <public type="style" name="TextAppearance.SuggestionHighlight" id="0x01030118" />
   <public type="style" name="Theme.Holo.Light.DarkActionBar" id="0x01030119" />
diff --git a/data/fonts/AndroidClock.ttf b/data/fonts/AndroidClock.ttf
index 7ebc963..3fa6d88 100644
--- a/data/fonts/AndroidClock.ttf
+++ b/data/fonts/AndroidClock.ttf
Binary files differ
diff --git a/data/fonts/AndroidClock_Highlight.ttf b/data/fonts/AndroidClock_Highlight.ttf
index 7ebc963..3fa6d88 100644
--- a/data/fonts/AndroidClock_Highlight.ttf
+++ b/data/fonts/AndroidClock_Highlight.ttf
Binary files differ
diff --git a/data/fonts/AndroidClock_Solid.ttf b/data/fonts/AndroidClock_Solid.ttf
index 7ebc963..3fa6d88 100644
--- a/data/fonts/AndroidClock_Solid.ttf
+++ b/data/fonts/AndroidClock_Solid.ttf
Binary files differ
diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs
index 9c3a0be..3716583 100644
--- a/docs/html/guide/guide_toc.cs
+++ b/docs/html/guide/guide_toc.cs
@@ -222,8 +222,7 @@
           <li><a href="<?cs var:toroot ?>guide/topics/manifest/receiver-element.html">&lt;receiver&gt;</a></li>
           <li><a href="<?cs var:toroot ?>guide/topics/manifest/service-element.html">&lt;service&gt;</a></li>
           <li><a href="<?cs var:toroot ?>guide/topics/manifest/supports-gl-texture-element.html">&lt;supports-gl-texture&gt;</a></li>
-          <li><a href="<?cs var:toroot ?>guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a>
-              <span class="new">updated</span></li>  <!-- ##api level 4## -->
+          <li><a href="<?cs var:toroot ?>guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a></li><!-- ##api level 4## -->
           <li><a href="<?cs var:toroot ?>guide/topics/manifest/uses-configuration-element.html">&lt;uses-configuration&gt;</a></li>
           <li><a href="<?cs var:toroot ?>guide/topics/manifest/uses-feature-element.html">&lt;uses-feature&gt;</a></li> <!-- ##api level 4## -->
           <li><a href="<?cs var:toroot ?>guide/topics/manifest/uses-library-element.html">&lt;uses-library&gt;</a></li>
@@ -244,7 +243,7 @@
               </a></li>
           <li><a href="<?cs var:toroot ?>guide/topics/graphics/opengl.html">
                 <span class="en">3D with OpenGL</span>
-              </a><span class="new">updated</span></li>
+              </a></li>
           <li><a href="<?cs var:toroot ?>guide/topics/graphics/animation.html">
                 <span class="en">Property Animation</span>
               </a></li>
@@ -271,7 +270,7 @@
 
       <li><a href="<?cs var:toroot ?>guide/topics/media/index.html">
             <span class="en">Media</span>
-          </a><span class="new">updated</span></li>
+          </a></li>
       <li>
         <a href="<?cs var:toroot ?>guide/topics/clipboard/copy-paste.html">
             <span class="en">Copy and Paste</span>
@@ -408,7 +407,6 @@
       </li>
       <li><a href="<?cs var:toroot ?>guide/market/publishing/multiple-apks.html">
           <span class="en">Multiple APK Support</span></a>
-          <span class="new">new!</span>
       </li>
     </ul>
   </li>
@@ -569,7 +567,7 @@
           </a></div>
         <ul>
           <li><a href="<?cs var:toroot ?>guide/developing/tools/adb.html">adb</a></li>
-          <li><a href="<?cs var:toroot ?>guide/developing/tools/adt.html">ADT</a> <span class="new">new!</span></li>
+          <li><a href="<?cs var:toroot ?>guide/developing/tools/adt.html">ADT</a></li>
           <li><a href="<?cs var:toroot ?>guide/developing/tools/android.html">android</a></li>
           <li><a href="<?cs var:toroot ?>guide/developing/tools/bmgr.html">bmgr</a>
           <li><a href="<?cs var:toroot ?>guide/developing/tools/dmtracedump.html">dmtracedump</a></li>
@@ -672,14 +670,14 @@
       <li class="toggle-list">
         <div><a href="<?cs var:toroot ?>guide/practices/screens_support.html">
           <span class="en">Supporting Multiple Screens</span>
-        </a> <span class="new">updated</span></div>
+        </a></div>
         <ul>
           <li><a href="<?cs var:toroot ?>guide/practices/screens-distribution.html">
             <span class="en">Distributing to Specific Screens</span>
           </a></li>
           <li><a href="<?cs var:toroot ?>guide/practices/screen-compat-mode.html">
             <span class="en">Screen Compatibility Mode</span>
-          </a> <span class="new">new!</span></li>
+          </a></li>
           <li><a href="<?cs var:toroot ?>guide/practices/screens-support-1.5.html">
             <span class="en">Strategies for Android 1.5</span>
           </a></li>
@@ -737,11 +735,11 @@
       <li class="toggle-list">
         <div><a href="<?cs var:toroot ?>guide/practices/design/performance.html">
             <span class="en">Designing for Performance</span>
-          </a> <span class="new-child">new!</span></div>
+          </a></div>
         <ul>
           <li><a href="<?cs var:toroot ?>guide/practices/design/jni.html">
                 <span class="en">JNI Tips</span>
-              </a> <span class="new">new!</span></li>
+              </a></li>
         </ul>
       </li>
       <li><a href="<?cs var:toroot ?>guide/practices/design/responsiveness.html">
diff --git a/docs/html/guide/topics/ui/notifiers/notifications.jd b/docs/html/guide/topics/ui/notifiers/notifications.jd
index abc945a..f12c5ee 100644
--- a/docs/html/guide/topics/ui/notifiers/notifications.jd
+++ b/docs/html/guide/topics/ui/notifiers/notifications.jd
@@ -12,7 +12,7 @@
       <li>You can attach an intent to your notification that the system will initiate when the
 user clicks it</li>
     </ul>
-    
+
     <h2>In this document</h2>
     <ol>
       <li><a href="#Basics">The Basics</a></li>
@@ -26,7 +26,7 @@
           <li><a href="#More">More features</a></li>
         </ol>
       </li>
-      <li><a href="#CustomExpandedView">Creating a Custom Expanded View</a></li>
+      <li><a href="#CustomExpandedView">Creating a Custom Notification Layout</a></li>
     </ol>
     <h2>Key classes</h2>
     <ol>
@@ -36,57 +36,63 @@
   </div>
 </div>
 
-<p>A status bar notification adds an icon to the system's status bar 
-(with an optional ticker-text message) and an expanded message in the "Notifications" window.
-When the user selects the expanded message, Android fires an 
-{@link android.content.Intent} that is defined by the notification (usually to launch an 
-{@link android.app.Activity}).
+<p>A status bar notification adds an icon to the system's status bar
+(with an optional ticker-text message) and a notification message in the notifications window.
+When the user selects the notification, Android fires an
+{@link android.content.Intent} that is defined by the {@link android.app.Notification} (usually to
+launch an {@link android.app.Activity}).
 You can also configure the notification to alert the user with a sound, a vibration, and flashing
 lights on the device.</p>
 
 <p>A status bar notification should be used for any case in
-which a background Service needs to alert the user about an event that requires a response. A background Service 
-<strong>should never</strong> launch an Activity on its own in order to receive user interaction.
-The Service should instead create a status bar notification that will launch the Activity
+which a background service needs to alert the user about an event that requires a response. A
+background service
+<strong>should never</strong> launch an activity on its own in order to receive user interaction.
+The service should instead create a status bar notification that will launch the activity
 when selected by the user.</p>
 
-<p>The screenshot below shows the status bar with a notification icon on the left side.</p>
+<p>Figure 1 shows the status bar with a notification icon on the left side.</p>
 <img src="{@docRoot}images/status_bar.png" alt="" />
+<p class="img-caption"><strong>Figure 1.</strong> Status bar with a notification.</p>
 
-<p>The next screenshot shows the notification's expanded message in the "Notifications" window.
-The user can reveal the Notifications window by pulling down the status bar
-(or selecting <em>Notifications</em> from the Home options menu).</p>
+<p>Figure 2 shows the notification's message in the notifications window.</p>
+
 <img src="{@docRoot}images/notifications_window.png" alt="" />
+<p class="img-caption"><strong>Figure 2.</strong> The notifications window.</p>
 
 
 <h2 id="Basics">The Basics</h2>
 
-<p>An {@link android.app.Activity} or {@link android.app.Service} can initiate a status bar 
-notification. Because an Activity can perform actions only while it is
-active and in focus, you should create your status bar notifications from a 
-Service. This way, the notification can be created from the background, 
+<p>An {@link android.app.Activity} or {@link android.app.Service} can initiate a status bar
+notification. Because an activity can perform actions only while it is
+running in the foreground and its window has focus, you will usually create status bar notifications
+from a
+service. This way, the notification can be created from the background,
 while the user is using another application or
 while the device is asleep. To create a notification, you must use two
 classes: {@link android.app.Notification} and {@link android.app.NotificationManager}.</p>
 
-<p>Use an instance of the {@link android.app.Notification} class to define the properties of your 
-status bar notification, such as the status bar icon, the expanded message, and extra settings such 
-as a sound to play. The {@link android.app.NotificationManager} is an Android system service that 
-executes and manages all Notifications. You do not instantiate the NotificationManager. In order
-to give it your Notification, you must retrieve a reference to the NotificationManager with
-{@link android.app.Activity#getSystemService(String) getSystemService()} and 
-then, when you want to notify the user, pass it your Notification object with 
+<p>Use an instance of the {@link android.app.Notification} class to define the properties of your
+status bar notification, such as the status bar icon, the notification message, and extra settings
+such as a sound to play. The {@link android.app.NotificationManager} is an Android system service
+that executes and manages all status bar notifications. You do not instantiate the
+{@link android.app.NotificationManager} directly. In order
+to give it your {@link android.app.Notification}, you must retrieve a reference to the
+{@link android.app.NotificationManager} with
+{@link android.app.Activity#getSystemService(String) getSystemService()} and
+then, when you want to notify the user, pass it your {@link android.app.Notification} with
 {@link android.app.NotificationManager#notify(int,Notification) notify()}. </p>
 
 <p>To create a status bar notification:</p>
 <ol>
-  <li>Get a reference to the NotificationManager:
+  <li>Get a reference to the {@link android.app.NotificationManager}:
 <pre>
 String ns = Context.NOTIFICATION_SERVICE;
 NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
 </pre>
   </li>
-  <li>Instantiate the Notification:
+  <!-- use Notification.Builder in 3.0 -->
+  <li>Instantiate the {@link android.app.Notification}:
 <pre>
 int icon = R.drawable.notification_icon;
 CharSequence tickerText = "Hello";
@@ -95,7 +101,7 @@
 Notification notification = new Notification(icon, tickerText, when);
 </pre>
   </li>
-  <li>Define the Notification's expanded message and Intent:
+  <li>Define the notification's message and {@link android.app.PendingIntent}:
 <pre>
 Context context = getApplicationContext();
 CharSequence contentTitle = "My notification";
@@ -106,7 +112,7 @@
 notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
 </pre>
   </li>
-  <li>Pass the Notification to the NotificationManager:
+  <li>Pass the {@link android.app.Notification} to the {@link android.app.NotificationManager}:
 <pre>
 private static final int HELLO_ID = 1;
 
@@ -121,38 +127,41 @@
 
 <p>The {@link android.app.NotificationManager} is a system service that manages all
 notifications. You must retrieve a reference to it with the
-{@link android.app.Activity#getSystemService(String) getSystemService()} method. 
+{@link android.app.Activity#getSystemService(String) getSystemService()} method.
 For example:</p>
 <pre>
 String ns = Context.NOTIFICATION_SERVICE;
 NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
 </pre>
 
-<p>When you want to send your status bar notification, pass the Notification object
-to the NotificationManager with {@link android.app.NotificationManager#notify(int,Notification)}. 
-The first parameter is the unique ID for the Notification and the second is the Notification object.
-The ID uniquely identifies the Notification from within your
-application. This is necessary if you need to update the Notification or (if
-your application manages different kinds of Notifications) select the appropriate action
-when the user returns to your application via the Intent defined in the Notification.</p>
+<p>When you want to deliver your status bar notification, pass the {@link android.app.Notification}
+to the {@link android.app.NotificationManager} with {@link
+android.app.NotificationManager#notify(int,Notification)}.
+The first parameter is the unique ID for the notification and the second is the {@link
+android.app.Notification} object.
+The ID uniquely identifies the notification from within your
+application. The ID is necessary if you need to update the notification or (if
+your application manages different kinds of notifications) select the appropriate action
+when the user returns to your application via the intent defined in the notification.</p>
 
-<p>To clear the status bar notification when the user selects it from the Notifications
-window, add the "FLAG_AUTO_CANCEL" flag to your Notification object. You can also clear it
-manually with {@link android.app.NotificationManager#cancel(int)}, passing it the notification ID,
-or clear all your Notifications with {@link android.app.NotificationManager#cancelAll()}.</p>
+<p>To clear the status bar notification when the user selects it from the notifications
+window, add the "FLAG_AUTO_CANCEL" flag to your {@link android.app.Notification}. You can
+also clear it manually with {@link android.app.NotificationManager#cancel(int)}, passing it the
+notification ID, or clear all your notifications with {@link
+android.app.NotificationManager#cancelAll()}.</p>
 
 
 <h2 id="CreateANotification">Creating a Notification</h2>
 
 <p>A {@link android.app.Notification} object defines the details of the notification
-message that is displayed in the status bar and "Notifications" window, and any other
+message that is displayed in the status bar and notifications window, and any other
 alert settings, such as sounds and blinking lights.</p>
 
 <p>A status bar notification <em>requires</em> all of the following:</p>
 <ul>
   <li>An icon for the status bar</li>
-  <li>A title and expanded message for the expanded view (unless you define a 
-    <a href="#CustomExpandedView">custom expanded view</a>)</li>
+  <li>A title and message, unless you define a
+    <a href="#CustomExpandedView">custom notification layout</a></li>
   <li>A {@link android.app.PendingIntent}, to be fired when the notification is selected</li>
 </ul>
 <p>Optional settings for the status bar notification include:</p>
@@ -163,18 +172,18 @@
   <li>A flashing LED setting</li>
 </ul>
 
-<p>The starter-kit for a new Notification includes the 
-{@link android.app.Notification#Notification(int,CharSequence,long)} constructor and the 
-{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)} 
-method. These define all the required settings for a Notification. 
-The following snippet demonstrates a basic Notification setup:</p>
+<p>The starter-kit for a new notification includes the
+{@link android.app.Notification#Notification(int,CharSequence,long)} constructor and the
+{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)}
+method. These define all the required settings for a notification.
+The following snippet demonstrates a basic notification setup:</p>
 <pre>
 int icon = R.drawable.notification_icon;        // icon from resources
 CharSequence tickerText = "Hello";              // ticker-text
 long when = System.currentTimeMillis();         // notification time
 Context context = getApplicationContext();      // application Context
-CharSequence contentTitle = "My notification";  // expanded message title
-CharSequence contentText = "Hello World!";      // expanded message text
+CharSequence contentTitle = "My notification";  // message title
+CharSequence contentText = "Hello World!";      // message text
 
 Intent notificationIntent = new Intent(this, MyClass.class);
 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
@@ -187,32 +196,33 @@
 
 <h3 id="Updating">Updating the notification</h3>
 
-<p>You can update the information in your status bar notification as events 
-continue to occur in your application. For example, when a new SMS text message arrives 
-before previous messages have been read, the Messaging application updates the existing 
+<p>You can update the information in your status bar notification as events
+continue to occur in your application. For example, when a new SMS text message arrives
+before previous messages have been read, the Messaging application updates the existing
 notification to display the total number of new messages received.
-This practice of updating an existing Notification is much better than adding new Notifications 
-to the NotificationManager because it avoids clutter in the Notifications window.</p>
+This practice of updating an existing notification is much better than adding new
+notifications, because it avoids clutter in the notifications window.</p>
 
 <p>Because each notification is uniquely identified
-by the NotificationManager with an integer ID, you can revise the notification by calling
-{@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)
-setLatestEventInfo()} with new values, change some field values of the Notification, and then call
+by the {@link android.app.NotificationManager} with an integer ID, you can revise the notification
+by calling {@link
+android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)
+setLatestEventInfo()} with new values, change some field values of the notification, and then call
 {@link android.app.NotificationManager#notify(int,Notification) notify()} again.</p>
 
 <p>You can revise each property with the object member fields
-(except for the Context and the expanded message title and text). You should always 
-revise the text message when you update the notification by calling
+(except for the {@link android.content.Context} and the notification title and text). You
+should always revise the text message when you update the notification by calling
 {@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)
-setLatestEventInfo()} with new values for <var>contentTitle</var> and <var>contentText</var>. 
-Then call {@link android.app.NotificationManager#notify(int,Notification) notify()} to update the 
-notification. (Of course, if you've created a <a href="#CustomExpandedView">custom expanded 
-view</a>, then updating these title and text values has no effect.)</p>
+setLatestEventInfo()} with new values for <var>contentTitle</var> and <var>contentText</var>.
+Then call {@link android.app.NotificationManager#notify(int,Notification) notify()} to update the
+notification. (Of course, if you've created a <a href="#CustomExpandedView">custom notification
+layout</a>, then updating these title and text values has no effect.)</p>
 
 
 <h3 id="Sound">Adding a sound</h3>
 
-<p>You can alert the user with the default notification sound 
+<p>You can alert the user with the default notification sound
 (which is defined by the user) or with a sound specified by your application.</p>
 
 <p>To use the user's default sound, add "DEFAULT_SOUND" to the <var>defaults</var> field:</p>
@@ -227,31 +237,35 @@
 notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
 </pre>
 
-<p>In the next example, the audio file is chosen from the internal 
+<p>In the next example, the audio file is chosen from the internal
 {@link android.provider.MediaStore.Audio.Media MediaStore}'s {@link android.content.ContentProvider}:</p>
 <pre>
 notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
 </pre>
 
-<p>In this case, the exact ID of the media file ("6") is known and appended to the content 
+<p>In this case, the exact ID of the media file ("6") is known and appended to the content
 {@link android.net.Uri}. If you don't know the exact ID, you must query all the
-media available in the MediaStore with a {@link android.content.ContentResolver}. 
+media available in the {@link android.provider.MediaStore} with a {@link
+android.content.ContentResolver}.
 See the <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
 documentation for more information on using a ContentResolver.</p>
 
 <p>If you want the sound to continuously repeat until the user responds to the notification
-or the notification is cancelled, add "FLAG_INSISTENT" to the <var>flags</var> field.</p>
+or the notification is cancelled, add {@link android.app.Notification#FLAG_INSISTENT} to the
+<var>flags</var> field.</p>
 
-<p class="note"><strong>Note:</strong> If the <var>defaults</var> field includes 
-"DEFAULT_SOUND", then the default sound overrides any sound defined by the <var>sound</var> field.</p>
+<p class="note"><strong>Note:</strong> If the <var>defaults</var> field includes
+{@link android.app.Notification#DEFAULT_SOUND}, then the default sound overrides any sound defined
+by the <var>sound</var> field.</p>
 
 
 <h3 id="Vibration">Adding vibration</h3>
 
-<p>You can alert the user with the the default 
+<p>You can alert the user with the the default
 vibration pattern or with a vibration pattern defined by your application.</p>
 
-<p>To use the default pattern, add "DEFAULT_VIBRATE" to the <var>defaults</var> field:</p>
+<p>To use the default pattern, add {@link android.app.Notification#DEFAULT_VIBRATE} to the
+<var>defaults</var> field:</p>
 <pre>
 notification.defaults |= Notification.DEFAULT_VIBRATE;
 </pre>
@@ -264,30 +278,32 @@
 </pre>
 
 <p>The long array defines the alternating pattern for the length of vibration off and on
-(in milliseconds). The first value is how long to wait (off) before beginning, the second 
-value is the length of the first vibration, the third is the next length off, and so on. 
+(in milliseconds). The first value is how long to wait (off) before beginning, the second
+value is the length of the first vibration, the third is the next length off, and so on.
 The pattern can be as long as you like, but it can't be set to repeat.
 </p>
 
-<p class="note"><strong>Note:</strong> If the <var>defaults</var> field includes 
-"DEFAULT_VIBRATE", then the default vibration overrides any vibration defined by the 
+<p class="note"><strong>Note:</strong> If the <var>defaults</var> field includes
+{@link android.app.Notification#DEFAULT_VIBRATE}, then the default vibration overrides any vibration
+defined by the
 <var>vibrate</var> field.</p>
 
 
 <h3 id="Lights">Adding flashing lights</h3>
 
-<p>To alert the user by flashing LED lights, you can implement the default 
+<p>To alert the user by flashing LED lights, you can implement the default
 light pattern (if available), or define your own color and pattern for the lights.</p>
 
-<p>To use the default light setting, add "DEFAULT_LIGHTS" to the <var>defaults</var> field:</p>
+<p>To use the default light setting, add {@link android.app.Notification#DEFAULT_LIGHTS} to the
+<var>defaults</var> field:</p>
 <pre>
 notification.defaults |= Notification.DEFAULT_LIGHTS;
 </pre>
 
 <p>To define your own color and pattern, define a value for the <var>ledARGB</var> field
-(for the color), the <var>ledOffMS</var> field (length of time, in milliseconds, to 
-keep the light off), the <var>ledOnMS</var> (length of time, in milliseconds, to keep the light on), 
-and also add "FLAG_SHOW_LIGHTS" to the <var>flags</var> field:</p>
+(for the color), the <var>ledOffMS</var> field (length of time, in milliseconds, to
+keep the light off), the <var>ledOnMS</var> (length of time, in milliseconds, to keep the light on),
+and also add {@link android.app.Notification#FLAG_SHOW_LIGHTS} to the <var>flags</var> field:</p>
 <pre>
 notification.ledARGB = 0xff00ff00;
 notification.ledOnMS = 300;
@@ -295,114 +311,161 @@
 notification.flags |= Notification.FLAG_SHOW_LIGHTS;
 </pre>
 
-<p>In this example, the green light repeatedly flashes on for 300 milliseconds and 
-turns off for one second. Not every color in the spectrum is supported by the 
-device LEDs, and not every device supports the same colors, so the hardware 
+<p>In this example, the green light repeatedly flashes on for 300 milliseconds and
+turns off for one second. Not every color in the spectrum is supported by the
+device LEDs, and not every device supports the same colors, so the hardware
 estimates to the best of its ability. Green is the most common notification color.</p>
 
 
 <h3 id="More">More features</h3>
 
 <p>You can add several more features to your notifications
-using Notification fields and flags. Some useful features include the following:</p>
+using {@link android.app.Notification} fields and flags. Some useful features include the
+following:</p>
 
 <dl>
-  <dt>"FLAG_AUTO_CANCEL" flag</dt>
+  <dt>{@link android.app.Notification#FLAG_AUTO_CANCEL} flag</dt>
   <dd>Add this to the <var>flags</var> field to automatically cancel the notification
-  after it is selected from the Notifications window.</dd>
-  <dt>"FLAG_INSISTENT" flag</dt>
+  after it is selected from the notifications window.</dd>
+  <dt>{@link android.app.Notification#FLAG_INSISTENT} flag</dt>
   <dd>Add this to the <var>flags</var> field to repeat the audio until the
   user responds.</dd>
-  <dt>"FLAG_ONGOING_EVENT" flag</dt>
+  <dt>{@link android.app.Notification#FLAG_ONGOING_EVENT} flag</dt>
   <dd>Add this to the <var>flags</var> field to group the notification under the "Ongoing"
-  title in the Notifications window. This indicates that the application is on-going &mdash;
-  its processes is still running in the background, even when the application is not 
+  title in the notifications window. This indicates that the application is on-going &mdash;
+  its processes are still running in the background, even when the application is not
   visible (such as with music or a phone call).</dd>
-  <dt>"FLAG_NO_CLEAR" flag</dt>
-  <dd>Add this to the <var>flags</var> field to indicate that the notification should 
-  <em>not</em> be cleared by the "Clear notifications" button. This is particularly useful if 
+  <dt>{@link android.app.Notification#FLAG_NO_CLEAR} flag</dt>
+  <dd>Add this to the <var>flags</var> field to indicate that the notification should
+  <em>not</em> be cleared by the "Clear notifications" button. This is particularly useful if
   your notification is on-going.</dd>
-  <dt><var>number</var> field</dt>
+  <dt>{@link android.app.Notification#number} field</dt>
   <dd>This value indicates the current number of events represented by the notification.
   The appropriate number is overlaid on top of the status bar icon.
   If you intend to use this field, then you must start with "1" when the Notification is first
   created. (If you change the value from zero to anything greater during an update, the number
   is not shown.)</dd>
-  <dt><var>iconLevel</var> field</dt>
-  <dd>This value indicates the current level of a 
+  <dt>{@link android.app.Notification#iconLevel} field</dt>
+  <dd>This value indicates the current level of a
   {@link android.graphics.drawable.LevelListDrawable} that is used for the notification icon.
-  You can animate the icon in the status bar by changing this value to correlate with the 
+  You can animate the icon in the status bar by changing this value to correlate with the
   drawable's defined in a LevelListDrawable. See the {@link android.graphics.drawable.LevelListDrawable}
   reference for more information.</dd>
 </dl>
 
-<p>See the {@link android.app.Notification} class reference for more information about additional 
+<p>See the {@link android.app.Notification} class reference for more information about additional
 features that you can customize for your application.</p>
 
 
-<h2 id="CustomExpandedView">Creating a Custom Expanded View</h2>
+<h2 id="CustomExpandedView">Creating a Custom Notification Layout</h2>
 
-<img src="{@docRoot}images/custom_message.png" alt="" style="float:right;" />
+<div class="figure" style="width:200px;margin-top:0">
+<img src="{@docRoot}images/custom_message.png" alt="" />
+<p class="img-caption"><strong>Figure 3.</strong> Notification with a custom layout.</p>
+</div>
 
-<p>By default, the expanded view used in the "Notifications" window includes a basic title and text 
-message. These are defined by the <var>contentTitle</var> and <var>contentText</var>
+<p>By default, the notification that appears in the notifications window includes a title
+and the message text.
+These are defined by the <var>contentTitle</var> and <var>contentText</var>
 parameters of the {@link android.app.Notification#setLatestEventInfo(Context,CharSequence,CharSequence,PendingIntent)
-setLatestEventInfo()} method. However, you can also define a custom layout for the expanded view using 
-{@link android.widget.RemoteViews}. The screenshot to the right shows an example of a
-custom expanded view that uses an ImageView and TextView in a LinearLayout.</p>
+setLatestEventInfo()} method. However, you can also define a custom layout for the
+notification using
+{@link android.widget.RemoteViews}. Figure 3 shows an example of a
+custom notification layout. It looks similar to the default notification, but is
+actually created with a custom XML layout.</p>
 
-<p>To define your own layout for the expanded message,
-instantiate a {@link android.widget.RemoteViews} object and
-pass it to the <var>contentView</var> field of your Notification. Pass the
-{@link android.app.PendingIntent} to the <var>contentIntent</var> field.</p>
+<p>To define your own layout for the notification,
+instantiate a {@link android.widget.RemoteViews} object that inflates a custom layout file, then
+pass the {@link android.widget.RemoteViews} to the <var>contentView</var> field of your
+Notification.</p>
 
-<p>Creating a custom expanded view is best understood with an example:</p>
+<p>Creating a custom notification layout is best understood with an example:</p>
 
 <ol>
-  <li>Create the XML layout for the expanded view.
-    For example, create a layout file called <code>custom_notification_layout.xml</code> and 
-    build it like so:
+  <li>Create the XML layout for the notification.
+    For example, the following layout is called <code>custom_notification.xml</code>:
 <pre>
-&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-              android:orientation="horizontal"
-              android:layout_width="fill_parent"
-              android:layout_height="fill_parent"
-              android:padding="3dp"
-              >
+&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/layout"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:padding="10dp" >
     &lt;ImageView android:id="@+id/image"
-              android:layout_width="wrap_content"
-              android:layout_height="fill_parent"
-              android:layout_marginRight="10dp"
-              />
+        android:layout_width="wrap_content"
+        android:layout_height="fill_parent"
+        android:layout_alignParentLeft="true"
+        android:layout_marginRight="10dp" />
+    &lt;TextView android:id="@+id/title"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_toRightOf="@id/image"
+        style="@style/NotificationTitle" />
     &lt;TextView android:id="@+id/text"
-              android:layout_width="wrap_content"
-              android:layout_height="fill_parent"
-              android:textColor="#000"
-              />
-&lt;/LinearLayout>
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_toRightOf="@id/image"
+        android:layout_below="@id/title"
+        style="@style/NotificationText" />
+&lt;/RelativeLayout>
 </pre>
 
-    <p>This layout is used for the expanded view,
-    but the content of the ImageView and TextView still needs to be defined by the application.
-    RemoteViews offers some convenient methods that allow you to define this content...</p>
+    <p>Notice that the two {@link android.widget.TextView} elements include the {@code style}
+attribute. It's important that you use style resources for the text in your custom
+notifications, because the background color of the notification can vary across different
+devices and platform versions. Beginning with Android 2.3 (API level 9), the system defines a
+style for the text it uses for the default notification layouts. Thus, you should apply
+that style when running on Android 2.3 or higher to ensure that your text is visible against
+the background.</p>
+
+    <p>For example, to use the standard text colors on versions of Android lower than 2.3, you
+should use the following styles for {@code res/values/styles.xml}:</p>
+<pre>
+&lt;?xml version="1.0" encoding="utf-8"?>
+&lt;resources>
+    &lt;style name="NotificationText">
+      &lt;item name="android:textColor">?android:attr/textColorPrimary&lt;/item>
+    &lt;/style>
+    &lt;style name="NotificationTitle">
+      &lt;item name="android:textColor">?android:attr/textColorPrimary&lt;/item>
+      &lt;item name="android:textStyle">bold&lt;/item>
+    &lt;/style>
+    &lt;!-- If you want a slightly different color for some text,
+         consider using ?android:attr/textColorSecondary -->
+&lt;/resources>
+</pre>
+    <p>Then, to apply the system's default colors for notifications on Android
+2.3 and higher, use the following styles for {@code res/values-v9/styles.xml}:</p>
+<pre>
+&lt;?xml version="1.0" encoding="utf-8"?>
+&lt;resources>
+    &lt;style name="NotificationText" parent="android:TextAppearance.StatusBar.EventContent" />
+    &lt;style name="NotificationTitle" parent="android:TextAppearance.StatusBar.EventContent.Title" />
+&lt;/resources>
+</pre>
+    <p>Now, when running on Android 2.3 (API level 9) or higher, the text in your custom view will
+use the same colors that the system does for default notifications. This is important because later
+versions of Android actually change the background color of the notifications to be dark. Inheriting
+the system's styles ensures that your text will be light in such cases, but also if the background
+is some other unexpected color, your text will also change as appropriate.</p>
   </li>
 
-  <li>In the application code, use the RemoveViews 
+  <li>Now, in the application code, use the RemoveViews
     methods to define the image and text. Then pass the RemoteViews object to the <var>contentView</var>
     field of the Notification, as shown in this example:
 <pre>
 RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
 contentView.setImageViewResource(R.id.image, R.drawable.notification_image);
-contentView.setTextViewText(R.id.text, "Hello, this message is in a custom expanded view");
+contentView.setTextViewText(R.id.title, "Custom notification");
+contentView.setTextViewText(R.id.text, "This is a custom layout");
 notification.contentView = contentView;
 </pre>
 
-    <p>As shown here, pass the application's package name and the layout 
+    <p>As shown here, pass the application's package name and the layout
     resource ID to the RemoteViews constructor. Then, define the content for the ImageView and TextView,
     using the {@link android.widget.RemoteViews#setImageViewResource(int, int) setImageViewResource()}
     and {@link android.widget.RemoteViews#setTextViewText(int, CharSequence) setTextViewText()}.
     In each case, pass the reference ID of the appropriate View object that you want to set, along with
-    the value for that View. Finally, the RemoteViews object is passed to the Notification in the 
+    the value for that View. Finally, the RemoteViews object is passed to the Notification in the
     <var>contentView</var> field.</p>
   </li>
 
@@ -416,23 +479,23 @@
 notification.contentIntent = contentIntent;
 </pre>
   </li>
-  
+
   <li>The notification can now be sent as usual:
     <pre>mNotificationManager.notify(CUSTOM_VIEW_ID, notification);</pre>
   </li>
 </ol>
 
 
-<p>The RemoteViews class also includes methods that you can use to easily add a 
-{@link android.widget.Chronometer} or {@link android.widget.ProgressBar} 
-in your notification's expanded view. For more information about creating custom layouts with 
-RemoteViews, refer to the {@link android.widget.RemoteViews} class reference.</p>
+<p>The {@link android.widget.RemoteViews} class also includes methods that you can use to easily add
+a {@link android.widget.Chronometer} or {@link android.widget.ProgressBar}
+in your notification's layout. For more information about creating custom layouts for your
+notification, refer to the {@link android.widget.RemoteViews} class reference.</p>
 
-<p class="warning"><strong>Note:</strong>
-When creating a custom expanded view, you must take special care to ensure that your 
-custom layout functions properly in different device orientations and resolutions. While this 
+<p class="caution"><strong>Caution:</strong>
+When creating a custom notification layout, you must take special care to ensure that your
+custom layout functions properly in different device orientations and resolutions. While this
 advice applies to all View layouts created on Android, it is especially important in this case
-because your layout real estate is very restricted. So don't make your custom layout too 
+because your layout real estate is very restricted. So don't make your custom layout too
 complex and be sure to test it in various configurations.</p>
 
 
diff --git a/docs/html/guide/topics/usb/adk.jd b/docs/html/guide/topics/usb/adk.jd
index 463ec9c..120576b 100644
--- a/docs/html/guide/topics/usb/adk.jd
+++ b/docs/html/guide/topics/usb/adk.jd
@@ -77,6 +77,10 @@
         DIY Drones</a></li>
 
       <li><a href=
+        "http://mbed.org/order/">
+        mbed</a></li>
+
+      <li><a href=
         "http://www.microchip.com/android">
         Microchip</a></li>
 
@@ -130,6 +134,11 @@
     Drones</a> provides an Arduino-compatible board geared towards RC (radio controlled) and UAV
     (unmanned aerial vehicle) enthusiasts.</li>
 
+    <li><a href="http://mbed.org/order/">mbed</a> provides a microcontroller and a library
+    to develop accessories that support the Android accessory protocol. For more information, see
+    <a href="http://mbed.org/cookbook/mbed-with-Android-ADK">mbed with the Android ADK</a>.
+    </li>
+
     <li><a href="http://www.microchip.com/android">Microchip</a> provides a PIC based USB
     microcontroller board.</li>
 
diff --git a/docs/html/images/custom_message.png b/docs/html/images/custom_message.png
index ea7c716..00b7632 100755
--- a/docs/html/images/custom_message.png
+++ b/docs/html/images/custom_message.png
Binary files differ
diff --git a/docs/html/resources/articles/speech-input.jd b/docs/html/resources/articles/speech-input.jd
index 736087ec..0867ff2 100644
--- a/docs/html/resources/articles/speech-input.jd
+++ b/docs/html/resources/articles/speech-input.jd
@@ -87,8 +87,8 @@
 regularly. You can use the
 {@link android.speech.RecognizerIntent#ACTION_GET_LANGUAGE_DETAILS}
 broadcast intent to query for the list of supported languages.
-The web search model is available in all three languages, while free-form has
-primarily been optimized for English. As we work hard to support more models in
+The web search model is available for all languages, while the free-form model
+may not be optimized for all languages. As we work hard to support more models in
 more languages, and to improve the accuracy of the speech recognition technology
 we use in our products, Android developers who integrate speech capabilities
 directly into their applications can reap the benefits as well. </p>
diff --git a/docs/html/resources/resources-data.js b/docs/html/resources/resources-data.js
index 720e143..f799b0c 100644
--- a/docs/html/resources/resources-data.js
+++ b/docs/html/resources/resources-data.js
@@ -31,7 +31,8 @@
   },
   misc: {
     'external': 'External',
-    'new': 'New'
+    'new': 'New',
+    'updated': 'Updated'
   }
 };
 
@@ -377,7 +378,7 @@
 ///////////////////
  
   {
-    tags: ['sample', 'new'],
+    tags: ['sample'],
     path: 'samples/AccelerometerPlay/index.html',
     title: {
       en: 'Accelerometer Play'
@@ -387,7 +388,7 @@
     }
   },
   {
-    tags: ['sample', 'new', 'accessibility'],
+    tags: ['sample', 'accessibility'],
     path: 'samples/AccessibilityService/index.html',
     title: {
       en: 'Accessibility Service'
@@ -407,7 +408,7 @@
     }
   },
   {
-    tags: ['sample', 'layout', 'ui', 'fragment', 'loader', 'new'],
+    tags: ['sample', 'layout', 'ui', 'fragment', 'loader'],
     path: 'samples/Support4Demos/index.html',
     title: {
       en: 'API 4+ Support Demos'
@@ -417,7 +418,7 @@
     }
   },
   {
-    tags: ['sample', 'layout', 'ui', 'new'],
+    tags: ['sample', 'layout', 'ui'],
     path: 'samples/Support13Demos/index.html',
     title: {
       en: 'API 13+ Support Demos'
@@ -487,13 +488,13 @@
     }
   },
   {
-    tags: ['sample', 'new', 'newfeature', 'ui'],
+    tags: ['sample', 'updated', 'newfeature', 'ui'],
     path: 'samples/HoneycombGallery/index.html',
     title: {
       en: 'Honeycomb Gallery'
     },
     description: {
-      en: 'An image gallery application using APIs that are new in Android 3.0 (a.k.a. Honeycomb).'
+      en: 'An image gallery application that demonstrates a variety of new APIs in Android 3.0 (Honeycomb). In addition to providing a tablet-optimized design, it also supports handsets running Android 4.0 (Ice Cream Sandwich) and beyond, so is a good example of how to reuse Fragments to support different screen sizes.'
     }
   },
   {
@@ -547,7 +548,7 @@
     }
   },
   {
-    tags: ['sample', 'new', 'media' ],
+    tags: ['sample', 'media' ],
     path: 'samples/RandomMusicPlayer/index.html',
     title: {
       en: 'Random Music Player'
@@ -557,7 +558,7 @@
     }
   },
   {
-    tags: ['sample', 'new', 'newfeature', 'performance', 'gamedev', 'gl'],
+    tags: ['sample', 'newfeature', 'performance', 'gamedev', 'gl'],
     path: 'samples/RenderScript/index.html',
     title: {
       en: 'RenderScript'
@@ -637,7 +638,7 @@
     }
   },
   {
-    tags: ['sample', 'new', 'newfeature', 'widgets'],
+    tags: ['sample', 'newfeature', 'widgets'],
     path: 'samples/StackWidget/index.html',
     title: {
       en: 'StackView Widget'
@@ -667,7 +668,7 @@
     }
   },
   {
-    tags: ['sample', 'new', 'newfeature'],
+    tags: ['sample', 'newfeature'],
     path: 'samples/USB/index.html',
     title: {
       en: 'USB'
@@ -683,7 +684,7 @@
       en: 'Voicemail Provider Demo'
     },
     description: {
-      en: 'A sample application to demonstrate how to use voicemail content provider APIs.'
+      en: 'A sample application to demonstrate how to use voicemail content provider APIs in Android 4.0.'
     }
   },
   {
@@ -707,7 +708,7 @@
     }
   },
   {
-    tags: ['sample', 'widgets', 'newfeature', 'new'],
+    tags: ['sample', 'widgets', 'newfeature'],
     path: 'samples/WeatherListWidget/index.html',
     title: {
       en: 'Weather List Widget'
@@ -733,7 +734,7 @@
       en: 'Text To Speech Engine'
     },
     description: {
-      en: 'An example Text To Speech engine written using the android text to speech engine API.'
+      en: 'An example Text To Speech engine written using the Android text to speech engine API in Android 4.0.'
     }
   },
 
diff --git a/docs/html/sdk/index.jd b/docs/html/sdk/index.jd
index 5cf37c1..105c868 100644
--- a/docs/html/sdk/index.jd
+++ b/docs/html/sdk/index.jd
@@ -1,21 +1,21 @@
 page.title=Android SDK
 sdk.redirect=0
 
-sdk.win_installer=installer_r12-windows.exe
-sdk.win_installer_bytes=36531492
-sdk.win_installer_checksum=367f0ed4ecd70aefc290d1f7dcb578ab
+sdk.win_installer=installer_r13-windows.exe
+sdk.win_installer_bytes=36533357
+sdk.win_installer_checksum=cd3a76fe2b8ed62b2d03cf1851692e2d
 
-sdk.win_download=android-sdk_r12-windows.zip
-sdk.win_bytes=36486190
-sdk.win_checksum=8d6c104a34cd2577c5506c55d981aebf
+sdk.win_download=android-sdk_r13-windows.zip
+sdk.win_bytes=36487911
+sdk.win_checksum=de8a039891e5e65b7742f188f07b992d
 
-sdk.mac_download=android-sdk_r12-mac_x86.zip
-sdk.mac_bytes=30231118
-sdk.mac_checksum=341544e4572b4b1afab123ab817086e7
+sdk.mac_download=android-sdk_r13-mac_x86.zip
+sdk.mac_bytes=30233944
+sdk.mac_checksum=f4002a0344b48856c09dec796acecd4d
 
-sdk.linux_download=android-sdk_r12-linux_x86.tgz
-sdk.linux_bytes=30034243
-sdk.linux_checksum=f8485275a8dee3d1929936ed538ee99a
+sdk.linux_download=android-sdk_r13-linux_x86.tgz
+sdk.linux_bytes=30034328
+sdk.linux_checksum=d80d7530a46c665644ae76084a9a0dc4
 
 @jd:body
 
diff --git a/docs/html/sdk/sdk_toc.cs b/docs/html/sdk/sdk_toc.cs
index a00ca12..8a57312 100644
--- a/docs/html/sdk/sdk_toc.cs
+++ b/docs/html/sdk/sdk_toc.cs
@@ -77,7 +77,7 @@
     <ul>
       <li class="toggle-list">
         <div><a href="<?cs var:toroot ?>sdk/android-3.2.html">
-        <span class="en">Android 3.2 Platform</span></a> <span class="new">new!</span></div>
+        <span class="en">Android 3.2 Platform</span></a></div>
         <ul>
           <!-- <li><a href="<?cs var:toroot ?>sdk/android-3.2-highlights.html">Platform Highlights</a></li> -->
           <li><a href="<?cs var:toroot ?>sdk/api_diff/13/changes.html">API Differences Report &raquo;</a></li>
@@ -142,11 +142,11 @@
       </li>
     </ul>
     <ul>
-      <li><a href="<?cs var:toroot ?>sdk/tools-notes.html">SDK Tools, r12</a> <span
+      <li><a href="<?cs var:toroot ?>sdk/tools-notes.html">SDK Tools, r13</a> <span
 class="new">new!</span></li>
       <li><a href="<?cs var:toroot ?>sdk/win-usb.html">Google USB Driver, r4</a></li>
       <li><a href="<?cs var:toroot ?>sdk/compatibility-library.html">Compatibility Package,
-r3</a> <span class="new">new!</span></li>
+r3</a></li>
     </ul>
   </li>
   <li>
@@ -169,7 +169,7 @@
       <span style="display:none" class="ja"></span>
       <span style="display:none" class="zh-CN"></span>
       <span style="display:none" class="zh-TW"></span></a>
-      <span class="new">new!</span></li>
+      </li>
     </ul>
   </li>
   <li>
@@ -183,8 +183,7 @@
       <span style="display:none" class="zh-TW"></span>
     </h2>
     <ul>
-      <li><a href="<?cs var:toroot ?>sdk/ndk/index.html">Android NDK, r6b</a> 
-        <span class="new">new!</span>
+      <li><a href="<?cs var:toroot ?>sdk/ndk/index.html">Android NDK, r6b</a>
         </li>
       <li><a href="<?cs var:toroot ?>sdk/ndk/overview.html">What is the NDK?</a></li>
     </ul>
diff --git a/docs/html/sdk/tools-notes.jd b/docs/html/sdk/tools-notes.jd
index 8c4d037..2179cec 100644
--- a/docs/html/sdk/tools-notes.jd
+++ b/docs/html/sdk/tools-notes.jd
@@ -4,7 +4,7 @@
 <p>SDK Tools is a downloadable component for the Android SDK. It includes the
 complete set of development and debugging tools for the Android SDK. </p>
 
-<p>If you are new to the Android SDK, the <a 
+<p>If you are new to the Android SDK, the <a
 href="{@docRoot}sdk/index.html">SDK starter package</a> installs the
 latest revision of the SDK Tools in the <code>&lt;sdk&gt;/tools</code> directory.</p>
 
@@ -66,6 +66,35 @@
 <div class="toggleable opened">
   <a href="#" onclick="return toggleDiv(this)">
         <img src="{@docRoot}assets/images/triangle-opened.png" class="toggle-img" height="9px" width="9px" />
+SDK Tools, Revision 13</a> <em>(September 2011)</em>
+  <div class="toggleme">
+  <dl>
+<dt>Dependencies:</dt>
+<dd>
+<p>If you are developing in Eclipse with ADT, note that the SDK Tools r13 is designed for use with
+ADT 12.0.0 and later. If you haven't already, we highly recommend updating your <a
+href="{@docRoot}sdk/eclipse-adt.html">ADT Plugin</a> to 12.0.0.</p>
+
+<p>If you are developing outside Eclipse, you must have <a href="http://ant.apache.org/">Apache
+Ant</a> 1.8 or later.</p>
+
+<dt>General notes:</dt>
+<dd>
+  <ul>
+    <li>Fix compilation issue in Ant (<code>dex</code> step) when paths have spaces.</li>
+    <li>Fix issue in emulator installation when paths have spaces.</li>
+    <li>Fix issue when AVD paths have spaces.</li>
+    <li>Fix rendering issue when using emulator scaling (<a href="http://code.google.com/p/android/issues/detail?id=18299">see more</a>).</li>
+  </ul>
+</dd>
+</dl>
+</div>
+</div>
+
+
+<div class="toggleable closed">
+  <a href="#" onclick="return toggleDiv(this)">
+        <img src="{@docRoot}assets/images/triangle-closed.png" class="toggle-img" height="9px" width="9px" />
 SDK Tools, Revision 12</a> <em>(July 2011)</em>
   <div class="toggleme">
   <dl>
@@ -396,7 +425,7 @@
 <dt>General notes:</dt>
 <dd>
 <ul>
-<li>Launcher script now forces GDK_NATIVE_WINDOW=true (linux only), to fix a 
+<li>Launcher script now forces GDK_NATIVE_WINDOW=true (linux only), to fix a
 compatibility issue between GTK and SWT.</li>
 </ul>
 </dd>
@@ -405,7 +434,7 @@
 <dd>
 <ul>
 <li>AVD Launch dialog now shows scale value.</li>
-<li>Fixes potential NPE in SDK Manager on AVD launch, for older AVD with no 
+<li>Fixes potential NPE in SDK Manager on AVD launch, for older AVD with no
 skin name specified.</li>
 <li>Fixes XML validation issue in on older Java versions.</li>
 <li>No longer forces the use of Java 1.5 on Mac OS X.</li>
@@ -470,7 +499,7 @@
 <dd>
 <ul>
 <li>Provides a new UI that lets you set options for controlling
-the emulator skin, screen size/density, and scale factor used when launching 
+the emulator skin, screen size/density, and scale factor used when launching
 an AVD.</li>
 <li>Provides improved AVD creation UI, which lets you customize the hardware
 properties of your AVDs.</li>
@@ -481,11 +510,11 @@
 
 <dt>Layoutopt, a new tool for optimizing layouts:</dt>
 
-<dd><p>The SDK Tools r3 package includes <code>layoutopt</code>, a new command-line 
-tool that helps you optimize your layout hierarchies. When run against your 
-layout files, the tool analyzes their hierarchies and notifies you of 
-inefficiencies and other potential issues. The tool also provides simple 
-solutions for the issues it finds. For usage, see <a 
+<dd><p>The SDK Tools r3 package includes <code>layoutopt</code>, a new command-line
+tool that helps you optimize your layout hierarchies. When run against your
+layout files, the tool analyzes their hierarchies and notifies you of
+inefficiencies and other potential issues. The tool also provides simple
+solutions for the issues it finds. For usage, see <a
 href="/guide/developing/tools/layoutopt.html">layoutopt</a>.</p>
 </dd>
 </dl>
diff --git a/drm/drmserver/DrmManager.cpp b/drm/drmserver/DrmManager.cpp
index 3e4fe8c..b2fa053 100644
--- a/drm/drmserver/DrmManager.cpp
+++ b/drm/drmserver/DrmManager.cpp
@@ -98,21 +98,27 @@
 }
 
 status_t DrmManager::loadPlugIns() {
+
+    String8 vendorPluginDirPath("/vendor/lib/drm");
+    loadPlugIns(vendorPluginDirPath);
+
     String8 pluginDirPath("/system/lib/drm");
-    return loadPlugIns(pluginDirPath);
+    loadPlugIns(pluginDirPath);
+    return DRM_NO_ERROR;
+
 }
 
 status_t DrmManager::loadPlugIns(const String8& plugInDirPath) {
-    if (mSupportInfoToPlugInIdMap.isEmpty()) {
-        mPlugInManager.loadPlugIns(plugInDirPath);
-        Vector<String8> plugInPathList = mPlugInManager.getPlugInIdList();
-        for (unsigned int i = 0; i < plugInPathList.size(); ++i) {
-            String8 plugInPath = plugInPathList[i];
-            DrmSupportInfo* info = mPlugInManager.getPlugIn(plugInPath).getSupportInfo(0);
-            if (NULL != info) {
+    mPlugInManager.loadPlugIns(plugInDirPath);
+    Vector<String8> plugInPathList = mPlugInManager.getPlugInIdList();
+    for (unsigned int i = 0; i < plugInPathList.size(); ++i) {
+        String8 plugInPath = plugInPathList[i];
+        DrmSupportInfo* info = mPlugInManager.getPlugIn(plugInPath).getSupportInfo(0);
+        if (NULL != info) {
+            if (mSupportInfoToPlugInIdMap.indexOfKey(*info) < 0) {
                 mSupportInfoToPlugInIdMap.add(*info, plugInPath);
-                delete info;
             }
+            delete info;
         }
     }
     return DRM_NO_ERROR;
diff --git a/include/surfaceflinger/ISurfaceComposer.h b/include/surfaceflinger/ISurfaceComposer.h
index 6b31ca4..e0f4cf9 100644
--- a/include/surfaceflinger/ISurfaceComposer.h
+++ b/include/surfaceflinger/ISurfaceComposer.h
@@ -88,11 +88,6 @@
         eElectronBeamAnimationOff = 0x10
     };
 
-    // flags for setOrientation
-    enum {
-        eOrientationAnimationDisable = 0x00000001
-    };
-
     /* create connection with surface flinger, requires
      * ACCESS_SURFACE_FLINGER permission
      */
@@ -112,7 +107,8 @@
     virtual status_t freezeDisplay(DisplayID dpy, uint32_t flags) = 0;
     virtual status_t unfreezeDisplay(DisplayID dpy, uint32_t flags) = 0;
 
-    /* Set display orientation. requires ACCESS_SURFACE_FLINGER permission */
+    /* Set display orientation. requires ACCESS_SURFACE_FLINGER permission
+     * No flags are currently defined.  Set flags to 0. */
     virtual int setOrientation(DisplayID dpy, int orientation, uint32_t flags) = 0;
 
     /* signal that we're done booting.
diff --git a/media/java/android/media/Ringtone.java b/media/java/android/media/Ringtone.java
index 0ce3526..f2c1694 100644
--- a/media/java/android/media/Ringtone.java
+++ b/media/java/android/media/Ringtone.java
@@ -203,7 +203,22 @@
         mUri = uri;
         openMediaPlayer();
     }
-    
+
+    /** @hide */
+    public void setWakeMode(Context context, int mode) {
+        if (mAudio == null) {
+            try {
+                openMediaPlayer();
+            } catch (Exception ex) {
+                Log.e(TAG, "setWakeMode() caught ", ex);
+                mAudio = null;
+            }
+        }
+        if (mAudio != null) {
+            mAudio.setWakeMode(context, mode);
+        }
+    }
+
     /**
      * Plays the ringtone.
      */
diff --git a/media/libstagefright/AVIExtractor.cpp b/media/libstagefright/AVIExtractor.cpp
index 4e46414..d47e5d1 100644
--- a/media/libstagefright/AVIExtractor.cpp
+++ b/media/libstagefright/AVIExtractor.cpp
@@ -18,6 +18,7 @@
 #define LOG_TAG "AVIExtractor"
 #include <utils/Log.h>
 
+#include "include/avc_utils.h"
 #include "include/AVIExtractor.h"
 
 #include <binder/ProcessState.h>
@@ -362,6 +363,13 @@
         case FOURCC('X', 'V', 'I', 'X'):
             return MEDIA_MIMETYPE_VIDEO_MPEG4;
 
+        // from http://wiki.multimedia.cx/index.php?title=H264
+        case FOURCC('a', 'v', 'c', '1'):
+        case FOURCC('d', 'a', 'v', 'c'):
+        case FOURCC('x', '2', '6', '4'):
+        case FOURCC('v', 's', 's', 'h'):
+            return MEDIA_MIMETYPE_VIDEO_AVC;
+
         default:
             return NULL;
     }
@@ -406,6 +414,14 @@
             return ERROR_MALFORMED;
         }
 
+        if (mime == NULL) {
+            LOGW("Unsupported video format '%c%c%c%c'",
+                 (char)(handler >> 24),
+                 (char)((handler >> 16) & 0xff),
+                 (char)((handler >> 8) & 0xff),
+                 (char)(handler & 0xff));
+        }
+
         kind = Track::VIDEO;
     } else if (type == FOURCC('a', 'u', 'd', 's')) {
         if (mime && strncasecmp(mime, "audio/", 6)) {
@@ -473,8 +489,11 @@
         track->mMeta->setInt32(kKeyHeight, height);
     } else {
         uint32_t format = U16LE_AT(data);
+
         if (format == 0x55) {
             track->mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
+        } else {
+            LOGW("Unsupported audio format = 0x%04x", format);
         }
 
         uint32_t numChannels = U16LE_AT(&data[2]);
@@ -646,21 +665,26 @@
 
         AString mime = tmp;
 
-        if (!strncasecmp("video/", mime.c_str(), 6)
-                && track->mThumbnailSampleIndex >= 0) {
-            int64_t thumbnailTimeUs;
-            CHECK_EQ((status_t)OK,
-                     getSampleTime(i, track->mThumbnailSampleIndex,
-                                   &thumbnailTimeUs));
+        if (!strncasecmp("video/", mime.c_str(), 6)) {
+            if (track->mThumbnailSampleIndex >= 0) {
+                int64_t thumbnailTimeUs;
+                CHECK_EQ((status_t)OK,
+                         getSampleTime(i, track->mThumbnailSampleIndex,
+                                       &thumbnailTimeUs));
 
-            track->mMeta->setInt64(kKeyThumbnailTime, thumbnailTimeUs);
+                track->mMeta->setInt64(kKeyThumbnailTime, thumbnailTimeUs);
+            }
+
+            status_t err = OK;
 
             if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_VIDEO_MPEG4)) {
-                status_t err = addMPEG4CodecSpecificData(i);
+                err = addMPEG4CodecSpecificData(i);
+            } else if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)) {
+                err = addH264CodecSpecificData(i);
+            }
 
-                if (err != OK) {
-                    return err;
-                }
+            if (err != OK) {
+                return err;
             }
         }
 
@@ -781,6 +805,63 @@
     return OK;
 }
 
+status_t AVIExtractor::addH264CodecSpecificData(size_t trackIndex) {
+    Track *track = &mTracks.editItemAt(trackIndex);
+
+    off64_t offset;
+    size_t size;
+    bool isKey;
+    int64_t timeUs;
+
+    // Extract codec specific data from the first non-empty sample.
+
+    size_t sampleIndex = 0;
+    for (;;) {
+        status_t err =
+            getSampleInfo(
+                    trackIndex, sampleIndex, &offset, &size, &isKey, &timeUs);
+
+        if (err != OK) {
+            return err;
+        }
+
+        if (size > 0) {
+            break;
+        }
+
+        ++sampleIndex;
+    }
+
+    sp<ABuffer> buffer = new ABuffer(size);
+    ssize_t n = mDataSource->readAt(offset, buffer->data(), buffer->size());
+
+    if (n < (ssize_t)size) {
+        return n < 0 ? (status_t)n : ERROR_MALFORMED;
+    }
+
+    sp<MetaData> meta = MakeAVCCodecSpecificData(buffer);
+
+    if (meta == NULL) {
+        LOGE("Unable to extract AVC codec specific data");
+        return ERROR_MALFORMED;
+    }
+
+    int32_t width, height;
+    CHECK(meta->findInt32(kKeyWidth, &width));
+    CHECK(meta->findInt32(kKeyHeight, &height));
+
+    uint32_t type;
+    const void *csd;
+    size_t csdSize;
+    CHECK(meta->findData(kKeyAVCC, &type, &csd, &csdSize));
+
+    track->mMeta->setInt32(kKeyWidth, width);
+    track->mMeta->setInt32(kKeyHeight, width);
+    track->mMeta->setData(kKeyAVCC, type, csd, csdSize);
+
+    return OK;
+}
+
 status_t AVIExtractor::getSampleInfo(
         size_t trackIndex, size_t sampleIndex,
         off64_t *offset, size_t *size, bool *isKey,
diff --git a/media/libstagefright/avc_utils.cpp b/media/libstagefright/avc_utils.cpp
index 07aa140..153ee33 100644
--- a/media/libstagefright/avc_utils.cpp
+++ b/media/libstagefright/avc_utils.cpp
@@ -297,7 +297,7 @@
     sp<MetaData> meta = new MetaData;
     meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
 
-    meta->setData(kKeyAVCC, 0, csd->data(), csd->size());
+    meta->setData(kKeyAVCC, kTypeAVCC, csd->data(), csd->size());
     meta->setInt32(kKeyWidth, width);
     meta->setInt32(kKeyHeight, height);
 
diff --git a/media/libstagefright/include/AVIExtractor.h b/media/libstagefright/include/AVIExtractor.h
index b575347..75ce68d 100644
--- a/media/libstagefright/include/AVIExtractor.h
+++ b/media/libstagefright/include/AVIExtractor.h
@@ -101,6 +101,7 @@
             size_t *sampleIndex) const;
 
     status_t addMPEG4CodecSpecificData(size_t trackIndex);
+    status_t addH264CodecSpecificData(size_t trackIndex);
 
     static bool IsCorrectChunkType(
         ssize_t trackIndex, Track::Kind kind, uint32_t chunkType);
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
index 4f39e69..b851ab7 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsBackupAgent.java
@@ -16,6 +16,21 @@
 
 package com.android.providers.settings;
 
+import android.app.backup.BackupAgentHelper;
+import android.app.backup.BackupDataInput;
+import android.app.backup.BackupDataOutput;
+import android.app.backup.FullBackupDataOutput;
+import android.content.ContentValues;
+import android.content.Context;
+import android.database.Cursor;
+import android.net.Uri;
+import android.net.wifi.WifiManager;
+import android.os.FileUtils;
+import android.os.ParcelFileDescriptor;
+import android.os.Process;
+import android.provider.Settings;
+import android.util.Log;
+
 import java.io.BufferedOutputStream;
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
@@ -27,28 +42,13 @@
 import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.FileWriter;
-import java.io.InputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.OutputStream;
-import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.zip.CRC32;
 
-import android.app.backup.BackupDataInput;
-import android.app.backup.BackupDataOutput;
-import android.app.backup.BackupAgentHelper;
-import android.app.backup.FullBackupDataOutput;
-import android.content.ContentValues;
-import android.content.Context;
-import android.database.Cursor;
-import android.net.Uri;
-import android.net.wifi.WifiManager;
-import android.os.FileUtils;
-import android.os.ParcelFileDescriptor;
-import android.os.Process;
-import android.provider.Settings;
-import android.text.TextUtils;
-import android.util.Log;
-
 /**
  * Performs backup and restore of the System and Secure settings.
  * List of settings that are backed up are stored in the Settings.java file
@@ -79,8 +79,7 @@
     // Versioning of the 'full backup' format
     private static final int FULL_BACKUP_VERSION = 1;
 
-    private static String[] sortedSystemKeys = null;
-    private static String[] sortedSecureKeys = null;
+    private static final int INTEGER_BYTE_COUNT = Integer.SIZE / Byte.SIZE;
 
     private static final byte[] EMPTY_DATA = new byte[0];
 
@@ -112,6 +111,7 @@
     private WifiManager mWfm;
     private static String mWifiConfigFile;
 
+    @Override
     public void onCreate() {
         if (DEBUG_BACKUP) Log.d(TAG, "onCreate() invoked");
 
@@ -348,26 +348,17 @@
     }
 
     private byte[] getSystemSettings() {
-        Cursor sortedCursor = getContentResolver().query(Settings.System.CONTENT_URI, PROJECTION,
-                null, null, Settings.NameValueTable.NAME);
-        // Copy and sort the array
-        if (sortedSystemKeys == null) {
-            sortedSystemKeys = copyAndSort(Settings.System.SETTINGS_TO_BACKUP);
-        }
-        byte[] result = extractRelevantValues(sortedCursor, sortedSystemKeys);
-        sortedCursor.close();
+        Cursor cursor = getContentResolver().query(Settings.System.CONTENT_URI, PROJECTION, null,
+                null, null);
+        byte[] result = extractRelevantValues(cursor, Settings.System.SETTINGS_TO_BACKUP);
+        cursor.close();
         return result;
     }
 
     private byte[] getSecureSettings() {
-        Cursor sortedCursor = getContentResolver().query(Settings.Secure.CONTENT_URI, PROJECTION,
-                null, null, Settings.NameValueTable.NAME);
-        // Copy and sort the array
-        if (sortedSecureKeys == null) {
-            sortedSecureKeys = copyAndSort(Settings.Secure.SETTINGS_TO_BACKUP);
-        }
-        byte[] result = extractRelevantValues(sortedCursor, sortedSecureKeys);
-        sortedCursor.close();
+        Cursor cursor = getContentResolver().query(Settings.Secure.CONTENT_URI, PROJECTION, null,
+                null, null);
+        byte[] result = extractRelevantValues(cursor, Settings.Secure.SETTINGS_TO_BACKUP);
         return result;
     }
 
@@ -383,119 +374,132 @@
     }
 
     private void restoreSettings(byte[] settings, int bytes, Uri contentUri) {
-        if (DEBUG) Log.i(TAG, "restoreSettings: " + contentUri);
+        if (DEBUG) {
+            Log.i(TAG, "restoreSettings: " + contentUri);
+        }
+
+        // Figure out the white list.
         String[] whitelist = null;
         if (contentUri.equals(Settings.Secure.CONTENT_URI)) {
             whitelist = Settings.Secure.SETTINGS_TO_BACKUP;
         } else if (contentUri.equals(Settings.System.CONTENT_URI)) {
             whitelist = Settings.System.SETTINGS_TO_BACKUP;
+        } else {
+            throw new IllegalArgumentException("Unknown URI: " + contentUri);
         }
 
-        ContentValues cv = new ContentValues(2);
+        // Restore only the white list data.
         int pos = 0;
-        while (pos < bytes) {
-            int length = readInt(settings, pos);
-            pos += 4;
-            String settingName = length > 0? new String(settings, pos, length) : null;
-            pos += length;
-            length = readInt(settings, pos);
-            pos += 4;
-            String settingValue = length > 0? new String(settings, pos, length) : null;
-            pos += length;
-            if (!TextUtils.isEmpty(settingName) && !TextUtils.isEmpty(settingValue)) {
-                //Log.i(TAG, "Restore " + settingName + " = " + settingValue);
+        Map<String, String> cachedEntries = new HashMap<String, String>();
+        ContentValues contentValues = new ContentValues(2);
+        SettingsHelper settingsHelper = mSettingsHelper;
 
-                // Only restore settings in our list of known-acceptable data
-                if (invalidSavedSetting(whitelist, settingName)) {
-                    continue;
-                }
+        final int whiteListSize = whitelist.length;
+        for (int i = 0; i < whiteListSize; i++) {
+            String key = whitelist[i];
+            String value = cachedEntries.remove(key);
 
-                if (mSettingsHelper.restoreValue(settingName, settingValue)) {
-                    cv.clear();
-                    cv.put(Settings.NameValueTable.NAME, settingName);
-                    cv.put(Settings.NameValueTable.VALUE, settingValue);
-                    getContentResolver().insert(contentUri, cv);
+            // If the value not cached, let us look it up.
+            if (value == null) {
+                while (pos < bytes) {
+                    int length = readInt(settings, pos);
+                    pos += INTEGER_BYTE_COUNT;
+                    String dataKey = length > 0 ? new String(settings, pos, length) : null;
+                    pos += length;
+                    length = readInt(settings, pos);
+                    pos += INTEGER_BYTE_COUNT;
+                    String dataValue = length > 0 ? new String(settings, pos, length) : null;
+                    pos += length;
+                    if (key.equals(dataKey)) {
+                        value = dataValue;
+                        break;
+                    }
+                    cachedEntries.put(dataKey, dataValue);
                 }
             }
-        }
-    }
 
-    // Returns 'true' if the given setting is one that we refuse to restore
-    private boolean invalidSavedSetting(String[] knownNames, String candidate) {
-        // no filter? allow everything
-        if (knownNames == null) {
-            return false;
-        }
+            if (value == null) {
+                continue;
+            }
 
-        // whitelisted setting?  allow it
-        for (String name : knownNames) {
-            if (name.equals(candidate)) {
-                return false;
+            if (settingsHelper.restoreValue(key, value)) {
+                contentValues.clear();
+                contentValues.put(Settings.NameValueTable.NAME, key);
+                contentValues.put(Settings.NameValueTable.VALUE, value);
+                getContentResolver().insert(contentUri, contentValues);
+            }
+
+            if (DEBUG) {
+                Log.d(TAG, "Restored setting: " + key + "=" + value);
             }
         }
-
-        // refuse everything else
-        if (DEBUG) Log.v(TAG, "Ignoring restore datum: " + candidate);
-        return true;
-    }
-
-    private String[] copyAndSort(String[] keys) {
-        String[] sortedKeys = new String[keys.length];
-        System.arraycopy(keys, 0, sortedKeys, 0, keys.length);
-        Arrays.sort(sortedKeys);
-        return sortedKeys;
     }
 
     /**
-     * Given a cursor sorted by key name and a set of keys sorted by name,
-     * extract the required keys and values and write them to a byte array.
-     * @param sortedCursor
-     * @param sortedKeys
-     * @return
+     * Given a cursor and a set of keys, extract the required keys and
+     * values and write them to a byte array.
+     *
+     * @param cursor A cursor with settings data.
+     * @param settings The settings to extract.
+     * @return The byte array of extracted values.
      */
-    byte[] extractRelevantValues(Cursor sortedCursor, String[] sortedKeys) {
-        byte[][] values = new byte[sortedKeys.length * 2][]; // keys and values
-        if (!sortedCursor.moveToFirst()) {
+    private byte[] extractRelevantValues(Cursor cursor, String[] settings) {
+        final int settingsCount = settings.length;
+        byte[][] values = new byte[settingsCount * 2][]; // keys and values
+        if (!cursor.moveToFirst()) {
             Log.e(TAG, "Couldn't read from the cursor");
             return new byte[0];
         }
-        int keyIndex = 0;
+
+        // Obtain the relevant data in a temporary array.
         int totalSize = 0;
-        while (!sortedCursor.isAfterLast()) {
-            String name = sortedCursor.getString(COLUMN_NAME);
-            while (sortedKeys[keyIndex].compareTo(name.toString()) < 0) {
-                keyIndex++;
-                if (keyIndex == sortedKeys.length) break;
-            }
-            if (keyIndex < sortedKeys.length && name.equals(sortedKeys[keyIndex])) {
-                String value = sortedCursor.getString(COLUMN_VALUE);
-                byte[] nameBytes = name.toString().getBytes();
-                totalSize += 4 + nameBytes.length;
-                values[keyIndex * 2] = nameBytes;
-                byte[] valueBytes;
-                if (TextUtils.isEmpty(value)) {
-                    valueBytes = null;
-                    totalSize += 4;
-                } else {
-                    valueBytes = value.toString().getBytes();
-                    totalSize += 4 + valueBytes.length;
-                    //Log.i(TAG, "Backing up " + name + " = " + value);
+        int backedUpSettingIndex = 0;
+        Map<String, String> cachedEntries = new HashMap<String, String>();
+        for (int i = 0; i < settingsCount; i++) {
+            String key = settings[i];
+            String value = cachedEntries.remove(key);
+
+            // If the value not cached, let us look it up.
+            if (value == null) {
+                while (!cursor.isAfterLast()) {
+                    String cursorKey = cursor.getString(COLUMN_NAME);
+                    String cursorValue = cursor.getString(COLUMN_VALUE);
+                    cursor.moveToNext();
+                    if (key.equals(cursorKey)) {
+                        value = cursorValue;
+                        break;
+                    }
+                    cachedEntries.put(cursorKey, cursorValue);
                 }
-                values[keyIndex * 2 + 1] = valueBytes;
-                keyIndex++;
             }
-            if (keyIndex == sortedKeys.length || !sortedCursor.moveToNext()) {
-                break;
+
+            if (value == null) {
+                continue;
+            }
+
+            // Write the key and value in the intermediary array.
+            byte[] keyBytes = key.getBytes();
+            totalSize += INTEGER_BYTE_COUNT + keyBytes.length;
+            values[backedUpSettingIndex * 2] = keyBytes;
+
+            byte[] valueBytes = value.getBytes();
+            totalSize += INTEGER_BYTE_COUNT + valueBytes.length;
+            values[backedUpSettingIndex * 2 + 1] = valueBytes;
+
+            backedUpSettingIndex++;
+
+            if (DEBUG) {
+                Log.d(TAG, "Backed up setting: " + key + "=" + value);
             }
         }
 
+        // Aggregate the result.
         byte[] result = new byte[totalSize];
         int pos = 0;
-        for (int i = 0; i < sortedKeys.length * 2; i++) {
-            if (values[i] != null) {
-                pos = writeInt(result, pos, values[i].length);
-                pos = writeBytes(result, pos, values[i]);
-            }
+        final int keyValuePairCount = backedUpSettingIndex * 2;
+        for (int i = 0; i < keyValuePairCount; i++) {
+            pos = writeInt(result, pos, values[i].length);
+            pos = writeBytes(result, pos, values[i]);
         }
         return result;
     }
@@ -647,14 +651,14 @@
      * @param out byte array
      * @param pos current pos in array
      * @param value integer to write
-     * @return the index after adding the size of an int (4)
+     * @return the index after adding the size of an int (4) in bytes.
      */
     private int writeInt(byte[] out, int pos, int value) {
         out[pos + 0] = (byte) ((value >> 24) & 0xFF);
         out[pos + 1] = (byte) ((value >> 16) & 0xFF);
         out[pos + 2] = (byte) ((value >>  8) & 0xFF);
         out[pos + 3] = (byte) ((value >>  0) & 0xFF);
-        return pos + 4;
+        return pos + INTEGER_BYTE_COUNT;
     }
 
     private int writeBytes(byte[] out, int pos, byte[] value) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
index 8fc8448..da6bcd2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -2031,8 +2031,13 @@
     // The user is not allowed to get stuck without navigation UI. Upon the slightest user
     // interaction we bring the navigation back.
     public void userActivity() {
-        if (mNavigationBarView != null) {
-            mNavigationBarView.setHidden(false);
+        if (0 != (mSystemUiVisibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)) {
+            try {
+                mBarService.setSystemUiVisibility(
+                    mSystemUiVisibility & ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
+            } catch (RemoteException ex) {
+                // weep softly
+            }
         }
     }
 
diff --git a/policy/src/com/android/internal/policy/impl/KeyguardUpdateMonitor.java b/policy/src/com/android/internal/policy/impl/KeyguardUpdateMonitor.java
index 958f555..2a23709 100644
--- a/policy/src/com/android/internal/policy/impl/KeyguardUpdateMonitor.java
+++ b/policy/src/com/android/internal/policy/impl/KeyguardUpdateMonitor.java
@@ -484,6 +484,9 @@
     public void registerInfoCallback(InfoCallback callback) {
         if (!mInfoCallbacks.contains(callback)) {
             mInfoCallbacks.add(callback);
+            // notify the register the current state right away
+            // TODO: need call other callback methods
+            callback.onRefreshCarrierInfo(mTelephonyPlmn, mTelephonySpn);
         } else {
             if (DEBUG) Log.e(TAG, "Object tried to add another INFO callback",
                     new Exception("Whoops"));
@@ -497,6 +500,10 @@
     public void registerSimStateCallback(SimStateCallback callback) {
         if (!mSimStateCallbacks.contains(callback)) {
             mSimStateCallbacks.add(callback);
+            // notify the register the current sim state right away,
+            // otherwise the register won't receive any state until
+            // sim state gets changed again.
+            callback.onSimStateChanged(mSimState);
         } else {
             if (DEBUG) Log.e(TAG, "Object tried to add another SIM callback",
                     new Exception("Whoops"));
diff --git a/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java b/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java
index 5d3dee9..0f1d633 100644
--- a/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java
+++ b/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java
@@ -1054,6 +1054,7 @@
                     final Ringtone sfx = RingtoneManager.getRingtone(mContext, soundUri);
                     if (sfx != null) {
                         sfx.setStreamType(AudioManager.STREAM_SYSTEM);
+                        sfx.setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
                         sfx.play();
                     } else {
                         if (DEBUG) Log.d(TAG, "playSounds: failed to load ringtone from uri: "
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindow.java b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
index 1b7271d..53b64a6 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindow.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
@@ -43,6 +43,7 @@
 import android.content.Context;
 import android.content.pm.ActivityInfo;
 import android.content.res.Configuration;
+import android.content.res.Resources;
 import android.content.res.TypedArray;
 import android.graphics.Canvas;
 import android.graphics.PixelFormat;
@@ -63,6 +64,7 @@
 import android.util.SparseArray;
 import android.util.TypedValue;
 import android.view.ActionMode;
+import android.view.ContextThemeWrapper;
 import android.view.Gravity;
 import android.view.IRotationWatcher;
 import android.view.IWindowManager;
@@ -990,7 +992,23 @@
      * @return Whether the initialization was successful.
      */
     protected boolean initializePanelMenu(final PanelFeatureState st) {
-        final MenuBuilder menu = new MenuBuilder(getContext());
+        Context context = getContext();
+
+        // If we have an action bar, initialize the menu with a context themed for it.
+        if ((st.featureId == FEATURE_OPTIONS_PANEL || st.featureId == FEATURE_ACTION_BAR) &&
+                mActionBar != null) {
+            TypedValue outValue = new TypedValue();
+            Resources.Theme currentTheme = context.getTheme();
+            currentTheme.resolveAttribute(com.android.internal.R.attr.actionBarWidgetTheme,
+                    outValue, true);
+            final int targetThemeRes = outValue.resourceId;
+
+            if (targetThemeRes != 0 && context.getThemeResId() != targetThemeRes) {
+                context = new ContextThemeWrapper(context, targetThemeRes);
+            }
+        }
+
+        final MenuBuilder menu = new MenuBuilder(context);
 
         menu.setCallback(this);
         st.setMenu(menu);
@@ -2135,6 +2153,7 @@
                                 com.android.internal.R.attr.actionModePopupWindowStyle);
                         mActionModePopup.setLayoutInScreenEnabled(true);
                         mActionModePopup.setLayoutInsetDecor(true);
+                        mActionModePopup.setFocusable(true);
                         mActionModePopup.setWindowLayoutType(
                                 WindowManager.LayoutParams.TYPE_APPLICATION);
                         mActionModePopup.setContentView(mActionModeView);
@@ -3470,6 +3489,8 @@
         }
 
         public boolean onOpenSubMenu(MenuBuilder subMenu) {
+            if (subMenu == null) return false;
+
             // Set a simple callback for the submenu
             subMenu.setCallback(this);
 
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
index c8c0041..b0abd97 100755
--- a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -280,7 +280,7 @@
     int mUserRotationMode = WindowManagerPolicy.USER_ROTATION_FREE;
     int mUserRotation = Surface.ROTATION_0;
 
-    boolean mAllowAllRotations;
+    int mAllowAllRotations = -1;
     boolean mCarDockEnablesAccelerometer;
     boolean mDeskDockEnablesAccelerometer;
     int mLidKeyboardAccessibility;
@@ -385,9 +385,6 @@
     int mPortraitRotation = 0;   // default portrait rotation
     int mUpsideDownRotation = 0; // "other" portrait rotation
 
-    // Nothing to see here, move along...
-    int mFancyRotationAnimation;
-    
     // What we do when the user long presses on home
     private int mLongPressOnHomeBehavior = -1;
 
@@ -439,12 +436,7 @@
 
         @Override public void onChange(boolean selfChange) {
             updateSettings();
-            try {
-                mWindowManager.setRotation(USE_LAST_ROTATION, false,
-                        mFancyRotationAnimation);
-            } catch (RemoteException e) {
-                // Ignore
-            }
+            updateRotation(false);
         }
     }
     
@@ -457,45 +449,11 @@
         public void onOrientationChanged(int rotation) {
             // Send updates based on orientation value
             if (localLOGV) Log.v(TAG, "onOrientationChanged, rotation changed to " +rotation);
-            try {
-                mWindowManager.setRotation(rotation, false,
-                        mFancyRotationAnimation);
-            } catch (RemoteException e) {
-                // Ignore
-
-            }
-        }                                      
+            updateRotation(false);
+        }
     }
     MyOrientationListener mOrientationListener;
 
-    boolean useSensorForOrientationLp(int appOrientation) {
-        // The app says use the sensor.
-        if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
-                || appOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
-                || appOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
-                || appOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
-            return true;
-        }
-        // The user preference says we can rotate, and the app is willing to rotate.
-        if (mAccelerometerDefault != 0 &&
-                (appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER
-                 || appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)) {
-            return true;
-        }
-        // We're in a dock that has a rotation affinity, and the app is willing to rotate.
-        if ((mCarDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_CAR)
-                || (mDeskDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_DESK)) {
-            // Note we override the nosensor flag here.
-            if (appOrientation == ActivityInfo.SCREEN_ORIENTATION_USER
-                    || appOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
-                    || appOrientation == ActivityInfo.SCREEN_ORIENTATION_NOSENSOR) {
-                return true;
-            }
-        }
-        // Else, don't use the sensor.
-        return false;
-    }
-    
     /*
      * We always let the sensor be switched on by default except when
      * the user has explicitly disabled sensor based rotation or when the
@@ -723,8 +681,6 @@
                 com.android.internal.R.integer.config_carDockRotation);
         mDeskDockRotation = readRotation(
                 com.android.internal.R.integer.config_deskDockRotation);
-        mAllowAllRotations = mContext.getResources().getBoolean(
-                com.android.internal.R.bool.config_allowAllRotations);
         mCarDockEnablesAccelerometer = mContext.getResources().getBoolean(
                 com.android.internal.R.bool.config_carDockEnablesAccelerometer);
         mDeskDockEnablesAccelerometer = mContext.getResources().getBoolean(
@@ -760,6 +716,13 @@
 
         // Controls rotation and the like.
         initializeHdmiState();
+
+        // Match current screen state.
+        if (mPowerManager.isScreenOn()) {
+            screenTurningOn(null);
+        } else {
+            screenTurnedOff(WindowManagerPolicy.OFF_BECAUSE_OF_USER);
+        }
     }
 
     public void setInitialDisplaySize(int width, int height) {
@@ -826,8 +789,6 @@
             mIncallPowerBehavior = Settings.Secure.getInt(resolver,
                     Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR,
                     Settings.Secure.INCALL_POWER_BUTTON_BEHAVIOR_DEFAULT);
-            mFancyRotationAnimation = Settings.System.getInt(resolver,
-                    "fancy_rotation_anim", 0) != 0 ? 0x80 : 0;
             int accelerometerDefault = Settings.System.getInt(resolver,
                     Settings.System.ACCELEROMETER_ROTATION, DEFAULT_ACCELEROMETER_ROTATION);
             
@@ -882,7 +843,7 @@
             updateScreenSaverTimeoutLocked();
         }
         if (updateRotation) {
-            updateRotation(0);
+            updateRotation(true);
         }
         if (addView != null) {
             WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
@@ -1025,8 +986,7 @@
     /** {@inheritDoc} */
     public void adjustConfigurationLw(Configuration config) {
         readLidState();
-
-        mPowerManager.setKeyboardVisibility(mLidOpen == LID_OPEN);
+        updateKeyboardVisibility();
 
         if (config.keyboard == Configuration.KEYBOARD_NOKEYS) {
             config.hardKeyboardHidden = Configuration.HARDKEYBOARDHIDDEN_YES;
@@ -2295,8 +2255,10 @@
     public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
         // lid changed state
         mLidOpen = lidOpen ? LID_OPEN : LID_CLOSED;
+        updateKeyboardVisibility();
+
         boolean awakeNow = mKeyguardMediator.doLidChangeTq(lidOpen);
-        updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
+        updateRotation(true);
         if (awakeNow) {
             // If the lid is opening and we don't have to keep the
             // keyguard up, then we can turn on the screen
@@ -2325,7 +2287,7 @@
     void setHdmiPlugged(boolean plugged) {
         if (mHdmiPlugged != plugged) {
             mHdmiPlugged = plugged;
-            updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
+            updateRotation(true);
             Intent intent = new Intent(ACTION_HDMI_PLUGGED);
             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
             intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
@@ -2802,7 +2764,7 @@
                 } catch (RemoteException e) {
                 }
             }
-            updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
+            updateRotation(true);
             updateOrientationListenerLp();
         }
     };
@@ -2825,31 +2787,42 @@
     /** {@inheritDoc} */
     public void screenTurningOn(final ScreenOnListener screenOnListener) {
         EventLog.writeEvent(70000, 1);
-        //Slog.i(TAG, "Screen turning on...");
-        mKeyguardMediator.onScreenTurnedOn(new KeyguardViewManager.ShowListener() {
-            @Override public void onShown(IBinder windowToken) {
-                if (windowToken != null) {
-                    try {
-                        mWindowManager.waitForWindowDrawn(windowToken, new IRemoteCallback.Stub() {
-                            @Override public void sendResult(Bundle data) {
-                                Slog.i(TAG, "Lock screen displayed!");
-                                screenOnListener.onScreenOn();
-                                synchronized (mLock) {
-                                    mScreenOnFully = true;
+        if (false) {
+            RuntimeException here = new RuntimeException("here");
+            here.fillInStackTrace();
+            Slog.i(TAG, "Screen turning on...", here);
+        }
+        if (screenOnListener != null) {
+            mKeyguardMediator.onScreenTurnedOn(new KeyguardViewManager.ShowListener() {
+                @Override public void onShown(IBinder windowToken) {
+                    if (windowToken != null) {
+                        try {
+                            mWindowManager.waitForWindowDrawn(windowToken,
+                                    new IRemoteCallback.Stub() {
+                                @Override public void sendResult(Bundle data) {
+                                    Slog.i(TAG, "Lock screen displayed!");
+                                    screenOnListener.onScreenOn();
+                                    synchronized (mLock) {
+                                        mScreenOnFully = true;
+                                    }
                                 }
-                            }
-                        });
-                    } catch (RemoteException e) {
-                    }
-                } else {
-                    Slog.i(TAG, "No lock screen!");
-                    screenOnListener.onScreenOn();
-                    synchronized (mLock) {
-                        mScreenOnFully = true;
+                            });
+                        } catch (RemoteException e) {
+                        }
+                    } else {
+                        Slog.i(TAG, "No lock screen!");
+                        screenOnListener.onScreenOn();
+                        synchronized (mLock) {
+                            mScreenOnFully = true;
+                        }
                     }
                 }
+            });
+        } else {
+            synchronized (mLock) {
+                mScreenOnFully = true;
             }
-        });
+        }
         synchronized (mLock) {
             mScreenOnEarly = true;
             updateOrientationListenerLp();
@@ -2914,10 +2887,9 @@
             }
         }
     }
-    
-    public int rotationForOrientationLw(int orientation, int lastRotation,
-            boolean displayEnabled) {
 
+    @Override
+    public int rotationForOrientationLw(int orientation, int lastRotation) {
         if (false) {
             Slog.v(TAG, "rotationForOrientationLw(orient="
                         + orientation + ", last=" + lastRotation
@@ -2928,128 +2900,136 @@
         }
 
         synchronized (mLock) {
+            int sensorRotation = mOrientationListener.getCurrentRotation(); // may be -1
+
+            int preferredRotation = -1;
+            if (mHdmiPlugged) {
+                // Ignore sensor when plugged into HDMI.
+                preferredRotation = mLandscapeRotation;
+            } else if (mLidOpen == LID_OPEN && mLidOpenRotation >= 0) {
+                // Ignore sensor when lid switch is open and rotation is forced.
+                preferredRotation = mLidOpenRotation;
+            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR
+                    && ((mCarDockEnablesAccelerometer && sensorRotation >= 0)
+                            || mCarDockRotation >= 0)) {
+                // Ignore sensor when in car dock unless explicitly enabled.
+                // This case can override the behavior of NOSENSOR, and can also
+                // enable 180 degree rotation while docked.
+                preferredRotation = mCarDockEnablesAccelerometer && sensorRotation >= 0
+                        ? sensorRotation : mCarDockRotation;
+            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
+                    && ((mDeskDockEnablesAccelerometer && sensorRotation >= 0)
+                            || mDeskDockRotation >= 0)) {
+                // Ignore sensor when in desk dock unless explicitly enabled.
+                // This case can override the behavior of NOSENSOR, and can also
+                // enable 180 degree rotation while docked.
+                preferredRotation = mDeskDockEnablesAccelerometer && sensorRotation >= 0
+                        ? sensorRotation : mDeskDockRotation;
+            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
+                // Ignore sensor when user locked rotation.
+                preferredRotation = mUserRotation;
+            } else if ((mAccelerometerDefault != 0
+                            && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
+                                    || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED))
+                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
+                    || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
+                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
+                    || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) {
+                // Otherwise, use sensor only if requested by the application or enabled
+                // by default for USER or UNSPECIFIED modes.  Does not apply to NOSENSOR.
+                if (mAllowAllRotations < 0) {
+                    // Can't read this during init() because the context doesn't
+                    // have display metrics at that time so we cannot determine
+                    // tablet vs. phone then.
+                    mAllowAllRotations = mContext.getResources().getBoolean(
+                            com.android.internal.R.bool.config_allowAllRotations) ? 1 : 0;
+                }
+                if (sensorRotation != Surface.ROTATION_180
+                        || mAllowAllRotations == 1
+                        || orientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR) {
+                    preferredRotation = sensorRotation;
+                } else {
+                    preferredRotation = lastRotation;
+                }
+            }
+
+            // TODO: Sometimes, we might want to override the application-requested
+            //       orientation, such as when HDMI is plugged in or when docked.
+            //       We can do that by modifying the appropriate cases above to return
+            //       the preferred orientation directly instead of continuing on down here.
+
             switch (orientation) {
                 case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
-                    //always return portrait if orientation set to portrait
+                    // Always return portrait if orientation set to portrait.
                     return mPortraitRotation;
-                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
-                    //always return landscape if orientation set to landscape
-                    return mLandscapeRotation;
-                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
-                    //always return portrait if orientation set to portrait
-                    return mUpsideDownRotation;
-                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
-                    //always return seascape if orientation set to reverse landscape
-                    return mSeascapeRotation;
-                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
-                    //return either landscape rotation based on the sensor
-                    return getCurrentLandscapeRotation(lastRotation);
-                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
-                    return getCurrentPortraitRotation(lastRotation);
-            }
 
-            // case for nosensor meaning ignore sensor and consider only lid
-            // or orientation sensor disabled
-            //or case.unspecified
-            if (mHdmiPlugged) {
-                return mLandscapeRotation;
-            } else if (mLidOpen == LID_OPEN) {
-                return mLidOpenRotation;
-            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
-                return mCarDockRotation;
-            } else if (mDockMode == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
-                return mDeskDockRotation;
-            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
-                return mUserRotation;
-            } else {
-                if (useSensorForOrientationLp(orientation)) {
-                    // Disable 180 degree rotation unless allowed by default for the device
-                    // or explicitly requested by the application.
-                    int rotation = mOrientationListener.getCurrentRotation(lastRotation);
-                    if (rotation == Surface.ROTATION_180
-                            && !mAllowAllRotations
-                            && orientation != ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR) {
+                case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
+                    // Always return landscape if orientation set to landscape.
+                    return mLandscapeRotation;
+
+                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
+                    // Always return portrait if orientation set to portrait.
+                    return mUpsideDownRotation;
+
+                case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
+                    // Always return seascape if orientation set to reverse landscape.
+                    return mSeascapeRotation;
+
+                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
+                    // Return either landscape rotation.
+                    if (isLandscapeOrSeascape(preferredRotation)) {
+                        return preferredRotation;
+                    }
+                    if (isLandscapeOrSeascape(lastRotation)) {
                         return lastRotation;
                     }
-                    return rotation;
-                }
-                return Surface.ROTATION_0;
-            }
-        }
-    }
+                    return mLandscapeRotation;
 
-    public int getLockedRotationLw() {
-        synchronized (mLock) {
-            if (false) {
-                // Not yet working.
-                if (mHdmiPlugged) {
+                case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
+                    // Return either portrait rotation.
+                    if (isAnyPortrait(preferredRotation)) {
+                        return preferredRotation;
+                    }
+                    if (isAnyPortrait(lastRotation)) {
+                        return lastRotation;
+                    }
+                    return mPortraitRotation;
+
+                default:
+                    // For USER, UNSPECIFIED and NOSENSOR, just return the preferred
+                    // orientation we already calculated.
+                    if (preferredRotation >= 0) {
+                        return preferredRotation;
+                    }
                     return Surface.ROTATION_0;
-                } else if (mLidOpen == LID_OPEN) {
-                    return mLidOpenRotation;
-                } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
-                    return mCarDockRotation;
-                } else if (mDockMode == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
-                    return mDeskDockRotation;
-                } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
-                    return mUserRotation;
-                }
-            }
-            return -1;
-        }
-    }
-
-    private int getCurrentLandscapeRotation(int lastRotation) {
-        // if the user has locked rotation, we ignore the sensor 
-        if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
-            if (isLandscapeOrSeascape(mUserRotation)) {
-                return mUserRotation;
-            } else {
-                // it seems odd to obey the sensor at all if rotation lock is enabled
-                return mLandscapeRotation;
             }
         }
-
-        int sensorRotation = mOrientationListener.getCurrentRotation(lastRotation);
-        if (isLandscapeOrSeascape(sensorRotation)) {
-            return sensorRotation;
-        }
-        // try to preserve the old rotation if it was landscape
-        if (isLandscapeOrSeascape(lastRotation)) {
-            return lastRotation;
-        }
-        // default to one of the primary landscape rotation
-        return mLandscapeRotation;
     }
 
-    private boolean isLandscapeOrSeascape(int sensorRotation) {
-        return sensorRotation == mLandscapeRotation || sensorRotation == mSeascapeRotation;
+    @Override
+    public boolean rotationHasCompatibleMetricsLw(int orientation, int rotation) {
+        switch (orientation) {
+            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
+            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT:
+            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT:
+                return isAnyPortrait(rotation);
+
+            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
+            case ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE:
+            case ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE:
+                return isLandscapeOrSeascape(rotation);
+
+            default:
+                return true;
+        }
     }
 
-    private int getCurrentPortraitRotation(int lastRotation) {
-        // if the user has locked rotation, we ignore the sensor 
-        if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
-            if (isAnyPortrait(mUserRotation)) {
-                return mUserRotation;
-            } else {
-                // it seems odd to obey the sensor at all if rotation lock is enabled
-                return mPortraitRotation;
-            }
-        }
-
-        int sensorRotation = mOrientationListener.getCurrentRotation(lastRotation);
-        if (isAnyPortrait(sensorRotation)) {
-            return sensorRotation;
-        }
-        // try to preserve the old rotation if it was portrait
-        if (isAnyPortrait(lastRotation)) {
-            return lastRotation;
-        }
-        // default to one of the primary portrait rotations
-        return mPortraitRotation;
+    private boolean isLandscapeOrSeascape(int rotation) {
+        return rotation == mLandscapeRotation || rotation == mSeascapeRotation;
     }
 
-    private boolean isAnyPortrait(int sensorRotation) {
-        return sensorRotation == mPortraitRotation || sensorRotation == mUpsideDownRotation;
+    private boolean isAnyPortrait(int rotation) {
+        return rotation == mPortraitRotation || rotation == mUpsideDownRotation;
     }
 
 
@@ -3298,26 +3278,19 @@
     /** {@inheritDoc} */
     public void enableScreenAfterBoot() {
         readLidState();
-        updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
+        updateKeyboardVisibility();
+
+        updateRotation(true);
     }
 
-    void updateRotation(int animFlags) {
+    private void updateKeyboardVisibility() {
         mPowerManager.setKeyboardVisibility(mLidOpen == LID_OPEN);
-        int rotation = Surface.ROTATION_0;
-        if (mHdmiPlugged) {
-            rotation = Surface.ROTATION_0;
-        } else if (mLidOpen == LID_OPEN) {
-            rotation = mLidOpenRotation;
-        } else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
-            rotation = mCarDockRotation;
-        } else if (mDockMode == Intent.EXTRA_DOCK_STATE_DESK && mDeskDockRotation >= 0) {
-            rotation = mDeskDockRotation;
-        }
-        //if lid is closed orientation will be portrait
+    }
+
+    void updateRotation(boolean alwaysSendConfiguration) {
         try {
             //set orientation on WindowManager
-            mWindowManager.setRotation(rotation, true,
-                    mFancyRotationAnimation | animFlags);
+            mWindowManager.updateRotation(alwaysSendConfiguration);
         } catch (RemoteException e) {
             // Ignore
         }
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index 8b58d42..86ac296 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -97,7 +97,7 @@
 public class ConnectivityService extends IConnectivityManager.Stub {
 
     private static final boolean DBG = true;
-    private static final boolean VDBG = true;
+    private static final boolean VDBG = false;
     private static final String TAG = "ConnectivityService";
 
     private static final boolean LOGD_RULES = false;
@@ -867,7 +867,7 @@
     // javadoc from interface
     public int startUsingNetworkFeature(int networkType, String feature,
             IBinder binder) {
-        if (DBG) {
+        if (VDBG) {
             log("startUsingNetworkFeature for net " + networkType + ": " + feature);
         }
         enforceChangePermission();
@@ -933,17 +933,19 @@
                     if (ni.isConnected() == true) {
                         // add the pid-specific dns
                         handleDnsConfigurationChange(usedNetworkType);
-                        if (DBG) log("special network already active");
+                        if (VDBG) log("special network already active");
                         return Phone.APN_ALREADY_ACTIVE;
                     }
-                    if (DBG) log("special network already connecting");
+                    if (VDBG) log("special network already connecting");
                     return Phone.APN_REQUEST_STARTED;
                 }
 
                 // check if the radio in play can make another contact
                 // assume if cannot for now
 
-                if (DBG) log("reconnecting to special network");
+                if (DBG) {
+                    log("startUsingNetworkFeature reconnecting to " + networkType + ": " + feature);
+                }
                 network.reconnect();
                 return Phone.APN_REQUEST_STARTED;
             } else {
@@ -985,7 +987,7 @@
             return stopUsingNetworkFeature(u, true);
         } else {
             // none found!
-            if (VDBG) log("ignoring stopUsingNetworkFeature - not a live request");
+            if (VDBG) log("stopUsingNetworkFeature - not a live request, ignoring");
             return 1;
         }
     }
@@ -999,12 +1001,15 @@
         NetworkStateTracker tracker = null;
         boolean callTeardown = false;  // used to carry our decision outside of sync block
 
-        if (DBG) {
-            log("stopUsingNetworkFeature for net " + networkType +
-                    ": " + feature);
+        if (VDBG) {
+            log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
         }
 
         if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
+            if (DBG) {
+                log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
+                        ", net is invalid");
+            }
             return -1;
         }
 
@@ -1013,7 +1018,10 @@
         synchronized(this) {
             // check if this process still has an outstanding start request
             if (!mFeatureUsers.contains(u)) {
-                if (DBG) log("ignoring - this process has no outstanding requests");
+                if (VDBG) {
+                    log("stopUsingNetworkFeature: this process has no outstanding requests" +
+                        ", ignoring");
+                }
                 return 1;
             }
             u.unlinkDeathRecipient();
@@ -1028,7 +1036,7 @@
             if (ignoreDups == false) {
                 for (FeatureUser x : mFeatureUsers) {
                     if (x.isSameUser(u)) {
-                        if (DBG) log("ignoring stopUsingNetworkFeature as dup is found");
+                        if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
                         return 1;
                     }
                 }
@@ -1039,7 +1047,10 @@
 
             tracker =  mNetTrackers[usedNetworkType];
             if (tracker == null) {
-                if (DBG) log("ignoring - no known tracker for net type " + usedNetworkType);
+                if (DBG) {
+                    log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
+                            " no known tracker for used net type " + usedNetworkType);
+                }
                 return -1;
             }
             if (usedNetworkType != networkType) {
@@ -1047,17 +1058,25 @@
                 mNetRequestersPids[usedNetworkType].remove(currentPid);
                 reassessPidDns(pid, true);
                 if (mNetRequestersPids[usedNetworkType].size() != 0) {
-                    if (DBG) log("not tearing down special network - " +
-                           "others still using it");
+                    if (VDBG) {
+                        log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
+                                " others still using it");
+                    }
                     return 1;
                 }
                 callTeardown = true;
             } else {
-                if (DBG) log("not a known feature - dropping");
+                if (DBG) {
+                    log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
+                            " not a known feature - dropping");
+                }
             }
         }
-        if (DBG) log("Doing network teardown");
+
         if (callTeardown) {
+            if (DBG) {
+                log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
+            }
             tracker.teardown();
             return 1;
         } else {
@@ -1592,7 +1611,7 @@
                 mInitialBroadcast = new Intent(intent);
             }
             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
-            if (DBG) {
+            if (VDBG) {
                 log("sendStickyBroadcast: action=" + intent.getAction());
             }
 
@@ -1604,7 +1623,7 @@
         if (delayMs <= 0) {
             sendStickyBroadcast(intent);
         } else {
-            if (DBG) {
+            if (VDBG) {
                 log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
                         + intent.getAction());
             }
@@ -1779,12 +1798,12 @@
                         }
                     }
                     if (resetDns) {
-                        if (DBG) log("resetting DNS cache for " + iface);
+                        if (VDBG) log("resetting DNS cache for " + iface);
                         try {
                             mNetd.flushInterfaceDnsCache(iface);
                         } catch (Exception e) {
                             // never crash - catch them all
-                            loge("Exception resetting dns cache: " + e);
+                            if (DBG) loge("Exception resetting dns cache: " + e);
                         }
                     }
                 }
@@ -1840,12 +1859,12 @@
                 // remove the default route unless somebody else has asked for it
                 String ifaceName = newLp.getInterfaceName();
                 if (TextUtils.isEmpty(ifaceName) == false && mAddedRoutes.contains(r) == false) {
-                    if (DBG) log("Removing " + r + " for interface " + ifaceName);
+                    if (VDBG) log("Removing " + r + " for interface " + ifaceName);
                     try {
                         mNetd.removeRoute(ifaceName, r);
                     } catch (Exception e) {
                         // never crash - catch them all
-                        loge("Exception trying to remove a route: " + e);
+                        if (VDBG) loge("Exception trying to remove a route: " + e);
                     }
                 }
             }
@@ -2059,7 +2078,7 @@
                 mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses));
                 mNetd.setDefaultInterfaceForDns(iface);
             } catch (Exception e) {
-                loge("exception setting default dns interface: " + e);
+                if (VDBG) loge("exception setting default dns interface: " + e);
             }
         }
         if (!domains.equals(SystemProperties.get("net.dns.search"))) {
@@ -2089,7 +2108,7 @@
                     mNetd.setDnsServersForInterface(p.getInterfaceName(),
                             NetworkUtils.makeStrings(dnses));
                 } catch (Exception e) {
-                    loge("exception setting dns servers: " + e);
+                    if (VDBG) loge("exception setting dns servers: " + e);
                 }
                 // set per-pid dns for attached secondary nets
                 List pids = mNetRequestersPids[netType];
@@ -2194,9 +2213,12 @@
                     int type = info.getType();
                     NetworkInfo.State state = info.getState();
 
-                    if (DBG) log("ConnectivityChange for " +
+                    if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
+                            (state == NetworkInfo.State.DISCONNECTED)) {
+                        log("ConnectivityChange for " +
                             info.getTypeName() + ": " +
                             state + "/" + info.getDetailedState());
+                    }
 
                     // Connectivity state changed:
                     // [31-13] Reserved for future use
@@ -2458,23 +2480,24 @@
     }
 
     private void handleInetConditionChange(int netType, int condition) {
-        if (DBG) {
-            log("Inet connectivity change, net=" +
-                    netType + ", condition=" + condition +
-                    ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
-        }
         if (mActiveDefaultNetwork == -1) {
-            if (DBG) log("no active default network - aborting");
+            if (DBG) log("handleInetConditionChange: no active default network - ignore");
             return;
         }
         if (mActiveDefaultNetwork != netType) {
-            if (DBG) log("given net not default - aborting");
+            if (DBG) log("handleInetConditionChange: net=" + netType +
+                            " != default=" + mActiveDefaultNetwork + " - ignore");
             return;
         }
+        if (VDBG) {
+            log("handleInetConditionChange: net=" +
+                    netType + ", condition=" + condition +
+                    ",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
+        }
         mDefaultInetCondition = condition;
         int delay;
         if (mInetConditionChangeInFlight == false) {
-            if (VDBG) log("starting a change hold");
+            if (VDBG) log("handleInetConditionChange: starting a change hold");
             // setup a new hold to debounce this
             if (mDefaultInetCondition > 50) {
                 delay = Settings.Secure.getInt(mContext.getContentResolver(),
@@ -2487,26 +2510,25 @@
             mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
                     mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
         } else {
-            // we've set the new condition, when this hold ends that will get
-            // picked up
-            if (VDBG) log("currently in hold - not setting new end evt");
+            // we've set the new condition, when this hold ends that will get picked up
+            if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
         }
     }
 
     private void handleInetConditionHoldEnd(int netType, int sequence) {
-        if (VDBG) {
-            log("Inet hold end, net=" + netType +
-                    ", condition =" + mDefaultInetCondition +
-                    ", published condition =" + mDefaultInetConditionPublished);
+        if (DBG) {
+            log("handleInetConditionHoldEnd: net=" + netType +
+                    ", condition=" + mDefaultInetCondition +
+                    ", published condition=" + mDefaultInetConditionPublished);
         }
         mInetConditionChangeInFlight = false;
 
         if (mActiveDefaultNetwork == -1) {
-            if (DBG) log("no active default network - aborting");
+            if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
             return;
         }
         if (mDefaultConnectionSequence != sequence) {
-            if (DBG) log("event hold for obsolete network - aborting");
+            if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
             return;
         }
         // TODO: Figure out why this optimization sometimes causes a
@@ -2518,7 +2540,7 @@
         //}
         NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
         if (networkInfo.isConnected() == false) {
-            if (DBG) log("default network not connected - aborting");
+            if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
             return;
         }
         mDefaultInetConditionPublished = mDefaultInetCondition;
@@ -2596,7 +2618,8 @@
             }
         }
         if (VDBG) log("changing default proxy to " + proxy);
-        if ((proxy == null && mGlobalProxy == null) || proxy.equals(mGlobalProxy)) return;
+
+        // global trumps default, if set, ignore this.
         if (mGlobalProxy != null) return;
         sendProxyBroadcast(proxy);
     }
diff --git a/services/java/com/android/server/NetworkManagementService.java b/services/java/com/android/server/NetworkManagementService.java
index 0cffb15..6fcf399 100644
--- a/services/java/com/android/server/NetworkManagementService.java
+++ b/services/java/com/android/server/NetworkManagementService.java
@@ -560,8 +560,10 @@
                     + e);
         }
 
-        for (String line : rsp) {
-            Log.v(TAG, "add route response is " + line);
+        if (DBG) {
+            for (String line : rsp) {
+                Log.v(TAG, "add route response is " + line);
+            }
         }
     }
 
diff --git a/services/java/com/android/server/PowerManagerService.java b/services/java/com/android/server/PowerManagerService.java
index 0934cd0..78dbbd6 100644
--- a/services/java/com/android/server/PowerManagerService.java
+++ b/services/java/com/android/server/PowerManagerService.java
@@ -79,6 +79,8 @@
     private static final String TAG = "PowerManagerService";
     static final String PARTIAL_NAME = "PowerManagerService";
 
+    static final boolean DEBUG_SCREEN_ON = false;
+
     private static final boolean LOG_PARTIAL_WL = false;
 
     // Indicates whether touch-down cycles should be logged as part of the
@@ -162,6 +164,8 @@
     private final int[] mBroadcastQueue = new int[] { -1, -1, -1 };
     private final int[] mBroadcastWhy = new int[3];
     private boolean mPreparingForScreenOn = false;
+    private boolean mSkippedScreenOn = false;
+    private boolean mInitialized = false;
     private int mPartialCount = 0;
     private int mPowerState;
     // mScreenOffReason can be WindowManagerPolicy.OFF_BECAUSE_OF_USER,
@@ -557,6 +561,10 @@
         nativeInit();
         synchronized (mLocks) {
             updateNativePowerStateLocked();
+            // We make sure to start out with the screen on due to user activity.
+            // (They did just boot their device, after all.)
+            forceUserActivityLocked();
+            mInitialized = true;
         }
     }
 
@@ -1123,7 +1131,8 @@
                     + " " + ((mNextTimeout-now)/1000) + "s from now");
             pw.println("  mDimScreen=" + mDimScreen
                     + " mStayOnConditions=" + mStayOnConditions
-                    + " mPreparingForScreenOn=" + mPreparingForScreenOn);
+                    + " mPreparingForScreenOn=" + mPreparingForScreenOn
+                    + " mSkippedScreenOn=" + mSkippedScreenOn);
             pw.println("  mScreenOffReason=" + mScreenOffReason
                     + " mUserState=" + mUserState);
             pw.println("  mBroadcastQueue={" + mBroadcastQueue[0] + ',' + mBroadcastQueue[1]
@@ -1312,8 +1321,23 @@
         }
     }
 
-    private void sendNotificationLocked(boolean on, int why)
-    {
+    private void sendNotificationLocked(boolean on, int why) {
+        if (!mInitialized) {
+            // No notifications sent until first initialization is done.
+            // This is so that when we are moving from our initial state
+            // which looks like the screen was off to it being on, we do not
+            // go through the process of waiting for the higher-level user
+            // space to be ready before turning up the display brightness.
+            // (And also do not send needless broadcasts about the screen.)
+            return;
+        }
+
+        if (DEBUG_SCREEN_ON) {
+            RuntimeException here = new RuntimeException("here");
+            here.fillInStackTrace();
+            Slog.i(TAG, "sendNotificationLocked: " + on, here);
+        }
+
         if (!on) {
             mStillNeedSleepNotification = false;
         }
@@ -1360,7 +1384,9 @@
 
         // The broadcast queue has changed; make sure the screen is on if it
         // is now possible for it to be.
-        updateNativePowerStateLocked();
+        if (mSkippedScreenOn) {
+            updateLightsLocked(mPowerState, SCREEN_ON_BIT);
+        }
 
         // Now send the message.
         if (index >= 0) {
@@ -1380,7 +1406,7 @@
                     synchronized (mLocks) {
                         if (mPreparingForScreenOn) {
                             mPreparingForScreenOn = false;
-                            updateNativePowerStateLocked();
+                            updateLightsLocked(mPowerState, SCREEN_ON_BIT);
                             EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP,
                                     4, mBroadcastWakeLock.mCount);
                             mBroadcastWakeLock.release();
@@ -1453,7 +1479,7 @@
                         synchronized (mLocks) {
                             EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3,
                                     mBroadcastWakeLock.mCount);
-                            updateNativePowerStateLocked();
+                            updateLightsLocked(mPowerState, SCREEN_ON_BIT);
                             mBroadcastWakeLock.release();
                         }
                     }
@@ -1646,6 +1672,11 @@
         };
 
     private int setScreenStateLocked(boolean on) {
+        if (DEBUG_SCREEN_ON) {
+            RuntimeException e = new RuntimeException("here");
+            e.fillInStackTrace();
+            Slog.i(TAG, "Set screen state: " + on, e);
+        }
         int err = Power.setScreenState(on);
         if (err == 0) {
             mLastScreenOnTime = (on ? SystemClock.elapsedRealtime() : 0);
@@ -1696,7 +1727,7 @@
             } else {
                 newState &= ~BATTERY_LOW_BIT;
             }
-            if (newState == mPowerState) {
+            if (newState == mPowerState && mInitialized) {
                 return;
             }
 
@@ -1722,10 +1753,7 @@
                          + " newBatteryLow=" + ((newState & BATTERY_LOW_BIT) != 0));
             }
 
-            if (mPowerState != newState) {
-                updateLightsLocked(newState, 0);
-                mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
-            }
+            final boolean stateChanged = mPowerState != newState;
 
             if (oldScreenOn != newScreenOn) {
                 if (newScreenOn) {
@@ -1777,10 +1805,24 @@
                     EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, reason,
                             mTotalTouchDownTime, mTouchCycles);
                     if (err == 0) {
-                        mPowerState |= SCREEN_ON_BIT;
                         sendNotificationLocked(true, -1);
+                        // Update the lights *after* taking care of turning the
+                        // screen on, so we do this after our notifications are
+                        // enqueued and thus will delay turning on the screen light
+                        // until the windows are correctly displayed.
+                        if (stateChanged) {
+                            updateLightsLocked(newState, 0);
+                        }
+                        mPowerState |= SCREEN_ON_BIT;
                     }
+
                 } else {
+                    // Update the lights *before* taking care of turning the
+                    // screen off, so we can initiate any animations that are desired.
+                    if (stateChanged) {
+                        updateLightsLocked(newState, 0);
+                    }
+
                     // cancel light sensor task
                     mHandler.removeCallbacks(mAutoBrightnessTask);
                     mLightSensorPendingDecrease = false;
@@ -1803,30 +1845,18 @@
                         mLastTouchDown = 0;
                     }
                 }
+            } else if (stateChanged) {
+                // Screen on/off didn't change, but lights may have.
+                updateLightsLocked(newState, 0);
             }
-            
+
+            mPowerState = (mPowerState & ~LIGHTS_MASK) | (newState & LIGHTS_MASK);
+
             updateNativePowerStateLocked();
         }
     }
-    
+
     private void updateNativePowerStateLocked() {
-        if ((mPowerState & SCREEN_ON_BIT) != 0) {
-            // Don't turn screen on until we know we are really ready to.
-            // This is to avoid letting the screen go on before things like the
-            // lock screen have been displayed.
-            if (mPreparingForScreenOn) {
-                // Currently waiting for confirmation from the policy that it
-                // is okay to turn on the screen.  Don't allow the screen to go
-                // on until that is done.
-                return;
-            }
-            for (int i=0; i<mBroadcastQueue.length; i++) {
-                if (mBroadcastQueue[i] == 1) {
-                    // A screen on is currently enqueued.
-                    return;
-                }
-            }
-        }
         nativeSetPowerState(
                 (mPowerState & SCREEN_ON_BIT) != 0,
                 (mPowerState & SCREEN_BRIGHT) == SCREEN_BRIGHT);
@@ -1852,8 +1882,43 @@
                 mBatteryService.getBatteryLevel() <= Power.LOW_BATTERY_THRESHOLD);
     }
 
+    private boolean shouldDeferScreenOnLocked() {
+        if (mPreparingForScreenOn) {
+            // Currently waiting for confirmation from the policy that it
+            // is okay to turn on the screen.  Don't allow the screen to go
+            // on until that is done.
+            if (DEBUG_SCREEN_ON) Slog.i(TAG,
+                    "updateLights: delaying screen on due to mPreparingForScreenOn");
+            return true;
+        } else {
+            // If there is a screen-on command in the notification queue, we
+            // can't turn the screen on until it has been processed (and we
+            // have set mPreparingForScreenOn) or it has been dropped.
+            for (int i=0; i<mBroadcastQueue.length; i++) {
+                if (mBroadcastQueue[i] == 1) {
+                    if (DEBUG_SCREEN_ON) Slog.i(TAG,
+                            "updateLights: delaying screen on due to notification queue");
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
     private void updateLightsLocked(int newState, int forceState) {
         final int oldState = mPowerState;
+
+        // If the screen is not currently on, we will want to delay actually
+        // turning the lights on if we are still getting the UI put up.
+        if ((oldState&SCREEN_ON_BIT) == 0 || mSkippedScreenOn) {
+            // Don't turn screen on until we know we are really ready to.
+            // This is to avoid letting the screen go on before things like the
+            // lock screen have been displayed.
+            if ((mSkippedScreenOn=shouldDeferScreenOnLocked())) {
+                newState &= ~(SCREEN_ON_BIT|SCREEN_BRIGHT_BIT);
+            }
+        }
+
         if ((newState & SCREEN_ON_BIT) != 0) {
             // Only turn on the buttons or keyboard if the screen is also on.
             // We should never see the buttons on but not the screen.
@@ -1960,6 +2025,13 @@
             }
             mScreenBrightness.setTargetLocked(brightness, steps,
                     INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
+            if (DEBUG_SCREEN_ON) {
+                RuntimeException e = new RuntimeException("here");
+                e.fillInStackTrace();
+                Slog.i(TAG, "Setting screen brightness: " + brightness, e);
+                mScreenBrightness.setTargetLocked(brightness, steps,
+                        INITIAL_SCREEN_BRIGHTNESS, nominalCurrentValue);
+            }
         }
 
         if (mSpew) {
diff --git a/services/java/com/android/server/TelephonyRegistry.java b/services/java/com/android/server/TelephonyRegistry.java
index bc256ed..8c8e725 100644
--- a/services/java/com/android/server/TelephonyRegistry.java
+++ b/services/java/com/android/server/TelephonyRegistry.java
@@ -53,6 +53,7 @@
  */
 class TelephonyRegistry extends ITelephonyRegistry.Stub {
     private static final String TAG = "TelephonyRegistry";
+    private static final boolean DBG = false;
 
     private static class Record {
         String pkgForDebug;
@@ -387,9 +388,11 @@
         if (!checkNotifyPermission("notifyDataConnection()" )) {
             return;
         }
-        Slog.i(TAG, "notifyDataConnection: state=" + state + " isDataConnectivityPossible="
+        if (DBG) {
+            Slog.i(TAG, "notifyDataConnection: state=" + state + " isDataConnectivityPossible="
                 + isDataConnectivityPossible + " reason='" + reason
                 + "' apn='" + apn + "' apnType=" + apnType + " networkType=" + networkType);
+        }
         synchronized (mRecords) {
             boolean modified = false;
             if (state == TelephonyManager.DATA_CONNECTED) {
@@ -421,8 +424,10 @@
                 modified = true;
             }
             if (modified) {
-                Slog.d(TAG, "onDataConnectionStateChanged(" + mDataConnectionState
+                if (DBG) {
+                    Slog.d(TAG, "onDataConnectionStateChanged(" + mDataConnectionState
                         + ", " + mDataConnectionNetworkType + ")");
+                }
                 for (Record r : mRecords) {
                     if ((r.events & PhoneStateListener.LISTEN_DATA_CONNECTION_STATE) != 0) {
                         try {
@@ -639,7 +644,7 @@
         }
         String msg = "Modify Phone State Permission Denial: " + method + " from pid="
                 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid();
-        Slog.w(TAG, msg);
+        if (DBG) Slog.w(TAG, msg);
         return false;
     }
 
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index 41af137..ed960d6 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -1631,8 +1631,8 @@
         }
         if (app.conProviders.size() > 0) {
             for (ContentProviderRecord cpr : app.conProviders.keySet()) {
-                if (cpr.app != null && cpr.app.lruSeq != mLruSeq) {
-                    updateLruProcessInternalLocked(cpr.app, oomAdj,
+                if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
+                    updateLruProcessInternalLocked(cpr.proc, oomAdj,
                             updateActivityTime, i+1);
                 }
             }
@@ -3373,7 +3373,24 @@
         for (i=0; i<N; i++) {
             bringDownServiceLocked(services.get(i), true);
         }
-        
+
+        ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
+        for (ContentProviderRecord provider : mProvidersByClass.values()) {
+            if (provider.info.packageName.equals(name)
+                    && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
+                if (!doit) {
+                    return true;
+                }
+                didSomething = true;
+                providers.add(provider);
+            }
+        }
+
+        N = providers.size();
+        for (i=0; i<N; i++) {
+            removeDyingProviderLocked(null, providers.get(i));
+        }
+
         if (doit) {
             if (purgeCache) {
                 AttributeCache ac = AttributeCache.instance();
@@ -5485,7 +5502,7 @@
                 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
                 ContentProviderRecord cpr = mProvidersByClass.get(comp);
                 if (cpr == null) {
-                    cpr = new ContentProviderRecord(cpi, app.info);
+                    cpr = new ContentProviderRecord(cpi, app.info, comp);
                     mProvidersByClass.put(comp, cpr);
                 }
                 app.pubProviders.put(cpi.name, cpr);
@@ -5643,25 +5660,25 @@
                 // return it right away.
                 final boolean countChanged = incProviderCount(r, cpr);
                 if (countChanged) {
-                    if (cpr.app != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
+                    if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
                         // If this is a perceptible app accessing the provider,
                         // make sure to count it as being accessed and thus
                         // back up on the LRU list.  This is good because
                         // content providers are often expensive to start.
-                        updateLruProcessLocked(cpr.app, false, true);
+                        updateLruProcessLocked(cpr.proc, false, true);
                     }
                 }
 
-                if (cpr.app != null) {
+                if (cpr.proc != null) {
                     if (false) {
                         if (cpr.name.flattenToShortString().equals(
                                 "com.android.providers.calendar/.CalendarProvider2")) {
                             Slog.v(TAG, "****************** KILLING "
                                 + cpr.name.flattenToShortString());
-                            Process.killProcess(cpr.app.pid);
+                            Process.killProcess(cpr.proc.pid);
                         }
                     }
-                    boolean success = updateOomAdjLocked(cpr.app);
+                    boolean success = updateOomAdjLocked(cpr.proc);
                     if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
                     // NOTE: there is still a race here where a signal could be
                     // pending on the process even though we managed to update its
@@ -5676,7 +5693,7 @@
                                 "Existing provider " + cpr.name.flattenToShortString()
                                 + " is crashing; detaching " + r);
                         boolean lastRef = decProviderCount(r, cpr);
-                        appDiedLocked(cpr.app, cpr.app.pid, cpr.app.thread);
+                        appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
                         if (!lastRef) {
                             // This wasn't the last ref our process had on
                             // the provider...  we have now been killed, bail.
@@ -5729,7 +5746,7 @@
                                     + cpi.name);
                             return null;
                         }
-                        cpr = new ContentProviderRecord(cpi, ai);
+                        cpr = new ContentProviderRecord(cpi, ai, comp);
                     } catch (RemoteException ex) {
                         // pm is in same process, this will never happen.
                     }
@@ -5864,7 +5881,7 @@
             //update content provider record entry info
             ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
             ContentProviderRecord localCpr = mProvidersByClass.get(comp);
-            if (localCpr.app == r) {
+            if (localCpr.proc == r) {
                 //should not happen. taken care of as a local provider
                 Slog.w(TAG, "removeContentProvider called on local provider: "
                         + cpr.info.name + " in process " + r.processName);
@@ -5940,7 +5957,7 @@
                     }
                     synchronized (dst) {
                         dst.provider = src.provider;
-                        dst.app = r;
+                        dst.proc = r;
                         dst.notifyAll();
                     }
                     updateOomAdjLocked(r);
@@ -8706,9 +8723,9 @@
                     r.dump(pw, "      ");
                 } else {
                     pw.print("  * "); pw.print(e.getKey().flattenToShortString());
-                    if (r.app != null) {
+                    if (r.proc != null) {
                         pw.println(":");
-                        pw.print("      "); pw.println(r.app);
+                        pw.print("      "); pw.println(r.proc);
                     } else {
                         pw.println();
                     }
@@ -9440,7 +9457,7 @@
             cpr.notifyAll();
         }
         
-        mProvidersByClass.remove(cpr.info.name);
+        mProvidersByClass.remove(cpr.name);
         String names[] = cpr.info.authority.split(";");
         for (int j = 0; j < names.length; j++) {
             mProvidersByName.remove(names[j]);
@@ -9454,9 +9471,10 @@
                     && capp.pid != MY_PID) {
                 Slog.i(TAG, "Kill " + capp.processName
                         + " (pid " + capp.pid + "): provider " + cpr.info.name
-                        + " in dying process " + proc.processName);
+                        + " in dying process " + (proc != null ? proc.processName : "??"));
                 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
-                        capp.processName, capp.setAdj, "dying provider " + proc.processName);
+                        capp.processName, capp.setAdj, "dying provider "
+                                + cpr.name.toShortString());
                 Process.killProcessQuiet(capp.pid);
             }
         }
@@ -9515,7 +9533,7 @@
             while (it.hasNext()) {
                 ContentProviderRecord cpr = it.next();
                 cpr.provider = null;
-                cpr.app = null;
+                cpr.proc = null;
 
                 // See if someone is waiting for this provider...  in which
                 // case we don't remove it, but just let it restart.
diff --git a/services/java/com/android/server/am/ContentProviderRecord.java b/services/java/com/android/server/am/ContentProviderRecord.java
index db235ee..9c55597 100644
--- a/services/java/com/android/server/am/ContentProviderRecord.java
+++ b/services/java/com/android/server/am/ContentProviderRecord.java
@@ -32,15 +32,15 @@
     final ApplicationInfo appInfo;
     final ComponentName name;
     int externals;     // number of non-framework processes supported by this provider
-    ProcessRecord app; // if non-null, hosting application
+    ProcessRecord proc; // if non-null, hosting process.
     ProcessRecord launchingApp; // if non-null, waiting for this app to be launched.
     String stringName;
     
-    public ContentProviderRecord(ProviderInfo _info, ApplicationInfo ai) {
+    public ContentProviderRecord(ProviderInfo _info, ApplicationInfo ai, ComponentName _name) {
         super(_info);
         uid = ai.uid;
         appInfo = ai;
-        name = new ComponentName(_info.packageName, _info.name);
+        name = _name;
         noReleaseNeeded = uid == 0 || uid == Process.SYSTEM_UID;
     }
 
@@ -61,7 +61,7 @@
         pw.print(prefix); pw.print("package=");
                 pw.print(info.applicationInfo.packageName);
                 pw.print(" process="); pw.println(info.processName);
-        pw.print(prefix); pw.print("app="); pw.println(app);
+        pw.print(prefix); pw.print("proc="); pw.println(proc);
         if (launchingApp != null) {
             pw.print(prefix); pw.print("launchingApp="); pw.println(launchingApp);
         }
diff --git a/services/java/com/android/server/connectivity/Tethering.java b/services/java/com/android/server/connectivity/Tethering.java
index 5286824..10f6d2c 100644
--- a/services/java/com/android/server/connectivity/Tethering.java
+++ b/services/java/com/android/server/connectivity/Tethering.java
@@ -71,7 +71,8 @@
 
     private Context mContext;
     private final static String TAG = "Tethering";
-    private final static boolean DEBUG = true;
+    private final static boolean DBG = true;
+    private final static boolean VDBG = false;
 
     // TODO - remove both of these - should be part of interface inspection/selection stuff
     private String[] mTetherableUsbRegexs;
@@ -178,7 +179,7 @@
     }
 
     public void interfaceStatusChanged(String iface, boolean up) {
-        if (DEBUG) Log.d(TAG, "interfaceStatusChanged " + iface + ", " + up);
+        if (VDBG) Log.d(TAG, "interfaceStatusChanged " + iface + ", " + up);
         boolean found = false;
         boolean usb = false;
         if (isWifi(iface)) {
@@ -203,7 +204,7 @@
                 if (isUsb(iface)) {
                     // ignore usb0 down after enabling RNDIS
                     // we will handle disconnect in interfaceRemoved instead
-                    Log.d(TAG, "ignoring interface down for " + iface);
+                    if (VDBG) Log.d(TAG, "ignoring interface down for " + iface);
                 } else if (sm != null) {
                     sm.sendMessage(TetherInterfaceSM.CMD_INTERFACE_DOWN);
                     mIfaces.remove(iface);
@@ -213,7 +214,7 @@
     }
 
     public void interfaceLinkStateChanged(String iface, boolean up) {
-        if (DEBUG) Log.d(TAG, "interfaceLinkStateChanged " + iface + ", " + up);
+        if (VDBG) Log.d(TAG, "interfaceLinkStateChanged " + iface + ", " + up);
         interfaceStatusChanged(iface, up);
     }
 
@@ -239,7 +240,7 @@
     }
 
     public void interfaceAdded(String iface) {
-        if (DEBUG) Log.d(TAG, "interfaceAdded " + iface);
+        if (VDBG) Log.d(TAG, "interfaceAdded " + iface);
         boolean found = false;
         boolean usb = false;
         if (isWifi(iface)) {
@@ -253,29 +254,29 @@
             found = true;
         }
         if (found == false) {
-            if (DEBUG) Log.d(TAG, iface + " is not a tetherable iface, ignoring");
+            if (VDBG) Log.d(TAG, iface + " is not a tetherable iface, ignoring");
             return;
         }
 
         synchronized (mIfaces) {
             TetherInterfaceSM sm = mIfaces.get(iface);
             if (sm != null) {
-                if (DEBUG) Log.d(TAG, "active iface (" + iface + ") reported as added, ignoring");
+                if (VDBG) Log.d(TAG, "active iface (" + iface + ") reported as added, ignoring");
                 return;
             }
             sm = new TetherInterfaceSM(iface, mLooper, usb);
             mIfaces.put(iface, sm);
             sm.start();
         }
-        if (DEBUG) Log.d(TAG, "interfaceAdded :" + iface);
+        if (VDBG) Log.d(TAG, "interfaceAdded :" + iface);
     }
 
     public void interfaceRemoved(String iface) {
-        if (DEBUG) Log.d(TAG, "interfaceRemoved " + iface);
+        if (VDBG) Log.d(TAG, "interfaceRemoved " + iface);
         synchronized (mIfaces) {
             TetherInterfaceSM sm = mIfaces.get(iface);
             if (sm == null) {
-                if (DEBUG) {
+                if (VDBG) {
                     Log.e(TAG, "attempting to remove unknown iface (" + iface + "), ignoring");
                 }
                 return;
@@ -288,7 +289,7 @@
     public void limitReached(String limitName, String iface) {}
 
     public int tether(String iface) {
-        Log.d(TAG, "Tethering " + iface);
+        if (DBG) Log.d(TAG, "Tethering " + iface);
         TetherInterfaceSM sm = null;
         synchronized (mIfaces) {
             sm = mIfaces.get(iface);
@@ -306,7 +307,7 @@
     }
 
     public int untether(String iface) {
-        Log.d(TAG, "Untethering " + iface);
+        if (DBG) Log.d(TAG, "Untethering " + iface);
         TetherInterfaceSM sm = null;
         synchronized (mIfaces) {
             sm = mIfaces.get(iface);
@@ -383,7 +384,7 @@
         broadcast.putStringArrayListExtra(ConnectivityManager.EXTRA_ERRORED_TETHER,
                 erroredList);
         mContext.sendStickyBroadcast(broadcast);
-        if (DEBUG) {
+        if (VDBG) {
             Log.d(TAG, "sendTetherStateChangedBroadcast " + availableList.size() + ", " +
                     activeList.size() + ", " + erroredList.size());
         }
@@ -468,14 +469,14 @@
                     mUsbTetherRequested = false;
                 }
             } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
-                if (DEBUG) Log.d(TAG, "Tethering got CONNECTIVITY_ACTION");
+                if (VDBG) Log.d(TAG, "Tethering got CONNECTIVITY_ACTION");
                 mTetherMasterSM.sendMessage(TetherMasterSM.CMD_UPSTREAM_CHANGED);
             }
         }
     }
 
     private void tetherUsb(boolean enable) {
-        if (DEBUG) Log.d(TAG, "tetherUsb " + enable);
+        if (VDBG) Log.d(TAG, "tetherUsb " + enable);
 
         String[] ifaces = new String[0];
         try {
@@ -497,7 +498,7 @@
 
     // configured when we start tethering and unconfig'd on error or conclusion
     private boolean configureUsbIface(boolean enabled) {
-        if (DEBUG) Log.d(TAG, "configureUsbIface(" + enabled + ")");
+        if (VDBG) Log.d(TAG, "configureUsbIface(" + enabled + ")");
 
         // toggle the USB interfaces
         String[] ifaces = new String[0];
@@ -547,7 +548,7 @@
     }
 
     public int setUsbTethering(boolean enable) {
-        if (DEBUG) Log.d(TAG, "setUsbTethering(" + enable + ")");
+        if (VDBG) Log.d(TAG, "setUsbTethering(" + enable + ")");
         UsbManager usbManager = (UsbManager)mContext.getSystemService(Context.USB_SERVICE);
 
         synchronized (this) {
@@ -808,7 +809,7 @@
 
             @Override
             public boolean processMessage(Message message) {
-                if (DEBUG) Log.d(TAG, "InitialState.processMessage what=" + message.what);
+                if (VDBG) Log.d(TAG, "InitialState.processMessage what=" + message.what);
                 boolean retValue = true;
                 switch (message.what) {
                     case CMD_TETHER_REQUESTED:
@@ -849,7 +850,7 @@
             }
             @Override
             public boolean processMessage(Message message) {
-                if (DEBUG) Log.d(TAG, "StartingState.processMessage what=" + message.what);
+                if (VDBG) Log.d(TAG, "StartingState.processMessage what=" + message.what);
                 boolean retValue = true;
                 switch (message.what) {
                     // maybe a parent class?
@@ -897,14 +898,14 @@
                     transitionTo(mInitialState);
                     return;
                 }
-                if (DEBUG) Log.d(TAG, "Tethered " + mIfaceName);
+                if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
                 setAvailable(false);
                 setTethered(true);
                 sendTetherStateChangedBroadcast();
             }
             @Override
             public boolean processMessage(Message message) {
-                if (DEBUG) Log.d(TAG, "TetheredState.processMessage what=" + message.what);
+                if (VDBG) Log.d(TAG, "TetheredState.processMessage what=" + message.what);
                 boolean retValue = true;
                 boolean error = false;
                 switch (message.what) {
@@ -944,14 +945,14 @@
                         } else if (message.what == CMD_INTERFACE_DOWN) {
                             transitionTo(mUnavailableState);
                         }
-                        if (DEBUG) Log.d(TAG, "Untethered " + mIfaceName);
+                        if (DBG) Log.d(TAG, "Untethered " + mIfaceName);
                         break;
                     case CMD_TETHER_CONNECTION_CHANGED:
                         String newUpstreamIfaceName = (String)(message.obj);
                         if ((mMyUpstreamIfaceName == null && newUpstreamIfaceName == null) ||
                                 (mMyUpstreamIfaceName != null &&
                                 mMyUpstreamIfaceName.equals(newUpstreamIfaceName))) {
-                            if (DEBUG) Log.d(TAG, "Connection changed noop - dropping");
+                            if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
                             break;
                         }
                         if (mMyUpstreamIfaceName != null) {
@@ -1018,7 +1019,7 @@
                                     ConnectivityManager.TETHER_ERROR_MASTER_ERROR);
                             break;
                         }
-                        if (DEBUG) Log.d(TAG, "Tether lost upstream connection " + mIfaceName);
+                        if (VDBG) Log.d(TAG, "Tether lost upstream connection " + mIfaceName);
                         sendTetherStateChangedBroadcast();
                         if (mUsb) {
                             if (!Tethering.this.configureUsbIface(false)) {
@@ -1248,7 +1249,7 @@
                     }
                 }
 
-                if (DEBUG) {
+                if (VDBG) {
                     Log.d(TAG, "chooseUpstreamType(" + tryCell + "), preferredApn ="
                             + mPreferredUpstreamMobileApn + ", got type=" + upType);
                 }
@@ -1280,7 +1281,7 @@
             }
 
             protected void notifyTetheredOfNewUpstreamIface(String ifaceName) {
-                if (DEBUG) Log.d(TAG, "notifying tethered with iface =" + ifaceName);
+                if (VDBG) Log.d(TAG, "notifying tethered with iface =" + ifaceName);
                 mUpstreamIfaceName = ifaceName;
                 for (Object o : mNotifyList) {
                     TetherInterfaceSM sm = (TetherInterfaceSM)o;
@@ -1296,19 +1297,19 @@
             }
             @Override
             public boolean processMessage(Message message) {
-                if (DEBUG) Log.d(TAG, "MasterInitialState.processMessage what=" + message.what);
+                if (VDBG) Log.d(TAG, "MasterInitialState.processMessage what=" + message.what);
                 boolean retValue = true;
                 switch (message.what) {
                     case CMD_TETHER_MODE_REQUESTED:
                         checkDunRequired();
                         TetherInterfaceSM who = (TetherInterfaceSM)message.obj;
-                        if (DEBUG) Log.d(TAG, "Tether Mode requested by " + who.toString());
+                        if (VDBG) Log.d(TAG, "Tether Mode requested by " + who.toString());
                         mNotifyList.add(who);
                         transitionTo(mTetherModeAliveState);
                         break;
                     case CMD_TETHER_MODE_UNREQUESTED:
                         who = (TetherInterfaceSM)message.obj;
-                        if (DEBUG) Log.d(TAG, "Tether Mode unrequested by " + who.toString());
+                        if (VDBG) Log.d(TAG, "Tether Mode unrequested by " + who.toString());
                         int index = mNotifyList.indexOf(who);
                         if (index != -1) {
                             mNotifyList.remove(who);
@@ -1339,7 +1340,7 @@
             }
             @Override
             public boolean processMessage(Message message) {
-                if (DEBUG) Log.d(TAG, "TetherModeAliveState.processMessage what=" + message.what);
+                if (VDBG) Log.d(TAG, "TetherModeAliveState.processMessage what=" + message.what);
                 boolean retValue = true;
                 switch (message.what) {
                     case CMD_TETHER_MODE_REQUESTED:
@@ -1368,7 +1369,7 @@
                         // make sure we're still using a requested connection - may have found
                         // wifi or something since then.
                         if (mCurrentConnectionSequence == message.arg1) {
-                            if (DEBUG) {
+                            if (VDBG) {
                                 Log.d(TAG, "renewing mobile connection - requeuing for another " +
                                         CELL_CONNECTION_RENEW_MS + "ms");
                             }
diff --git a/services/java/com/android/server/pm/PackageManagerService.java b/services/java/com/android/server/pm/PackageManagerService.java
index 9ebdd52..105e603 100644
--- a/services/java/com/android/server/pm/PackageManagerService.java
+++ b/services/java/com/android/server/pm/PackageManagerService.java
@@ -4849,15 +4849,14 @@
     }
 
     @Override
-    public void verifyPendingInstall(int id, boolean verified, String message)
+    public void verifyPendingInstall(int id, int verificationCode)
             throws RemoteException {
         mContext.enforceCallingOrSelfPermission(
                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, null);
 
         final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
         msg.arg1 = id;
-        msg.arg2 = verified ? 1 : 0;
-        msg.obj = message;
+        msg.arg2 = verificationCode;
         mHandler.sendMessage(msg);
     }
 
diff --git a/services/java/com/android/server/wm/DragState.java b/services/java/com/android/server/wm/DragState.java
index dd440bf..f2e7485 100644
--- a/services/java/com/android/server/wm/DragState.java
+++ b/services/java/com/android/server/wm/DragState.java
@@ -125,6 +125,12 @@
             mDragWindowHandle.frameTop = 0;
             mDragWindowHandle.frameRight = mService.mCurDisplayWidth;
             mDragWindowHandle.frameBottom = mService.mCurDisplayHeight;
+
+            // Pause rotations before a drag.
+            if (WindowManagerService.DEBUG_ORIENTATION) {
+                Slog.d(WindowManagerService.TAG, "Pausing rotation during drag");
+            }
+            mService.pauseRotationLocked();
         }
     }
 
@@ -142,6 +148,12 @@
 
             mDragWindowHandle = null;
             mDragApplicationHandle = null;
+
+            // Resume rotations after a drag.
+            if (WindowManagerService.DEBUG_ORIENTATION) {
+                Slog.d(WindowManagerService.TAG, "Resuming rotation after drag");
+            }
+            mService.resumeRotationLocked();
         }
     }
 
@@ -257,13 +269,6 @@
         // free our resources and drop all the object references
         mService.mDragState.reset();
         mService.mDragState = null;
-
-        if (WindowManagerService.DEBUG_ORIENTATION) Slog.d(WindowManagerService.TAG, "Performing post-drag rotation");
-        boolean changed = mService.setRotationUncheckedLocked(
-                WindowManagerPolicy.USE_LAST_ROTATION, 0, false);
-        if (changed) {
-            mService.mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
-        }
     }
 
     void notifyMoveLw(float x, float y) {
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index ff75cfd..02b246a 100644
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -427,14 +427,11 @@
     int mAppDisplayWidth = 0;
     int mAppDisplayHeight = 0;
     int mRotation = 0;
-    int mRequestedRotation = 0;
     int mForcedAppOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
     boolean mAltOrientation = false;
-    int mLastRotationFlags;
     ArrayList<IRotationWatcher> mRotationWatchers
             = new ArrayList<IRotationWatcher>();
-    int mDeferredRotation;
-    int mDeferredRotationAnimFlags;
+    int mDeferredRotationPauseCount;
 
     boolean mLayoutNeeded = true;
     boolean mAnimationPending = false;
@@ -3414,9 +3411,7 @@
                 //send a message to Policy indicating orientation change to take
                 //action like disabling/enabling sensors etc.,
                 mPolicy.setCurrentOrientationLw(req);
-                if (setRotationUncheckedLocked(WindowManagerPolicy.USE_LAST_ROTATION,
-                        mLastRotationFlags | Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE,
-                        inTransaction)) {
+                if (updateRotationUncheckedLocked(inTransaction)) {
                     changed = true;
                 }
             }
@@ -4823,8 +4818,7 @@
         mPolicy.enableScreenAfterBoot();
 
         // Make sure the last requested orientation has been applied.
-        setRotationUnchecked(WindowManagerPolicy.USE_LAST_ROTATION, false,
-                mLastRotationFlags | Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
+        updateRotationUnchecked(false);
     }
 
     public void showBootMessage(final CharSequence msg, final boolean always) {
@@ -5043,6 +5037,10 @@
         return bm;
     }
 
+    /**
+     * Freeze rotation changes.  (Enable "rotation lock".)
+     * Persists across reboots.
+     */
     public void freezeRotation() {
         if (!checkCallingPermission(android.Manifest.permission.SET_ORIENTATION,
                 "freezeRotation()")) {
@@ -5052,9 +5050,13 @@
         if (DEBUG_ORIENTATION) Slog.v(TAG, "freezeRotation: mRotation=" + mRotation);
 
         mPolicy.setUserRotationMode(WindowManagerPolicy.USER_ROTATION_LOCKED, mRotation);
-        setRotationUnchecked(WindowManagerPolicy.USE_LAST_ROTATION, false, 0);
+        updateRotationUnchecked(false);
     }
 
+    /**
+     * Thaw rotation changes.  (Disable "rotation lock".)
+     * Persists across reboots.
+     */
     public void thawRotation() {
         if (!checkCallingPermission(android.Manifest.permission.SET_ORIENTATION,
                 "thawRotation()")) {
@@ -5064,30 +5066,56 @@
         if (DEBUG_ORIENTATION) Slog.v(TAG, "thawRotation: mRotation=" + mRotation);
 
         mPolicy.setUserRotationMode(WindowManagerPolicy.USER_ROTATION_FREE, 777); // rot not used
-        setRotationUnchecked(WindowManagerPolicy.USE_LAST_ROTATION, false, 0);
+        updateRotationUnchecked(false);
     }
 
-    public void setRotation(int rotation,
-            boolean alwaysSendConfiguration, int animFlags) {
-        if (!checkCallingPermission(android.Manifest.permission.SET_ORIENTATION,
-                "setRotation()")) {
-            throw new SecurityException("Requires SET_ORIENTATION permission");
+    /**
+     * Recalculate the current rotation.
+     *
+     * Called by the window manager policy whenever the state of the system changes
+     * such that the current rotation might need to be updated, such as when the
+     * device is docked or rotated into a new posture.
+     */
+    public void updateRotation(boolean alwaysSendConfiguration) {
+        updateRotationUnchecked(alwaysSendConfiguration);
+    }
+
+    /**
+     * Temporarily pauses rotation changes until resumed.
+     *
+     * This can be used to prevent rotation changes from occurring while the user is
+     * performing certain operations, such as drag and drop.
+     *
+     * This call nests and must be matched by an equal number of calls to {@link #resumeRotation}.
+     */
+    void pauseRotationLocked() {
+        mDeferredRotationPauseCount += 1;
+    }
+
+    /**
+     * Resumes normal rotation changes after being paused.
+     */
+    void resumeRotationLocked() {
+        if (mDeferredRotationPauseCount > 0) {
+            mDeferredRotationPauseCount -= 1;
+            if (mDeferredRotationPauseCount == 0) {
+                boolean changed = updateRotationUncheckedLocked(false);
+                if (changed) {
+                    mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
+                }
+            }
         }
-
-        setRotationUnchecked(rotation, alwaysSendConfiguration, animFlags);
     }
 
-    public void setRotationUnchecked(int rotation,
-            boolean alwaysSendConfiguration, int animFlags) {
-        if(DEBUG_ORIENTATION) Slog.v(TAG,
-                   "setRotationUnchecked(rotation=" + rotation +
-                   " alwaysSendConfiguration=" + alwaysSendConfiguration +
-                   " animFlags=" + animFlags);
+    public void updateRotationUnchecked(
+            boolean alwaysSendConfiguration) {
+        if(DEBUG_ORIENTATION) Slog.v(TAG, "updateRotationUnchecked("
+                   + "alwaysSendConfiguration=" + alwaysSendConfiguration + ")");
 
         long origId = Binder.clearCallingIdentity();
         boolean changed;
         synchronized(mWindowMap) {
-            changed = setRotationUncheckedLocked(rotation, animFlags, false);
+            changed = updateRotationUncheckedLocked(false);
         }
 
         if (changed || alwaysSendConfiguration) {
@@ -5098,152 +5126,113 @@
     }
 
     /**
-     * Apply a new rotation to the screen, respecting the requests of
-     * applications.  Use WindowManagerPolicy.USE_LAST_ROTATION to simply
-     * re-evaluate the desired rotation.
-     * 
-     * Returns null if the rotation has been changed.  In this case YOU
-     * MUST CALL setNewConfiguration() TO UNFREEZE THE SCREEN.
+     * Updates the current rotation.
+     *
+     * Returns true if the rotation has been changed.  In this case YOU
+     * MUST CALL sendNewConfiguration() TO UNFREEZE THE SCREEN.
      */
-    public boolean setRotationUncheckedLocked(int rotation, int animFlags, boolean inTransaction) {
-        if (mDragState != null
-                || (mScreenRotationAnimation != null && mScreenRotationAnimation.isAnimating())) {
-            // Potential rotation during a drag or while waiting for a previous orientation
-            // change to finish (rotation animation will be dismissed).
-            // Don't do the rotation now, but make a note to perform the rotation later.
-            if (DEBUG_ORIENTATION) Slog.v(TAG, "Deferring rotation.");
-            if (rotation != WindowManagerPolicy.USE_LAST_ROTATION) {
-                mDeferredRotation = rotation;
-                mDeferredRotationAnimFlags = animFlags;
-            }
+    public boolean updateRotationUncheckedLocked(boolean inTransaction) {
+        if (mDeferredRotationPauseCount > 0) {
+            // Rotation updates have been paused temporarily.  Defer the update until
+            // updates have been resumed.
+            if (DEBUG_ORIENTATION) Slog.v(TAG, "Deferring rotation, rotation is paused.");
             return false;
         }
 
-        boolean changed;
-        if (rotation == WindowManagerPolicy.USE_LAST_ROTATION) {
-            if (mDeferredRotation != WindowManagerPolicy.USE_LAST_ROTATION) {
-                rotation = mDeferredRotation;
-                mRequestedRotation = rotation;
-                mLastRotationFlags = mDeferredRotationAnimFlags;
+        if (mScreenRotationAnimation != null && mScreenRotationAnimation.isAnimating()) {
+            // Rotation updates cannot be performed while the previous rotation change
+            // animation is still in progress.  Skip this update.  We will try updating
+            // again after the animation is finished and the display is unfrozen.
+            if (DEBUG_ORIENTATION) Slog.v(TAG, "Deferring rotation, animation in progress.");
+            return false;
+        }
+
+        if (!mDisplayEnabled) {
+            // No point choosing a rotation if the display is not enabled.
+            if (DEBUG_ORIENTATION) Slog.v(TAG, "Deferring rotation, display is not enabled.");
+            return false;
+        }
+
+        // TODO: Implement forced rotation changes.
+        //       Set mAltOrientation to indicate that the application is receiving
+        //       an orientation that has different metrics than it expected.
+        //       eg. Portrait instead of Landscape.
+
+        int rotation = mPolicy.rotationForOrientationLw(mForcedAppOrientation, mRotation);
+        boolean altOrientation = !mPolicy.rotationHasCompatibleMetricsLw(
+                mForcedAppOrientation, rotation);
+
+        if (DEBUG_ORIENTATION) {
+            Slog.v(TAG, "Application requested orientation "
+                    + mForcedAppOrientation + ", got rotation " + rotation
+                    + " which has " + (altOrientation ? "incompatible" : "compatible")
+                    + " metrics");
+        }
+
+        if (mRotation == rotation && mAltOrientation == altOrientation) {
+            // No change.
+            return false;
+        }
+
+        if (DEBUG_ORIENTATION) {
+            Slog.v(TAG,
+                "Rotation changed to " + rotation + (altOrientation ? " (alt)" : "")
+                + " from " + mRotation + (mAltOrientation ? " (alt)" : "")
+                + ", forceApp=" + mForcedAppOrientation);
+        }
+
+        mRotation = rotation;
+        mAltOrientation = altOrientation;
+
+        mWindowsFreezingScreen = true;
+        mH.removeMessages(H.WINDOW_FREEZE_TIMEOUT);
+        mH.sendMessageDelayed(mH.obtainMessage(H.WINDOW_FREEZE_TIMEOUT), 2000);
+        mWaitingForConfig = true;
+        mLayoutNeeded = true;
+        startFreezingDisplayLocked(inTransaction);
+        mInputManager.setDisplayOrientation(0, rotation);
+
+        // NOTE: We disable the rotation in the emulator because
+        //       it doesn't support hardware OpenGL emulation yet.
+        if (CUSTOM_SCREEN_ROTATION && mScreenRotationAnimation != null
+                && mScreenRotationAnimation.hasScreenshot()) {
+            Surface.freezeDisplay(0);
+            if (!inTransaction) {
+                if (SHOW_TRANSACTIONS) Slog.i(TAG,
+                        ">>> OPEN TRANSACTION setRotationUnchecked");
+                Surface.openTransaction();
             }
-            rotation = mRequestedRotation;
+            try {
+                if (mScreenRotationAnimation != null) {
+                    mScreenRotationAnimation.setRotation(rotation);
+                }
+            } finally {
+                if (!inTransaction) {
+                    Surface.closeTransaction();
+                    if (SHOW_TRANSACTIONS) Slog.i(TAG,
+                            "<<< CLOSE TRANSACTION setRotationUnchecked");
+                }
+            }
+            Surface.setOrientation(0, rotation);
+            Surface.unfreezeDisplay(0);
         } else {
-            mRequestedRotation = rotation;
-            mLastRotationFlags = animFlags;
+            Surface.setOrientation(0, rotation);
         }
-        mDeferredRotation = WindowManagerPolicy.USE_LAST_ROTATION;
-        if (DEBUG_ORIENTATION) Slog.v(TAG, "Overwriting rotation value from " + rotation);
-        rotation = mPolicy.rotationForOrientationLw(mForcedAppOrientation,
-                mRotation, mDisplayEnabled);
-        if (DEBUG_ORIENTATION) Slog.v(TAG, "new rotation is set to " + rotation);
+        rebuildBlackFrame(inTransaction);
 
-        int desiredRotation = rotation;
-        int lockedRotation = mPolicy.getLockedRotationLw();
-        if (lockedRotation >= 0 && rotation != lockedRotation) {
-            // We are locked in a rotation but something is requesting
-            // a different rotation...  we will either keep the locked
-            // rotation if it results in the same orientation, or have to
-            // switch into an emulated orientation mode.
-
-            // First, we know that our rotation is actually going to be
-            // the locked rotation.
-            rotation = lockedRotation;
-
-            // Now the difference between the desired and lockedRotation
-            // may mean that the orientation is different...  if that is
-            // not the case, we can just make the desired rotation be the
-            // same as the new locked rotation.
-            switch (lockedRotation) {
-                case Surface.ROTATION_0:
-                    if (rotation == Surface.ROTATION_180) {
-                        desiredRotation = lockedRotation;
-                    }
-                    break;
-                case Surface.ROTATION_90:
-                    if (rotation == Surface.ROTATION_270) {
-                        desiredRotation = lockedRotation;
-                    }
-                    break;
-                case Surface.ROTATION_180:
-                    if (rotation == Surface.ROTATION_0) {
-                        desiredRotation = lockedRotation;
-                    }
-                    break;
-                case Surface.ROTATION_270:
-                    if (rotation == Surface.ROTATION_90) {
-                        desiredRotation = lockedRotation;
-                    }
-                    break;
+        for (int i=mWindows.size()-1; i>=0; i--) {
+            WindowState w = mWindows.get(i);
+            if (w.mSurface != null) {
+                w.mOrientationChanging = true;
             }
         }
-
-        changed = mDisplayEnabled && mRotation != rotation;
-        if (mAltOrientation != (rotation != desiredRotation)) {
-            changed = true;
-            mAltOrientation = rotation != desiredRotation;
+        for (int i=mRotationWatchers.size()-1; i>=0; i--) {
+            try {
+                mRotationWatchers.get(i).onRotationChanged(rotation);
+            } catch (RemoteException e) {
+            }
         }
-
-        if (changed) {
-            if (DEBUG_ORIENTATION) Slog.v(TAG,
-                    "Rotation changed to " + rotation
-                    + " from " + mRotation
-                    + " (forceApp=" + mForcedAppOrientation
-                    + ", req=" + mRequestedRotation + ")");
-            mRotation = rotation;
-            mWindowsFreezingScreen = true;
-            mH.removeMessages(H.WINDOW_FREEZE_TIMEOUT);
-            mH.sendMessageDelayed(mH.obtainMessage(H.WINDOW_FREEZE_TIMEOUT),
-                    2000);
-            mWaitingForConfig = true;
-            mLayoutNeeded = true;
-            startFreezingDisplayLocked(inTransaction);
-            //Slog.i(TAG, "Setting rotation to " + rotation + ", animFlags=" + animFlags);
-            mInputManager.setDisplayOrientation(0, rotation);
-            if (mDisplayEnabled) {
-                // NOTE: We disable the rotation in the emulator because
-                //       it doesn't support hardware OpenGL emulation yet.
-                if (CUSTOM_SCREEN_ROTATION && mScreenRotationAnimation != null
-                        && mScreenRotationAnimation.hasScreenshot()) {
-                    Surface.freezeDisplay(0);
-                    if (!inTransaction) {
-                        if (SHOW_TRANSACTIONS) Slog.i(TAG,
-                                ">>> OPEN TRANSACTION setRotationUnchecked");
-                        Surface.openTransaction();
-                    }
-                    try {
-                        if (mScreenRotationAnimation != null) {
-                            mScreenRotationAnimation.setRotation(rotation);
-                        }
-                    } finally {
-                        if (!inTransaction) {
-                            Surface.closeTransaction();
-                            if (SHOW_TRANSACTIONS) Slog.i(TAG,
-                                    "<<< CLOSE TRANSACTION setRotationUnchecked");
-                        }
-                    }
-                    Surface.setOrientation(0, rotation, animFlags);
-                    Surface.unfreezeDisplay(0);
-                } else {
-                    Surface.setOrientation(0, rotation, animFlags);
-                }
-                rebuildBlackFrame(inTransaction);
-            }
-
-            for (int i=mWindows.size()-1; i>=0; i--) {
-                WindowState w = mWindows.get(i);
-                if (w.mSurface != null) {
-                    w.mOrientationChanging = true;
-                }
-            }
-            for (int i=mRotationWatchers.size()-1; i>=0; i--) {
-                try {
-                    mRotationWatchers.get(i).onRotationChanged(rotation);
-                } catch (RemoteException e) {
-                }
-            }
-        } //end if changed
-
-        return changed;
+        return true;
     }
 
     public int getRotation() {
@@ -8601,8 +8590,7 @@
 
         if (updateRotation) {
             if (DEBUG_ORIENTATION) Slog.d(TAG, "Performing post-rotate rotation");
-            boolean changed = setRotationUncheckedLocked(
-                    WindowManagerPolicy.USE_LAST_ROTATION, 0, false);
+            boolean changed = updateRotationUncheckedLocked(false);
             if (changed) {
                 mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
             } else {
@@ -9029,8 +9017,7 @@
         
         if (updateRotation) {
             if (DEBUG_ORIENTATION) Slog.d(TAG, "Performing post-rotate rotation");
-            configChanged |= setRotationUncheckedLocked(
-                    WindowManagerPolicy.USE_LAST_ROTATION, 0, false);
+            configChanged |= updateRotationUncheckedLocked(false);
         }
         
         if (configChanged) {
@@ -9403,12 +9390,10 @@
                     pw.print(" mAppsFreezingScreen="); pw.print(mAppsFreezingScreen);
                     pw.print(" mWaitingForConfig="); pw.println(mWaitingForConfig);
             pw.print("  mRotation="); pw.print(mRotation);
-                    pw.print(" mRequestedRotation="); pw.print(mRequestedRotation);
                     pw.print(" mAltOrientation="); pw.println(mAltOrientation);
             pw.print("  mLastWindowForcedOrientation"); pw.print(mLastWindowForcedOrientation);
                     pw.print(" mForcedAppOrientation="); pw.println(mForcedAppOrientation);
-            pw.print("  mDeferredRotation="); pw.print(mDeferredRotation);
-                    pw.print(", mDeferredRotationAnimFlags="); pw.println(mDeferredRotationAnimFlags);
+            pw.print("  mDeferredRotationPauseCount="); pw.println(mDeferredRotationPauseCount);
             pw.print("  mAnimationPending="); pw.print(mAnimationPending);
                     pw.print(" mWindowAnimationScale="); pw.print(mWindowAnimationScale);
                     pw.print(" mTransitionWindowAnimationScale="); pw.println(mTransitionAnimationScale);
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 0ef03bb..09097ee 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -566,7 +566,7 @@
 
             const int dpy = 0;
             const int orientation = mCurrentState.orientation;
-            const uint32_t type = mCurrentState.orientationType;
+            // Currently unused: const uint32_t flags = mCurrentState.orientationFlags;
             GraphicPlane& plane(graphicPlane(dpy));
             plane.setOrientation(orientation);
 
@@ -1299,7 +1299,7 @@
     Mutex::Autolock _l(mStateLock);
     if (mCurrentState.orientation != orientation) {
         if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
-            mCurrentState.orientationType = flags;
+            mCurrentState.orientationFlags = flags;
             mCurrentState.orientation = orientation;
             setTransactionFlags(eTransactionNeeded);
             mTransactionCV.wait(mStateLock);
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index d7f005f..43191b7 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -245,7 +245,7 @@
         }
         LayerVector     layersSortedByZ;
         uint8_t         orientation;
-        uint8_t         orientationType;
+        uint8_t         orientationFlags;
         uint8_t         freezeDisplay;
     };
 
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
index ebf5e65..78ba7dd 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
@@ -1768,8 +1768,10 @@
             ApnSetting apn = apnContext.getApnSetting();
             if (apn.proxy != null && apn.proxy.length() != 0) {
                 try {
+                    String port = apn.port;
+                    if (TextUtils.isEmpty(port)) port = "8080";
                     ProxyProperties proxy = new ProxyProperties(apn.proxy,
-                            Integer.parseInt(apn.port), null);
+                            Integer.parseInt(port), null);
                     dcac.setLinkPropertiesHttpProxySync(proxy);
                 } catch (NumberFormatException e) {
                     loge("onDataSetupComplete: NumberFormatException making ProxyProperties (" +
@@ -2085,18 +2087,6 @@
     }
 
     /**
-     * Check current radio access technology is LTE or EHRPD.
-     *
-     * @param integer value of radio access technology
-     * @return true when current radio access technology is LTE or EHRPD
-     * @	   false when current radio access technology is not LTE or EHRPD
-     */
-    private boolean needToCheckApnBearer(int radioTech) {
-        return (radioTech == ServiceState.RADIO_TECHNOLOGY_LTE ||
-                radioTech == ServiceState.RADIO_TECHNOLOGY_EHRPD);
-    }
-
-    /**
      * Build a list of APNs to be used to create PDP's.
      *
      * @param requestedApnType
@@ -2117,7 +2107,6 @@
 
         String operator = mPhone.mIccRecords.getOperatorNumeric();
         int radioTech = mPhone.getServiceState().getRadioTechnology();
-        boolean needToCheckApnBearer = needToCheckApnBearer(radioTech);
 
         if (requestedApnType.equals(Phone.APN_TYPE_DEFAULT)) {
             if (canSetPreferApn && mPreferredApn != null) {
@@ -2126,7 +2115,7 @@
                         + mPreferredApn.numeric + ":" + mPreferredApn);
                 }
                 if (mPreferredApn.numeric.equals(operator)) {
-                    if (!needToCheckApnBearer || mPreferredApn.bearer == radioTech) {
+                    if (mPreferredApn.bearer == 0 || mPreferredApn.bearer == radioTech) {
                         apnList.add(mPreferredApn);
                         if (DBG) log("buildWaitingApns: X added preferred apnList=" + apnList);
                         return apnList;
@@ -2145,7 +2134,7 @@
         if (mAllApns != null) {
             for (ApnSetting apn : mAllApns) {
                 if (apn.canHandleType(requestedApnType)) {
-                    if (!needToCheckApnBearer || apn.bearer == radioTech) {
+                    if (apn.bearer == 0 || apn.bearer == radioTech) {
                         if (DBG) log("apn info : " +apn.toString());
                         apnList.add(apn);
                     }
diff --git a/test-runner/src/android/test/mock/MockPackageManager.java b/test-runner/src/android/test/mock/MockPackageManager.java
index f2fb36f..3525abe 100644
--- a/test-runner/src/android/test/mock/MockPackageManager.java
+++ b/test-runner/src/android/test/mock/MockPackageManager.java
@@ -546,11 +546,8 @@
         throw new UnsupportedOperationException();
     }
 
-    /**
-     * @hide
-     */
     @Override
-    public void verifyPendingInstall(int id, boolean verified, String failureMessage) {
+    public void verifyPendingInstall(int id, int verificationCode) {
         throw new UnsupportedOperationException();
     }
 
diff --git a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
index f015378..5df018e 100644
--- a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
+++ b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
@@ -412,9 +412,31 @@
     @SmallTest
     public void testSET_ORIENTATION() {
         try {
-            mWm.setRotation(0, true, 0);
+            mWm.updateRotation(true);
             mWm.getSwitchState(0);
-            fail("IWindowManager.setRotation did not throw SecurityException as"
+            fail("IWindowManager.updateRotation did not throw SecurityException as"
+                    + " expected");
+        } catch (SecurityException e) {
+            // expected
+        } catch (RemoteException e) {
+            fail("Unexpected remote exception");
+        }
+
+        try {
+            mWm.freezeRotation();
+            mWm.getSwitchState(0);
+            fail("IWindowManager.freezeRotation did not throw SecurityException as"
+                    + " expected");
+        } catch (SecurityException e) {
+            // expected
+        } catch (RemoteException e) {
+            fail("Unexpected remote exception");
+        }
+
+        try {
+            mWm.thawRotation();
+            mWm.getSwitchState(0);
+            fail("IWindowManager.thawRotation did not throw SecurityException as"
                     + " expected");
         } catch (SecurityException e) {
             // expected
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowManager.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowManager.java
index 3d1fa7a..940b290 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowManager.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowManager.java
@@ -396,7 +396,7 @@
 
     }
 
-    public void setRotation(int arg0, boolean arg1, int arg2) throws RemoteException {
+    public void updateRotation(boolean arg0) throws RemoteException {
         // TODO Auto-generated method stub
 
     }