Merge "Return early when we cannot allocate a hardware layer Bug #5462308"
diff --git a/Android.mk b/Android.mk
index a38723a..f41130b 100644
--- a/Android.mk
+++ b/Android.mk
@@ -402,8 +402,8 @@
 		            resources/samples/AccelerometerPlay "Accelerometer Play" \
 		-samplecode $(sample_dir)/ActionBarCompat \
 		            resources/samples/ActionBarCompat "Action Bar Compatibility" \
-                -samplecode $(sample_dir)/AndroidBeam \
-		            resources/samples/AndroidBeam "Android Beam" \
+                -samplecode $(sample_dir)/AndroidBeamDemo \
+		            resources/samples/AndroidBeamDemo "Android Beam Demo" \
 		-samplecode $(sample_dir)/ApiDemos \
 		            resources/samples/ApiDemos "API Demos" \
 		-samplecode $(sample_dir)/Support4Demos \
diff --git a/api/current.txt b/api/current.txt
index 662ebcd..ffa46ec 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -6782,6 +6782,13 @@
     method public abstract boolean onMove(int, int);
   }
 
+  public class CrossProcessCursorWrapper extends android.database.CursorWrapper implements android.database.CrossProcessCursor {
+    ctor public CrossProcessCursorWrapper(android.database.Cursor);
+    method public void fillWindow(int, android.database.CursorWindow);
+    method public android.database.CursorWindow getWindow();
+    method public boolean onMove(int, int);
+  }
+
   public abstract interface Cursor {
     method public abstract void close();
     method public abstract void copyStringToBuffer(int, android.database.CharArrayBuffer);
@@ -6851,7 +6858,8 @@
   }
 
   public class CursorWindow extends android.database.sqlite.SQLiteClosable implements android.os.Parcelable {
-    ctor public CursorWindow(boolean);
+    ctor public CursorWindow(java.lang.String);
+    ctor public deprecated CursorWindow(boolean);
     method public boolean allocRow();
     method public void clear();
     method public void close();
diff --git a/cmds/stagefright/stagefright.cpp b/cmds/stagefright/stagefright.cpp
index 528d197..7cb8f62 100644
--- a/cmds/stagefright/stagefright.cpp
+++ b/cmds/stagefright/stagefright.cpp
@@ -30,7 +30,6 @@
 #include <binder/ProcessState.h>
 #include <media/IMediaPlayerService.h>
 #include <media/stagefright/foundation/ALooper.h>
-#include "include/ARTSPController.h"
 #include "include/LiveSession.h"
 #include "include/NuCachedSource2.h"
 #include <media/stagefright/AudioPlayer.h>
@@ -636,7 +635,6 @@
     gDisplayHistogram = false;
 
     sp<ALooper> looper;
-    sp<ARTSPController> rtspController;
     sp<LiveSession> liveSession;
 
     int res;
@@ -948,7 +946,6 @@
         sp<DataSource> dataSource = DataSource::CreateFromURI(filename);
 
         if (strncasecmp(filename, "sine:", 5)
-                && strncasecmp(filename, "rtsp://", 7)
                 && strncasecmp(filename, "httplive://", 11)
                 && dataSource == NULL) {
             fprintf(stderr, "Unable to create data source.\n");
@@ -984,23 +981,7 @@
         } else {
             sp<MediaExtractor> extractor;
 
-            if (!strncasecmp("rtsp://", filename, 7)) {
-                if (looper == NULL) {
-                    looper = new ALooper;
-                    looper->start();
-                }
-
-                rtspController = new ARTSPController(looper);
-                status_t err = rtspController->connect(filename);
-                if (err != OK) {
-                    fprintf(stderr, "could not connect to rtsp server.\n");
-                    return -1;
-                }
-
-                extractor = rtspController.get();
-
-                syncInfoPresent = false;
-            } else if (!strncasecmp("httplive://", filename, 11)) {
+            if (!strncasecmp("httplive://", filename, 11)) {
                 String8 uri("http://");
                 uri.append(filename + 11);
 
@@ -1021,6 +1002,7 @@
                 syncInfoPresent = false;
             } else {
                 extractor = MediaExtractor::Create(dataSource);
+
                 if (extractor == NULL) {
                     fprintf(stderr, "could not create extractor.\n");
                     return -1;
@@ -1116,13 +1098,6 @@
         } else {
             playSource(&client, mediaSource);
         }
-
-        if (rtspController != NULL) {
-            rtspController->disconnect();
-            rtspController.clear();
-
-            sleep(3);
-        }
     }
 
     if ((useSurfaceAlloc || useSurfaceTexAlloc) && !audioOnly) {
diff --git a/core/java/android/accessibilityservice/AccessibilityService.java b/core/java/android/accessibilityservice/AccessibilityService.java
index 1e238f0..64a2755 100644
--- a/core/java/android/accessibilityservice/AccessibilityService.java
+++ b/core/java/android/accessibilityservice/AccessibilityService.java
@@ -32,11 +32,9 @@
  * when {@link AccessibilityEvent}s are fired. Such events denote some state transition
  * in the user interface, for example, the focus has changed, a button has been clicked,
  * etc. Such a service can optionally request the capability for querying the content
- * of the active window. Development of an accessibility service requires extends this
- * class and implements its abstract methods.
- * <p>
- * <strong>Lifecycle</strong>
- * </p>
+ * of the active window. Development of an accessibility service requires extending this
+ * class and implementing its abstract methods.
+ * <h3>Lifecycle</h3>
  * <p>
  * The lifecycle of an accessibility service is managed exclusively by the system and
  * follows the established service life cycle. Additionally, starting or stopping an
@@ -45,30 +43,20 @@
  * calls {@link AccessibilityService#onServiceConnected()}. This method can be
  * overriden by clients that want to perform post binding setup.
  * </p>
- * <p>
- * <strong>Declaration</strong>
- * </p>
+ * <h3>Declaration</h3>
  * <p>
  * An accessibility is declared as any other service in an AndroidManifest.xml but it
  * must also specify that it handles the "android.accessibilityservice.AccessibilityService"
  * {@link android.content.Intent}. Failure to declare this intent will cause the system to
  * ignore the accessibility service. Following is an example declaration:
  * </p>
- * <p>
- * <code>
- * <pre>
- *   &lt;service android:name=".MyAccessibilityService"&gt;
+ * <pre> &lt;service android:name=".MyAccessibilityService"&gt;
  *     &lt;intent-filter&gt;
- *       &lt;action android:name="android.accessibilityservice.AccessibilityService" /&gt;
+ *         &lt;action android:name="android.accessibilityservice.AccessibilityService" /&gt;
  *     &lt;/intent-filter&gt;
  *     . . .
- *   &lt;/service&gt;
- * </pre>
- * </code>
- * </p>
- * <p>
- * <strong>Configuration</strong>
- * </p>
+ * &lt;/service&gt;</pre>
+ * <h3>Configuration</h3>
  * <p>
  * An accessibility service can be configured to receive specific types of accessibility events,
  * listen only to specific packages, get events from each type only once in a given time frame,
@@ -81,30 +69,24 @@
  * <li>
  * Providing a {@link #SERVICE_META_DATA meta-data} entry in the manifest when declaring
  * the service. A service declaration with a meta-data tag is presented below:
- * <p>
- * <code>
- * <pre>
- *   &lt;service android:name=".MyAccessibilityService"&gt;
+ * <pre> &lt;service android:name=".MyAccessibilityService"&gt;
  *     &lt;intent-filter&gt;
- *       &lt;action android:name="android.accessibilityservice.AccessibilityService" /&gt;
+ *         &lt;action android:name="android.accessibilityservice.AccessibilityService" /&gt;
  *     &lt;/intent-filter&gt;
  *     &lt;meta-data android:name="android.accessibilityservice" android:resource="@xml/accessibilityservice" /&gt;
- *   &lt;/service&gt;
- * </pre>
- * </code>
- * </p>
- * <p>
- * <strong>Note:</strong>This approach enables setting all properties.
+ * &lt;/service&gt;</pre>
+ * <p class="note">
+ * <strong>Note:</strong> This approach enables setting all properties.
  * </p>
  * <p>
  * For more details refer to {@link #SERVICE_META_DATA} and
- * <code>&lt;{@link android.R.styleable#AccessibilityService accessibility-service}&gt;</code>..
+ * <code>&lt;{@link android.R.styleable#AccessibilityService accessibility-service}&gt;</code>.
  * </p>
  * </li>
  * <li>
  * Calling {@link AccessibilityService#setServiceInfo(AccessibilityServiceInfo)}. Note
  * that this method can be called any time to dynamically change the service configuration.
- * <p>
+ * <p class="note">
  * <strong>Note:</strong> This approach enables setting only dynamically configurable properties:
  * {@link AccessibilityServiceInfo#eventTypes},
  * {@link AccessibilityServiceInfo#feedbackType},
@@ -117,9 +99,7 @@
  * </p>
  * </li>
  * </ul>
- * <p>
- * <strong>Retrieving window content</strong>
- * </p>
+ * <h3>Retrieving window content</h3>
  * <p>
  * An service can specify in its declaration that it can retrieve the active window
  * content which is represented as a tree of {@link AccessibilityNodeInfo}. Note that
@@ -144,8 +124,8 @@
  * this method will return an {@link AccessibilityNodeInfo} that can be used to traverse the
  * window content which represented as a tree of such objects.
  * </p>
- * <p>
- * <strong>Note</strong>An accessibility service may have requested to be notified for
+ * <p class="note">
+ * <strong>Note</strong> An accessibility service may have requested to be notified for
  * a subset of the event types, thus be unaware that the active window has changed. Therefore
  * accessibility service that would like to retrieve window content should:
  * <ul>
@@ -158,15 +138,13 @@
  * <li>
  * Prepare that a retrieval method on {@link AccessibilityNodeInfo} may fail since the
  * active window has changed and the service did not get the accessibility event yet. Note
- * that it is possible to have a retrieval method failing event adopting the strategy
+ * that it is possible to have a retrieval method failing even adopting the strategy
  * specified in the previous bullet because the accessibility event dispatch is asynchronous
  * and crosses process boundaries.
  * </li>
  * </ul>
  * </p>
- * <p>
- * <b>Notification strategy</b>
- * </p>
+ * <h3>Notification strategy</h3>
  * <p>
  * For each feedback type only one accessibility service is notified. Services are notified
  * in the order of registration. Hence, if two services are registered for the same
@@ -178,40 +156,39 @@
  * well with most applications to coexist with "polished" ones that are targeted for
  * specific applications.
  * </p>
- * <p>
- * <b>Event types</b>
- * </p>
- * {@link AccessibilityEvent#TYPE_VIEW_CLICKED}
- * {@link AccessibilityEvent#TYPE_VIEW_LONG_CLICKED}
- * {@link AccessibilityEvent#TYPE_VIEW_FOCUSED}
- * {@link AccessibilityEvent#TYPE_VIEW_SELECTED}
- * {@link AccessibilityEvent#TYPE_VIEW_TEXT_CHANGED}
- * {@link AccessibilityEvent#TYPE_WINDOW_STATE_CHANGED}
- * {@link AccessibilityEvent#TYPE_NOTIFICATION_STATE_CHANGED}
- * {@link AccessibilityEvent#TYPE_TOUCH_EXPLORATION_GESTURE_START}
- * {@link AccessibilityEvent#TYPE_TOUCH_EXPLORATION_GESTURE_END}
- * {@link AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}
- * {@link AccessibilityEvent#TYPE_VIEW_HOVER_EXIT}
- * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED}
- * {@link AccessibilityEvent#TYPE_VIEW_TEXT_SELECTION_CHANGED}
- * {@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED}
- * <p>
- * <b>Feedback types</b>
- * <p>
- * {@link AccessibilityServiceInfo#FEEDBACK_AUDIBLE}
- * {@link AccessibilityServiceInfo#FEEDBACK_HAPTIC}
- * {@link AccessibilityServiceInfo#FEEDBACK_AUDIBLE}
- * {@link AccessibilityServiceInfo#FEEDBACK_VISUAL}
- * {@link AccessibilityServiceInfo#FEEDBACK_GENERIC}
- *
- * @see AccessibilityEvent
- * @see AccessibilityServiceInfo
- * @see android.view.accessibility.AccessibilityManager
- *
+ * <p class="note">
  * <strong>Note:</strong> The event notification timeout is useful to avoid propagating
  * events to the client too frequently since this is accomplished via an expensive
  * interprocess call. One can think of the timeout as a criteria to determine when
- * event generation has settled down.
+ * event generation has settled down.</p>
+ * <h3>Event types</h3>
+ * <ul>
+ * <li>{@link AccessibilityEvent#TYPE_VIEW_CLICKED}
+ * <li>{@link AccessibilityEvent#TYPE_VIEW_LONG_CLICKED}
+ * <li>{@link AccessibilityEvent#TYPE_VIEW_FOCUSED}
+ * <li>{@link AccessibilityEvent#TYPE_VIEW_SELECTED}
+ * <li>{@link AccessibilityEvent#TYPE_VIEW_TEXT_CHANGED}
+ * <li>{@link AccessibilityEvent#TYPE_WINDOW_STATE_CHANGED}
+ * <li>{@link AccessibilityEvent#TYPE_NOTIFICATION_STATE_CHANGED}
+ * <li>{@link AccessibilityEvent#TYPE_TOUCH_EXPLORATION_GESTURE_START}
+ * <li>{@link AccessibilityEvent#TYPE_TOUCH_EXPLORATION_GESTURE_END}
+ * <li>{@link AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}
+ * <li>{@link AccessibilityEvent#TYPE_VIEW_HOVER_EXIT}
+ * <li>{@link AccessibilityEvent#TYPE_VIEW_SCROLLED}
+ * <li>{@link AccessibilityEvent#TYPE_VIEW_TEXT_SELECTION_CHANGED}
+ * <li>{@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED}
+ * </ul>
+ * <h3>Feedback types</h3>
+ * <ul>
+ * <li>{@link AccessibilityServiceInfo#FEEDBACK_AUDIBLE}
+ * <li>{@link AccessibilityServiceInfo#FEEDBACK_HAPTIC}
+ * <li>{@link AccessibilityServiceInfo#FEEDBACK_AUDIBLE}
+ * <li>{@link AccessibilityServiceInfo#FEEDBACK_VISUAL}
+ * <li>{@link AccessibilityServiceInfo#FEEDBACK_GENERIC}
+ * </ul>
+ * @see AccessibilityEvent
+ * @see AccessibilityServiceInfo
+ * @see android.view.accessibility.AccessibilityManager
  */
 public abstract class AccessibilityService extends Service {
     /**
@@ -225,10 +202,7 @@
      * about itself. This meta-data must reference an XML resource containing an
      * <code>&lt;{@link android.R.styleable#AccessibilityService accessibility-service}&gt;</code>
      * tag. This is a a sample XML file configuring an accessibility service:
-     * <p>
-     * <code>
-     * <pre>
-     *   &lt;accessibility-service
+     * <pre> &lt;accessibility-service
      *     android:accessibilityEventTypes="typeViewClicked|typeViewFocused"
      *     android:packageNames="foo.bar, foo.baz"
      *     android:accessibilityFeedbackType="feedbackSpoken"
@@ -237,10 +211,7 @@
      *     android:settingsActivity="foo.bar.TestBackActivity"
      *     android:canRetrieveWindowContent="true"
      *     . . .
-     *   /&gt;
-     * </pre>
-     * </code>
-     * </p>
+     * /&gt;</pre>
      */
     public static final String SERVICE_META_DATA = "android.accessibilityservice";
 
diff --git a/core/java/android/app/AlertDialog.java b/core/java/android/app/AlertDialog.java
index c09e87f..e37b3fa 100644
--- a/core/java/android/app/AlertDialog.java
+++ b/core/java/android/app/AlertDialog.java
@@ -54,6 +54,12 @@
  * without text editors, so that it will be placed on top of the current
  * input method UI.  You can modify this behavior by forcing the flag to your
  * desired mode after calling {@link #onCreate}.
+ *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For more information about creating dialogs, read the
+ * <a href="{@docRoot}guide/topics/ui/dialogs.html">Dialogs</a> developer guide.</p>
+ * </div>
  */
 public class AlertDialog extends Dialog implements DialogInterface {
     private AlertController mAlert;
diff --git a/core/java/android/app/Dialog.java b/core/java/android/app/Dialog.java
index 82186dd..7a69419 100644
--- a/core/java/android/app/Dialog.java
+++ b/core/java/android/app/Dialog.java
@@ -66,9 +66,14 @@
  * your Dialog takes input focus, as it the default) with the following code:
  * 
  * <pre>
- *     getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
- *             WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
- * </pre>
+ * getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
+ *         WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);</pre>
+ *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For more information about creating dialogs, read the
+ * <a href="{@docRoot}guide/topics/ui/dialogs.html">Dialogs</a> developer guide.</p>
+ * </div>
  */
 public class Dialog implements DialogInterface, Window.Callback,
         KeyEvent.Callback, OnCreateContextMenuListener {
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 9490b96..f5add25 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -38,9 +38,12 @@
  * <p>The {@link Notification.Builder Notification.Builder} has been added to make it
  * easier to construct Notifications.</p>
  *
- * <p>For a guide to creating notifications, see the
- * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Creating Status 
- * Bar Notifications</a> document in the Dev Guide.</p>
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For a guide to creating notifications, read the
+ * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
+ * developer guide.</p>
+ * </div>
  */
 public class Notification implements Parcelable
 {
diff --git a/core/java/android/app/NotificationManager.java b/core/java/android/app/NotificationManager.java
index 4913e78..bf83f5e 100644
--- a/core/java/android/app/NotificationManager.java
+++ b/core/java/android/app/NotificationManager.java
@@ -55,6 +55,13 @@
  * You do not instantiate this class directly; instead, retrieve it through
  * {@link android.content.Context#getSystemService}.
  *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For a guide to creating notifications, read the
+ * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
+ * developer guide.</p>
+ * </div>
+ *
  * @see android.app.Notification
  * @see android.content.Context#getSystemService
  */
diff --git a/core/java/android/app/SearchManager.java b/core/java/android/app/SearchManager.java
index 3290b9d..3aa159e 100644
--- a/core/java/android/app/SearchManager.java
+++ b/core/java/android/app/SearchManager.java
@@ -24,6 +24,7 @@
 import android.content.Intent;
 import android.content.pm.ResolveInfo;
 import android.database.Cursor;
+import android.graphics.Rect;
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.Handler;
@@ -498,8 +499,24 @@
                             ComponentName launchActivity,
                             Bundle appSearchData,
                             boolean globalSearch) {
+        startSearch(initialQuery, selectInitialQuery, launchActivity,
+                appSearchData, globalSearch, null);
+    }
+
+    /**
+     * As {@link #startSearch(String, boolean, ComponentName, Bundle, boolean)} but including
+     * source bounds for the global search intent.
+     *
+     * @hide
+     */
+    public void startSearch(String initialQuery,
+                            boolean selectInitialQuery,
+                            ComponentName launchActivity,
+                            Bundle appSearchData,
+                            boolean globalSearch,
+                            Rect sourceBounds) {
         if (globalSearch) {
-            startGlobalSearch(initialQuery, selectInitialQuery, appSearchData);
+            startGlobalSearch(initialQuery, selectInitialQuery, appSearchData, sourceBounds);
             return;
         }
 
@@ -520,7 +537,7 @@
      * Starts the global search activity.
      */
     /* package */ void startGlobalSearch(String initialQuery, boolean selectInitialQuery,
-            Bundle appSearchData) {
+            Bundle appSearchData, Rect sourceBounds) {
         ComponentName globalSearchActivity = getGlobalSearchActivity();
         if (globalSearchActivity == null) {
             Log.w(TAG, "No global search activity found.");
@@ -546,6 +563,7 @@
         if (selectInitialQuery) {
             intent.putExtra(EXTRA_SELECT_QUERY, selectInitialQuery);
         }
+        intent.setSourceBounds(sourceBounds);
         try {
             if (DBG) Log.d(TAG, "Starting global search: " + intent.toUri(0));
             mContext.startActivity(intent);
diff --git a/core/java/android/app/StatusBarManager.java b/core/java/android/app/StatusBarManager.java
index ca64c88..c5ee48d 100644
--- a/core/java/android/app/StatusBarManager.java
+++ b/core/java/android/app/StatusBarManager.java
@@ -40,15 +40,20 @@
     public static final int DISABLE_NOTIFICATION_TICKER
             = View.STATUS_BAR_DISABLE_NOTIFICATION_TICKER;
     public static final int DISABLE_SYSTEM_INFO = View.STATUS_BAR_DISABLE_SYSTEM_INFO;
-    public static final int DISABLE_NAVIGATION = View.STATUS_BAR_DISABLE_NAVIGATION;
+    public static final int DISABLE_HOME = View.STATUS_BAR_DISABLE_HOME;
+    public static final int DISABLE_RECENT = View.STATUS_BAR_DISABLE_RECENT;
     public static final int DISABLE_BACK = View.STATUS_BAR_DISABLE_BACK;
     public static final int DISABLE_CLOCK = View.STATUS_BAR_DISABLE_CLOCK;
 
+    @Deprecated
+    public static final int DISABLE_NAVIGATION = 
+            View.STATUS_BAR_DISABLE_HOME | View.STATUS_BAR_DISABLE_RECENT;
+
     public static final int DISABLE_NONE = 0x00000000;
 
     public static final int DISABLE_MASK = DISABLE_EXPAND | DISABLE_NOTIFICATION_ICONS
             | DISABLE_NOTIFICATION_ALERTS | DISABLE_NOTIFICATION_TICKER
-            | DISABLE_SYSTEM_INFO| DISABLE_NAVIGATION | DISABLE_BACK | DISABLE_CLOCK;
+            | DISABLE_SYSTEM_INFO | DISABLE_RECENT | DISABLE_HOME | DISABLE_BACK | DISABLE_CLOCK;
 
     private Context mContext;
     private IStatusBarService mService;
diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java
index e452f1f..092a0c8 100644
--- a/core/java/android/content/ContentProvider.java
+++ b/core/java/android/content/ContentProvider.java
@@ -45,9 +45,6 @@
  * multiple applications you can use a database directly via
  * {@link android.database.sqlite.SQLiteDatabase}.
  *
- * <p>For more information, read <a href="{@docRoot}guide/topics/providers/content-providers.html">Content
- * Providers</a>.</p>
- *
  * <p>When a request is made via
  * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
  * request to the content provider registered with the authority. The content provider can interpret
@@ -73,6 +70,12 @@
  * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
  * ContentProvider instance, so subclasses don't have to worry about the details of
  * cross-process calls.</p>
+ *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For more information about using content providers, read the
+ * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
+ * developer guide.</p>
  */
 public abstract class ContentProvider implements ComponentCallbacks2 {
     private static final String TAG = "ContentProvider";
diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java
index 0d25926..cc3219b 100644
--- a/core/java/android/content/ContentResolver.java
+++ b/core/java/android/content/ContentResolver.java
@@ -26,6 +26,7 @@
 import android.content.res.AssetFileDescriptor;
 import android.content.res.Resources;
 import android.database.ContentObserver;
+import android.database.CrossProcessCursorWrapper;
 import android.database.Cursor;
 import android.database.CursorWrapper;
 import android.database.IContentObserver;
@@ -54,6 +55,12 @@
 
 /**
  * This class provides applications access to the content model.
+ *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For more information about using a ContentResolver with content providers, read the
+ * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
+ * developer guide.</p>
  */
 public abstract class ContentResolver {
     /**
@@ -1562,7 +1569,7 @@
             samplePercent);
     }
 
-    private final class CursorWrapperInner extends CursorWrapper {
+    private final class CursorWrapperInner extends CrossProcessCursorWrapper {
         private final IContentProvider mContentProvider;
         public static final String TAG="CursorWrapperInner";
 
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index 2be5153..45a42e4 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -57,8 +57,8 @@
  *
  * <p>An Intent provides a facility for performing late runtime binding between the code in
  * different applications. Its most significant use is in the launching of activities, where it
- * can be thought of as the glue between activities. It is basically a passive data structure 
- * holding an abstract description of an action to be performed.</p> 
+ * can be thought of as the glue between activities. It is basically a passive data structure
+ * holding an abstract description of an action to be performed.</p>
  *
  * <div class="special reference">
  * <h3>Developer Guides</h3>
@@ -2566,7 +2566,7 @@
      */
     public static final String EXTRA_LOCAL_ONLY =
         "android.intent.extra.LOCAL_ONLY";
-    
+
     // ---------------------------------------------------------------------
     // ---------------------------------------------------------------------
     // Intent flags (see mFlags variable).
@@ -5291,7 +5291,7 @@
         if (r != null) {
             mSourceBounds = new Rect(r);
         } else {
-            r = null;
+            mSourceBounds = null;
         }
     }
 
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index 7a7e4f4..3eb7647 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -2124,6 +2124,9 @@
         if (pkg == null) {
             return null;
         }
+        if ((flags & GET_SIGNATURES) != 0) {
+            packageParser.collectCertificates(pkg, 0);
+        }
         return PackageParser.generatePackageInfo(pkg, null, flags, 0, 0);
     }
 
diff --git a/core/java/android/database/AbstractCursor.java b/core/java/android/database/AbstractCursor.java
index ee6aec6..74fef29 100644
--- a/core/java/android/database/AbstractCursor.java
+++ b/core/java/android/database/AbstractCursor.java
@@ -53,7 +53,10 @@
     abstract public boolean isNull(int column);
 
     public int getType(int column) {
-        throw new UnsupportedOperationException();
+        // Reflects the assumption that all commonly used field types (meaning everything
+        // but blobs) are convertible to strings so it should be safe to call
+        // getString to retrieve them.
+        return FIELD_TYPE_STRING;
     }
 
     // TODO implement getBlob in all cursor types
@@ -185,46 +188,9 @@
         return result;
     }
 
-    /**
-     * Copy data from cursor to CursorWindow
-     * @param position start position of data
-     * @param window
-     */
+    @Override
     public void fillWindow(int position, CursorWindow window) {
-        if (position < 0 || position >= getCount()) {
-            return;
-        }
-        window.acquireReference();
-        try {
-            int oldpos = mPos;
-            mPos = position - 1;
-            window.clear();
-            window.setStartPosition(position);
-            int columnNum = getColumnCount();
-            window.setNumColumns(columnNum);
-            while (moveToNext() && window.allocRow()) {
-                for (int i = 0; i < columnNum; i++) {
-                    String field = getString(i);
-                    if (field != null) {
-                        if (!window.putString(field, mPos, i)) {
-                            window.freeLastRow();
-                            break;
-                        }
-                    } else {
-                        if (!window.putNull(mPos, i)) {
-                            window.freeLastRow();
-                            break;
-                        }
-                    }
-                }
-            }
-
-            mPos = oldpos;
-        } catch (IllegalStateException e){
-            // simply ignore it
-        } finally {
-            window.releaseReference();
-        }
+        DatabaseUtils.cursorFillWindow(this, position, window);
     }
 
     public final boolean move(int offset) {
diff --git a/core/java/android/database/AbstractWindowedCursor.java b/core/java/android/database/AbstractWindowedCursor.java
index d0aedd2..083485f 100644
--- a/core/java/android/database/AbstractWindowedCursor.java
+++ b/core/java/android/database/AbstractWindowedCursor.java
@@ -188,15 +188,14 @@
 
     /**
      * If there is a window, clear it.
-     * Otherwise, creates a local window.
+     * Otherwise, creates a new window.
      *
      * @param name The window name.
      * @hide
      */
-    protected void clearOrCreateLocalWindow(String name) {
+    protected void clearOrCreateWindow(String name) {
         if (mWindow == null) {
-            // If there isn't a window set already it will only be accessed locally
-            mWindow = new CursorWindow(name, true /* the window is local only */);
+            mWindow = new CursorWindow(name);
         } else {
             mWindow.clear();
         }
diff --git a/core/java/android/database/CrossProcessCursor.java b/core/java/android/database/CrossProcessCursor.java
index 8e6a5aa..26379cc 100644
--- a/core/java/android/database/CrossProcessCursor.java
+++ b/core/java/android/database/CrossProcessCursor.java
@@ -16,27 +16,63 @@
 
 package android.database;
 
+/**
+ * A cross process cursor is an extension of a {@link Cursor} that also supports
+ * usage from remote processes.
+ * <p>
+ * The contents of a cross process cursor are marshalled to the remote process by
+ * filling {@link CursorWindow} objects using {@link #fillWindow}.  As an optimization,
+ * the cursor can provide a pre-filled window to use via {@link #getWindow} thereby
+ * obviating the need to copy the data to yet another cursor window.
+ */
 public interface CrossProcessCursor extends Cursor {
     /**
-     * returns a pre-filled window, return NULL if no such window
+     * Returns a pre-filled window that contains the data within this cursor.
+     * <p>
+     * In particular, the window contains the row indicated by {@link Cursor#getPosition}.
+     * The window's contents are automatically scrolled whenever the current
+     * row moved outside the range covered by the window.
+     * </p>
+     *
+     * @return The pre-filled window, or null if none.
      */
     CursorWindow getWindow();
 
     /**
-     * copies cursor data into the window start at pos
+     * Copies cursor data into the window.
+     * <p>
+     * Clears the window and fills it with data beginning at the requested
+     * row position until all of the data in the cursor is exhausted
+     * or the window runs out of space.
+     * </p><p>
+     * The filled window uses the same row indices as the original cursor.
+     * For example, if you fill a window starting from row 5 from the cursor,
+     * you can query the contents of row 5 from the window just by asking it
+     * for row 5 because there is a direct correspondence between the row indices
+     * used by the cursor and the window.
+     * </p><p>
+     * The current position of the cursor, as returned by {@link #getPosition},
+     * is not changed by this method.
+     * </p>
+     *
+     * @param position The zero-based index of the first row to copy into the window.
+     * @param window The window to fill.
      */
-    void fillWindow(int pos, CursorWindow winow);
+    void fillWindow(int position, CursorWindow window);
 
     /**
      * This function is called every time the cursor is successfully scrolled
      * to a new position, giving the subclass a chance to update any state it
-     * may have. If it returns false the move function will also do so and the
+     * may have.  If it returns false the move function will also do so and the
      * cursor will scroll to the beforeFirst position.
+     * <p>
+     * This function should be called by methods such as {@link #moveToPosition(int)},
+     * so it will typically not be called from outside of the cursor class itself.
+     * </p>
      *
-     * @param oldPosition the position that we're moving from
-     * @param newPosition the position that we're moving to
-     * @return true if the move is successful, false otherwise
+     * @param oldPosition The position that we're moving from.
+     * @param newPosition The position that we're moving to.
+     * @return True if the move is successful, false otherwise.
      */
     boolean onMove(int oldPosition, int newPosition); 
-    
 }
diff --git a/core/java/android/database/CrossProcessCursorWrapper.java b/core/java/android/database/CrossProcessCursorWrapper.java
new file mode 100644
index 0000000..8c250b8
--- /dev/null
+++ b/core/java/android/database/CrossProcessCursorWrapper.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package android.database;
+
+import android.database.CrossProcessCursor;
+import android.database.Cursor;
+import android.database.CursorWindow;
+import android.database.CursorWrapper;
+
+/**
+ * Cursor wrapper that implements {@link CrossProcessCursor}.
+ * <p>
+ * If the wrapper cursor implemented {@link CrossProcessCursor}, then delegates
+ * {@link #fillWindow}, {@link #getWindow()} and {@link #onMove} to it.  Otherwise,
+ * provides default implementations of these methods that traverse the contents
+ * of the cursor similar to {@link AbstractCursor#fillWindow}.
+ * </p><p>
+ * This wrapper can be used to adapt an ordinary {@link Cursor} into a
+ * {@link CrossProcessCursor}.
+ * </p>
+ */
+public class CrossProcessCursorWrapper extends CursorWrapper implements CrossProcessCursor {
+    /**
+     * Creates a cross process cursor wrapper.
+     * @param cursor The underlying cursor to wrap.
+     */
+    public CrossProcessCursorWrapper(Cursor cursor) {
+        super(cursor);
+    }
+
+    @Override
+    public void fillWindow(int position, CursorWindow window) {
+        if (mCursor instanceof CrossProcessCursor) {
+            final CrossProcessCursor crossProcessCursor = (CrossProcessCursor)mCursor;
+            crossProcessCursor.fillWindow(position, window);
+            return;
+        }
+
+        DatabaseUtils.cursorFillWindow(mCursor, position, window);
+    }
+
+    @Override
+    public CursorWindow getWindow() {
+        if (mCursor instanceof CrossProcessCursor) {
+            final CrossProcessCursor crossProcessCursor = (CrossProcessCursor)mCursor;
+            return crossProcessCursor.getWindow();
+        }
+
+        return null;
+    }
+
+    @Override
+    public boolean onMove(int oldPosition, int newPosition) {
+        if (mCursor instanceof CrossProcessCursor) {
+            final CrossProcessCursor crossProcessCursor = (CrossProcessCursor)mCursor;
+            return crossProcessCursor.onMove(oldPosition, newPosition);
+        }
+
+        return true;
+    }
+}
diff --git a/core/java/android/database/CursorToBulkCursorAdaptor.java b/core/java/android/database/CursorToBulkCursorAdaptor.java
index dd2c9b7..215035d 100644
--- a/core/java/android/database/CursorToBulkCursorAdaptor.java
+++ b/core/java/android/database/CursorToBulkCursorAdaptor.java
@@ -25,9 +25,9 @@
 /**
  * Wraps a BulkCursor around an existing Cursor making it remotable.
  * <p>
- * If the wrapped cursor is a {@link AbstractWindowedCursor} then it owns
- * the cursor window.  Otherwise, the adaptor takes ownership of the
- * cursor itself and ensures it gets closed as needed during deactivation
+ * If the wrapped cursor returns non-null from {@link CrossProcessCursor#getWindow}
+ * then it is assumed to own the window.  Otherwise, the adaptor provides a
+ * window to be filled and ensures it gets closed as needed during deactivation
  * and requeries.
  * </p>
  *
@@ -48,12 +48,11 @@
     private CrossProcessCursor mCursor;
 
     /**
-     * The cursor window used by the cross process cursor.
-     * This field is always null for abstract windowed cursors since they are responsible
-     * for managing the lifetime of their window.
+     * The cursor window that was filled by the cross process cursor in the
+     * case where the cursor does not support getWindow.
+     * This field is only ever non-null when the window has actually be filled.
      */
-    private CursorWindow mWindowForNonWindowedCursor;
-    private boolean mWindowForNonWindowedCursorWasFilled;
+    private CursorWindow mFilledWindow;
 
     private static final class ContentObserverProxy extends ContentObserver {
         protected IContentObserver mRemote;
@@ -90,11 +89,10 @@
 
     public CursorToBulkCursorAdaptor(Cursor cursor, IContentObserver observer,
             String providerName) {
-        try {
-            mCursor = (CrossProcessCursor) cursor;
-        } catch (ClassCastException e) {
-            throw new UnsupportedOperationException(
-                    "Only CrossProcessCursor cursors are supported across process for now", e);
+        if (cursor instanceof CrossProcessCursor) {
+            mCursor = (CrossProcessCursor)cursor;
+        } else {
+            mCursor = new CrossProcessCursorWrapper(cursor);
         }
         mProviderName = providerName;
 
@@ -103,11 +101,10 @@
         }
     }
 
-    private void closeWindowForNonWindowedCursorLocked() {
-        if (mWindowForNonWindowedCursor != null) {
-            mWindowForNonWindowedCursor.close();
-            mWindowForNonWindowedCursor = null;
-            mWindowForNonWindowedCursorWasFilled = false;
+    private void closeFilledWindowLocked() {
+        if (mFilledWindow != null) {
+            mFilledWindow.close();
+            mFilledWindow = null;
         }
     }
 
@@ -118,7 +115,7 @@
             mCursor = null;
         }
 
-        closeWindowForNonWindowedCursorLocked();
+        closeFilledWindowLocked();
     }
 
     private void throwIfCursorIsClosed() {
@@ -139,30 +136,24 @@
         synchronized (mLock) {
             throwIfCursorIsClosed();
 
-            CursorWindow window;
-            if (mCursor instanceof AbstractWindowedCursor) {
-                AbstractWindowedCursor windowedCursor = (AbstractWindowedCursor)mCursor;
-                window = windowedCursor.getWindow();
-                if (window == null) {
-                    window = new CursorWindow(mProviderName, false /*localOnly*/);
-                    windowedCursor.setWindow(window);
-                }
+            if (!mCursor.moveToPosition(startPos)) {
+                closeFilledWindowLocked();
+                return null;
+            }
 
-                mCursor.moveToPosition(startPos);
+            CursorWindow window = mCursor.getWindow();
+            if (window != null) {
+                closeFilledWindowLocked();
             } else {
-                window = mWindowForNonWindowedCursor;
+                window = mFilledWindow;
                 if (window == null) {
-                    window = new CursorWindow(mProviderName, false /*localOnly*/);
-                    mWindowForNonWindowedCursor = window;
-                }
-
-                mCursor.moveToPosition(startPos);
-
-                if (!mWindowForNonWindowedCursorWasFilled
-                        || startPos < window.getStartPosition()
-                        || startPos >= window.getStartPosition() + window.getNumRows()) {
+                    mFilledWindow = new CursorWindow(mProviderName);
+                    window = mFilledWindow;
                     mCursor.fillWindow(startPos, window);
-                    mWindowForNonWindowedCursorWasFilled = true;
+                } else if (startPos < window.getStartPosition()
+                        || startPos >= window.getStartPosition() + window.getNumRows()) {
+                    window.clear();
+                    mCursor.fillWindow(startPos, window);
                 }
             }
 
@@ -211,7 +202,7 @@
                 mCursor.deactivate();
             }
 
-            closeWindowForNonWindowedCursorLocked();
+            closeFilledWindowLocked();
         }
     }
 
@@ -227,7 +218,7 @@
         synchronized (mLock) {
             throwIfCursorIsClosed();
 
-            closeWindowForNonWindowedCursorLocked();
+            closeFilledWindowLocked();
 
             try {
                 if (!mCursor.requery()) {
diff --git a/core/java/android/database/CursorWindow.java b/core/java/android/database/CursorWindow.java
index a18a721..9c93324 100644
--- a/core/java/android/database/CursorWindow.java
+++ b/core/java/android/database/CursorWindow.java
@@ -31,8 +31,8 @@
 /**
  * A buffer containing multiple cursor rows.
  * <p>
- * A {@link CursorWindow} is read-write when created and used locally.  When sent
- * to a remote process (by writing it to a {@link Parcel}), the remote process
+ * A {@link CursorWindow} is read-write when initially created and used locally.
+ * When sent to a remote process (by writing it to a {@link Parcel}), the remote process
  * receives a read-only view of the cursor window.  Typically the cursor window
  * will be allocated by the producer, filled with data, and then sent to the
  * consumer for reading.
@@ -58,8 +58,7 @@
 
     private final CloseGuard mCloseGuard = CloseGuard.get();
 
-    private static native int nativeCreate(String name,
-            int cursorWindowSize, boolean localOnly);
+    private static native int nativeCreate(String name, int cursorWindowSize);
     private static native int nativeCreateFromParcel(Parcel parcel);
     private static native void nativeDispose(int windowPtr);
     private static native void nativeWriteToParcel(int windowPtr, Parcel parcel);
@@ -93,14 +92,10 @@
      * </p>
      *
      * @param name The name of the cursor window, or null if none.
-     * @param localWindow True if this window will be used in this process only,
-     * false if it might be sent to another processes.
-     *
-     * @hide
      */
-    public CursorWindow(String name, boolean localWindow) {
+    public CursorWindow(String name) {
         mStartPos = 0;
-        mWindowPtr = nativeCreate(name, sCursorWindowSize, localWindow);
+        mWindowPtr = nativeCreate(name, sCursorWindowSize);
         if (mWindowPtr == 0) {
             throw new CursorWindowAllocationException("Cursor window allocation of " +
                     (sCursorWindowSize / 1024) + " kb failed. " + printStats());
@@ -117,10 +112,14 @@
      * </p>
      *
      * @param localWindow True if this window will be used in this process only,
-     * false if it might be sent to another processes.
+     * false if it might be sent to another processes.  This argument is ignored.
+     *
+     * @deprecated There is no longer a distinction between local and remote
+     * cursor windows.  Use the {@link #CursorWindow(String)} constructor instead.
      */
+    @Deprecated
     public CursorWindow(boolean localWindow) {
-        this(null, localWindow);
+        this((String)null);
     }
 
     private CursorWindow(Parcel source) {
@@ -272,8 +271,7 @@
      * Returns true if the field at the specified row and column index
      * has type {@link Cursor#FIELD_TYPE_NULL}.
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return True if the field has type {@link Cursor#FIELD_TYPE_NULL}.
      * @deprecated Use {@link #getType(int, int)} instead.
@@ -287,8 +285,7 @@
      * Returns true if the field at the specified row and column index
      * has type {@link Cursor#FIELD_TYPE_BLOB} or {@link Cursor#FIELD_TYPE_NULL}.
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return True if the field has type {@link Cursor#FIELD_TYPE_BLOB} or
      * {@link Cursor#FIELD_TYPE_NULL}.
@@ -304,8 +301,7 @@
      * Returns true if the field at the specified row and column index
      * has type {@link Cursor#FIELD_TYPE_INTEGER}.
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return True if the field has type {@link Cursor#FIELD_TYPE_INTEGER}.
      * @deprecated Use {@link #getType(int, int)} instead.
@@ -319,8 +315,7 @@
      * Returns true if the field at the specified row and column index
      * has type {@link Cursor#FIELD_TYPE_FLOAT}.
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return True if the field has type {@link Cursor#FIELD_TYPE_FLOAT}.
      * @deprecated Use {@link #getType(int, int)} instead.
@@ -334,8 +329,7 @@
      * Returns true if the field at the specified row and column index
      * has type {@link Cursor#FIELD_TYPE_STRING} or {@link Cursor#FIELD_TYPE_NULL}.
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return True if the field has type {@link Cursor#FIELD_TYPE_STRING}
      * or {@link Cursor#FIELD_TYPE_NULL}.
@@ -360,8 +354,7 @@
      * </ul>
      * </p>
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return The field type.
      */
@@ -391,8 +384,7 @@
      * </ul>
      * </p>
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return The value of the field as a byte array.
      */
@@ -427,8 +419,7 @@
      * </ul>
      * </p>
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return The value of the field as a string.
      */
@@ -466,8 +457,7 @@
      * </ul>
      * </p>
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @param buffer The {@link CharArrayBuffer} to hold the string.  It is automatically
      * resized if the requested string is larger than the buffer's current capacity.
@@ -502,8 +492,7 @@
      * </ul>
      * </p>
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return The value of the field as a <code>long</code>.
      */
@@ -535,8 +524,7 @@
      * </ul>
      * </p>
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return The value of the field as a <code>double</code>.
      */
@@ -557,8 +545,7 @@
      * result to <code>short</code>.
      * </p>
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return The value of the field as a <code>short</code>.
      */
@@ -574,8 +561,7 @@
      * result to <code>int</code>.
      * </p>
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return The value of the field as an <code>int</code>.
      */
@@ -591,8 +577,7 @@
      * result to <code>float</code>.
      * </p>
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return The value of the field as an <code>float</code>.
      */
@@ -604,8 +589,7 @@
      * Copies a byte array into the field at the specified row and column index.
      *
      * @param value The value to store.
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return True if successful.
      */
@@ -622,8 +606,7 @@
      * Copies a string into the field at the specified row and column index.
      *
      * @param value The value to store.
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return True if successful.
      */
@@ -640,8 +623,7 @@
      * Puts a long integer into the field at the specified row and column index.
      *
      * @param value The value to store.
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return True if successful.
      */
@@ -659,8 +641,7 @@
      * specified row and column index.
      *
      * @param value The value to store.
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return True if successful.
      */
@@ -676,8 +657,7 @@
     /**
      * Puts a null value into the field at the specified row and column index.
      *
-     * @param row The zero-based row index, relative to the cursor window's
-     * start position ({@link #getStartPosition()}).
+     * @param row The zero-based row index.
      * @param column The zero-based column index.
      * @return True if successful.
      */
diff --git a/core/java/android/database/CursorWrapper.java b/core/java/android/database/CursorWrapper.java
index 320733e..7baeb8c 100644
--- a/core/java/android/database/CursorWrapper.java
+++ b/core/java/android/database/CursorWrapper.java
@@ -25,9 +25,13 @@
  * use for this class is to extend a cursor while overriding only a subset of its methods.
  */
 public class CursorWrapper implements Cursor {
+    /** @hide */
+    protected final Cursor mCursor;
 
-    private final Cursor mCursor;
-
+    /**
+     * Creates a cursor wrapper.
+     * @param cursor The underlying cursor to wrap.
+     */
     public CursorWrapper(Cursor cursor) {
         mCursor = cursor;
     }
diff --git a/core/java/android/database/DatabaseUtils.java b/core/java/android/database/DatabaseUtils.java
index 8e6f699..a10ca15 100644
--- a/core/java/android/database/DatabaseUtils.java
+++ b/core/java/android/database/DatabaseUtils.java
@@ -237,7 +237,8 @@
             return Cursor.FIELD_TYPE_BLOB;
         } else if (obj instanceof Float || obj instanceof Double) {
             return Cursor.FIELD_TYPE_FLOAT;
-        } else if (obj instanceof Long || obj instanceof Integer) {
+        } else if (obj instanceof Long || obj instanceof Integer
+                || obj instanceof Short || obj instanceof Byte) {
             return Cursor.FIELD_TYPE_INTEGER;
         } else {
             return Cursor.FIELD_TYPE_STRING;
@@ -245,6 +246,82 @@
     }
 
     /**
+     * Fills the specified cursor window by iterating over the contents of the cursor.
+     * The window is filled until the cursor is exhausted or the window runs out
+     * of space.
+     *
+     * The original position of the cursor is left unchanged by this operation.
+     *
+     * @param cursor The cursor that contains the data to put in the window.
+     * @param position The start position for filling the window.
+     * @param window The window to fill.
+     * @hide
+     */
+    public static void cursorFillWindow(final Cursor cursor,
+            int position, final CursorWindow window) {
+        if (position < 0 || position >= cursor.getCount()) {
+            return;
+        }
+        window.acquireReference();
+        try {
+            final int oldPos = cursor.getPosition();
+            final int numColumns = cursor.getColumnCount();
+            window.clear();
+            window.setStartPosition(position);
+            window.setNumColumns(numColumns);
+            if (cursor.moveToPosition(position)) {
+                do {
+                    if (!window.allocRow()) {
+                        break;
+                    }
+                    for (int i = 0; i < numColumns; i++) {
+                        final int type = cursor.getType(i);
+                        final boolean success;
+                        switch (type) {
+                            case Cursor.FIELD_TYPE_NULL:
+                                success = window.putNull(position, i);
+                                break;
+
+                            case Cursor.FIELD_TYPE_INTEGER:
+                                success = window.putLong(cursor.getLong(i), position, i);
+                                break;
+
+                            case Cursor.FIELD_TYPE_FLOAT:
+                                success = window.putDouble(cursor.getDouble(i), position, i);
+                                break;
+
+                            case Cursor.FIELD_TYPE_BLOB: {
+                                final byte[] value = cursor.getBlob(i);
+                                success = value != null ? window.putBlob(value, position, i)
+                                        : window.putNull(position, i);
+                                break;
+                            }
+
+                            default: // assume value is convertible to String
+                            case Cursor.FIELD_TYPE_STRING: {
+                                final String value = cursor.getString(i);
+                                success = value != null ? window.putString(value, position, i)
+                                        : window.putNull(position, i);
+                                break;
+                            }
+                        }
+                        if (!success) {
+                            window.freeLastRow();
+                            break;
+                        }
+                    }
+                    position += 1;
+                } while (cursor.moveToNext());
+            }
+            cursor.moveToPosition(oldPos);
+        } catch (IllegalStateException e){
+            // simply ignore it
+        } finally {
+            window.releaseReference();
+        }
+    }
+
+    /**
      * Appends an SQL string to the given StringBuilder, including the opening
      * and closing single quotes. Any single quotes internal to sqlString will
      * be escaped.
diff --git a/core/java/android/database/sqlite/SQLiteCursor.java b/core/java/android/database/sqlite/SQLiteCursor.java
index a1c36e2..9574300 100644
--- a/core/java/android/database/sqlite/SQLiteCursor.java
+++ b/core/java/android/database/sqlite/SQLiteCursor.java
@@ -155,7 +155,7 @@
     }
 
     private void fillWindow(int startPos) {
-        clearOrCreateLocalWindow(getDatabase().getPath());
+        clearOrCreateWindow(getDatabase().getPath());
         mWindow.setStartPosition(startPos);
         int count = getQuery().fillWindow(mWindow);
         if (startPos == 0) { // fillWindow returns count(*) only for startPos = 0
diff --git a/core/java/android/hardware/Camera.java b/core/java/android/hardware/Camera.java
index 9bd4a3b..d338764 100644
--- a/core/java/android/hardware/Camera.java
+++ b/core/java/android/hardware/Camera.java
@@ -337,7 +337,7 @@
      * Camera objects are locked by default unless {@link #unlock()} is
      * called.  Normally {@link #reconnect()} is used instead.
      *
-     * <p>Since API level 13, camera is automatically locked for applications in
+     * <p>Since API level 14, camera is automatically locked for applications in
      * {@link android.media.MediaRecorder#start()}. Applications can use the
      * camera (ex: zoom) after recording starts. There is no need to call this
      * after recording starts or stops.
@@ -356,7 +356,7 @@
      * which will re-acquire the lock and allow you to continue using the
      * camera.
      *
-     * <p>Since API level 13, camera is automatically locked for applications in
+     * <p>Since API level 14, camera is automatically locked for applications in
      * {@link android.media.MediaRecorder#start()}. Applications can use the
      * camera (ex: zoom) after recording starts. There is no need to call this
      * after recording starts or stops.
@@ -781,7 +781,7 @@
          * @see android.hardware.Camera.Parameters#setAutoWhiteBalanceLock(boolean)
          */
         void onAutoFocus(boolean success, Camera camera);
-    };
+    }
 
     /**
      * Starts camera auto-focus and registers a callback function to run when
@@ -804,11 +804,17 @@
      * {@link android.hardware.Camera.Parameters#FLASH_MODE_OFF}, flash may be
      * fired during auto-focus, depending on the driver and camera hardware.<p>
      *
-     * Auto-exposure lock {@link android.hardware.Camera.Parameters#getAutoExposureLock()}
+     * <p>Auto-exposure lock {@link android.hardware.Camera.Parameters#getAutoExposureLock()}
      * and auto-white balance locks {@link android.hardware.Camera.Parameters#getAutoWhiteBalanceLock()}
      * do not change during and after autofocus. But auto-focus routine may stop
      * auto-exposure and auto-white balance transiently during focusing.
      *
+     * <p>Stopping preview with {@link #stopPreview()}, or triggering still
+     * image capture with {@link #takePicture(Camera.ShutterCallback,
+     * Camera.PictureCallback, Camera.PictureCallback)}, will not change the
+     * the focus position. Applications must call cancelAutoFocus to reset the
+     * focus.</p>
+     *
      * @param cb the callback to run
      * @see #cancelAutoFocus()
      * @see android.hardware.Camera.Parameters#setAutoExposureLock(boolean)
@@ -1059,8 +1065,7 @@
         /**
          * Notify the listener of the detected faces in the preview frame.
          *
-         * @param faces The detected faces in a list sorted by the confidence score.
-         *              The highest scored face is the first element.
+         * @param faces The detected faces in a list
          * @param camera  The {@link Camera} service object
          */
         void onFaceDetection(Face[] faces, Camera camera);
@@ -1121,7 +1126,7 @@
 
     /**
      * Information about a face identified through camera face detection.
-     * 
+     *
      * <p>When face detection is used with a camera, the {@link FaceDetectionListener} returns a
      * list of face objects for use in focusing and metering.</p>
      *
@@ -1140,7 +1145,9 @@
          * the field of view. For example, suppose the size of the viewfinder UI
          * is 800x480. The rect passed from the driver is (-1000, -1000, 0, 0).
          * The corresponding viewfinder rect should be (0, 0, 400, 240). The
-         * width and height of the rect will not be 0 or negative.
+         * width and height of the rect will not be 0 or negative. The
+         * coordinates can be smaller than -1000 or bigger than 1000. But at
+         * least one vertex will be within (-1000, -1000) and (1000, 1000).
          *
          * <p>The direction is relative to the sensor orientation, that is, what
          * the sensor sees. The direction is not affected by the rotation or
@@ -1653,9 +1660,18 @@
          * call {@link #takePicture(Camera.ShutterCallback,
          * Camera.PictureCallback, Camera.PictureCallback)} in this mode but the
          * subject may not be in focus. Auto focus starts when the parameter is
-         * set. Applications should not call {@link
-         * #autoFocus(AutoFocusCallback)} in this mode. To stop continuous
-         * focus, applications should change the focus mode to other modes.
+         * set.
+         *
+         * <p>Since API level 14, applications can call {@link
+         * #autoFocus(AutoFocusCallback)} in this mode. The focus callback will
+         * immediately return with a boolean that indicates whether the focus is
+         * sharp or not. The focus position is locked after autoFocus call. If
+         * applications want to resume the continuous focus, cancelAutoFocus
+         * must be called. Restarting the preview will not resume the continuous
+         * autofocus. To stop continuous focus, applications should change the
+         * focus mode to other modes.
+         *
+         * @see #FOCUS_MODE_CONTINUOUS_PICTURE
          */
         public static final String FOCUS_MODE_CONTINUOUS_VIDEO = "continuous-video";
 
@@ -1663,13 +1679,17 @@
          * Continuous auto focus mode intended for taking pictures. The camera
          * continuously tries to focus. The speed of focus change is more
          * aggressive than {@link #FOCUS_MODE_CONTINUOUS_VIDEO}. Auto focus
-         * starts when the parameter is set. If applications call {@link
-         * #autoFocus(AutoFocusCallback)} in this mode, the focus callback will
-         * immediately return with a boolean that indicates whether the focus is
-         * sharp or not. The apps can then decide if they want to take a picture
-         * immediately or to change the focus mode to auto, and run a full
-         * autofocus cycle. To stop continuous focus, applications should change
-         * the focus mode to other modes.
+         * starts when the parameter is set.
+         *
+         * <p>If applications call {@link #autoFocus(AutoFocusCallback)} in this
+         * mode, the focus callback will immediately return with a boolean that
+         * indicates whether the focus is sharp or not. The apps can then decide
+         * if they want to take a picture immediately or to change the focus
+         * mode to auto, and run a full autofocus cycle. The focus position is
+         * locked after autoFocus call. If applications want to resume the
+         * continuous focus, cancelAutoFocus must be called. Restarting the
+         * preview will not resume the continuous autofocus. To stop continuous
+         * focus, applications should change the focus mode to other modes.
          *
          * @see #FOCUS_MODE_CONTINUOUS_VIDEO
          */
@@ -3061,8 +3081,9 @@
          * when using zoom.</p>
          *
          * <p>Focus area only has effect if the current focus mode is
-         * {@link #FOCUS_MODE_AUTO}, {@link #FOCUS_MODE_MACRO}, or
-         * {@link #FOCUS_MODE_CONTINUOUS_VIDEO}.</p>
+         * {@link #FOCUS_MODE_AUTO}, {@link #FOCUS_MODE_MACRO},
+         * {@link #FOCUS_MODE_CONTINUOUS_VIDEO}, or
+         * {@link #FOCUS_MODE_CONTINUOUS_PICTURE}.</p>
          *
          * @return a list of current focus areas
          */
diff --git a/core/java/android/nfc/NfcActivityManager.java b/core/java/android/nfc/NfcActivityManager.java
index da878d4..5fe58e9 100644
--- a/core/java/android/nfc/NfcActivityManager.java
+++ b/core/java/android/nfc/NfcActivityManager.java
@@ -162,6 +162,7 @@
     synchronized void maybeRemoveState(Activity activity, NfcActivityState state) {
         if (state.ndefMessage == null && state.ndefMessageCallback == null &&
                 state.onNdefPushCompleteCallback == null) {
+            NfcFragment.remove(activity);
             mNfcState.remove(activity);
         }
     }
diff --git a/core/java/android/os/storage/IMountService.java b/core/java/android/os/storage/IMountService.java
index d1dc6e5..0640d7e 100644
--- a/core/java/android/os/storage/IMountService.java
+++ b/core/java/android/os/storage/IMountService.java
@@ -658,6 +658,24 @@
                 return _result;
             }
 
+            @Override
+            public int verifyEncryptionPassword(String password) throws RemoteException {
+                Parcel _data = Parcel.obtain();
+                Parcel _reply = Parcel.obtain();
+                int _result;
+                try {
+                    _data.writeInterfaceToken(DESCRIPTOR);
+                    _data.writeString(password);
+                    mRemote.transact(Stub.TRANSACTION_verifyEncryptionPassword, _data, _reply, 0);
+                    _reply.readException();
+                    _result = _reply.readInt();
+                } finally {
+                    _reply.recycle();
+                    _data.recycle();
+                }
+                return _result;
+            }
+
             public Parcelable[] getVolumeList() throws RemoteException {
                 Parcel _data = Parcel.obtain();
                 Parcel _reply = Parcel.obtain();
@@ -761,6 +779,8 @@
 
         static final int TRANSACTION_getEncryptionState = IBinder.FIRST_CALL_TRANSACTION + 31;
 
+        static final int TRANSACTION_verifyEncryptionPassword = IBinder.FIRST_CALL_TRANSACTION + 32;
+
         /**
          * Cast an IBinder object into an IMountService interface, generating a
          * proxy if needed.
@@ -1286,6 +1306,12 @@
     public int changeEncryptionPassword(String password) throws RemoteException;
 
     /**
+     * Verify the encryption password against the stored volume.  This method
+     * may only be called by the system process.
+     */
+    public int verifyEncryptionPassword(String password) throws RemoteException;
+
+    /**
      * Returns list of all mountable volumes.
      */
     public Parcelable[] getVolumeList() throws RemoteException;
diff --git a/core/java/android/provider/ContactsContract.java b/core/java/android/provider/ContactsContract.java
index 8483b4f..4bc0892 100644
--- a/core/java/android/provider/ContactsContract.java
+++ b/core/java/android/provider/ContactsContract.java
@@ -187,6 +187,59 @@
     public static final String DEFERRED_SNIPPETING_QUERY = "deferred_snippeting_query";
 
     /**
+     * <p>
+     * API for obtaining a pre-authorized version of a URI that normally requires special
+     * permission (beyond READ_CONTACTS) to read.  The caller obtaining the pre-authorized URI
+     * must already have the necessary permissions to access the URI; otherwise a
+     * {@link SecurityException} will be thrown.
+     * </p>
+     * <p>
+     * The authorized URI returned in the bundle contains an expiring token that allows the
+     * caller to execute the query without having the special permissions that would normally
+     * be required.
+     * </p>
+     * <p>
+     * This API does not access disk, and should be safe to invoke from the UI thread.
+     * </p>
+     * <p>
+     * Example usage:
+     * <pre>
+     * Uri profileUri = ContactsContract.Profile.CONTENT_VCARD_URI;
+     * Bundle uriBundle = new Bundle();
+     * uriBundle.putParcelable(ContactsContract.Authorization.KEY_URI_TO_AUTHORIZE, uri);
+     * Bundle authResponse = getContext().getContentResolver().call(
+     *         ContactsContract.AUTHORITY_URI,
+     *         ContactsContract.Authorization.AUTHORIZATION_METHOD,
+     *         null, // String arg, not used.
+     *         uriBundle);
+     * if (authResponse != null) {
+     *     Uri preauthorizedProfileUri = (Uri) authResponse.getParcelable(
+     *             ContactsContract.Authorization.KEY_AUTHORIZED_URI);
+     *     // This pre-authorized URI can be queried by a caller without READ_PROFILE
+     *     // permission.
+     * }
+     * </pre>
+     * </p>
+     * @hide
+     */
+    public static final class Authorization {
+        /**
+         * The method to invoke to create a pre-authorized URI out of the input argument.
+         */
+        public static final String AUTHORIZATION_METHOD = "authorize";
+
+        /**
+         * The key to set in the outbound Bundle with the URI that should be authorized.
+         */
+        public static final String KEY_URI_TO_AUTHORIZE = "uri_to_authorize";
+
+        /**
+         * The key to retrieve from the returned Bundle to obtain the pre-authorized URI.
+         */
+        public static final String KEY_AUTHORIZED_URI = "authorized_uri";
+    }
+
+    /**
      * @hide
      */
     public static final class Preferences {
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 3d2a3ce..5754e60 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -4053,6 +4053,14 @@
         public static final String PACKAGE_VERIFIER_TIMEOUT = "verifier_timeout";
 
         /**
+         * Duration in milliseconds before pre-authorized URIs for the contacts
+         * provider should expire.
+         * @hide
+         */
+        public static final String CONTACTS_PREAUTH_URI_EXPIRATION =
+                "contacts_preauth_uri_expiration";
+
+        /**
          * This are the settings to be backed up.
          *
          * NOTE: Settings are backed up and restored in the order they appear
diff --git a/core/java/android/speech/tts/TtsEngines.java b/core/java/android/speech/tts/TtsEngines.java
index bb72bea..2706bc7 100644
--- a/core/java/android/speech/tts/TtsEngines.java
+++ b/core/java/android/speech/tts/TtsEngines.java
@@ -344,7 +344,10 @@
         String v1Locale = lang;
         if (!TextUtils.isEmpty(country)) {
             v1Locale += LOCALE_DELIMITER + country;
+        } else {
+            return v1Locale;
         }
+
         if (!TextUtils.isEmpty(variant)) {
             v1Locale += LOCALE_DELIMITER + variant;
         }
@@ -355,8 +358,28 @@
     private String getDefaultLocale() {
         final Locale locale = Locale.getDefault();
 
-        return locale.getISO3Language() + LOCALE_DELIMITER + locale.getISO3Country() +
-                LOCALE_DELIMITER + locale.getVariant();
+        // Note that the default locale might have an empty variant
+        // or language, and we take care that the construction is
+        // the same as {@link #getV1Locale} i.e no trailing delimiters
+        // or spaces.
+        String defaultLocale = locale.getISO3Language();
+        if (TextUtils.isEmpty(defaultLocale)) {
+            Log.w(TAG, "Default locale is empty.");
+            return "";
+        }
+
+        if (!TextUtils.isEmpty(locale.getISO3Country())) {
+            defaultLocale += LOCALE_DELIMITER + locale.getISO3Country();
+        } else {
+            // Do not allow locales of the form lang--variant with
+            // an empty country.
+            return defaultLocale;
+        }
+        if (!TextUtils.isEmpty(locale.getVariant())) {
+            defaultLocale += LOCALE_DELIMITER + locale.getVariant();
+        }
+
+        return defaultLocale;
     }
 
     /**
diff --git a/core/java/android/text/method/ArrowKeyMovementMethod.java b/core/java/android/text/method/ArrowKeyMovementMethod.java
index e93039b..4ec4bc4 100644
--- a/core/java/android/text/method/ArrowKeyMovementMethod.java
+++ b/core/java/android/text/method/ArrowKeyMovementMethod.java
@@ -197,16 +197,18 @@
     @Override
     protected boolean leftWord(TextView widget, Spannable buffer) {
         final int selectionEnd = widget.getSelectionEnd();
-        mWordIterator.setCharSequence(buffer, selectionEnd, selectionEnd);
-        return Selection.moveToPreceding(buffer, mWordIterator, isSelecting(buffer));
+        final WordIterator wordIterator = widget.getWordIterator();
+        wordIterator.setCharSequence(buffer, selectionEnd, selectionEnd);
+        return Selection.moveToPreceding(buffer, wordIterator, isSelecting(buffer));
     }
 
     /** {@hide} */
     @Override
     protected boolean rightWord(TextView widget, Spannable buffer) {
         final int selectionEnd = widget.getSelectionEnd();
-        mWordIterator.setCharSequence(buffer, selectionEnd, selectionEnd);
-        return Selection.moveToFollowing(buffer, mWordIterator, isSelecting(buffer));
+        final WordIterator wordIterator = widget.getWordIterator();
+        wordIterator.setCharSequence(buffer, selectionEnd, selectionEnd);
+        return Selection.moveToFollowing(buffer, wordIterator, isSelecting(buffer));
     }
 
     @Override
@@ -322,8 +324,6 @@
         return sInstance;
     }
 
-    private WordIterator mWordIterator = new WordIterator();
-
     private static final Object LAST_TAP_DOWN = new Object();
     private static ArrowKeyMovementMethod sInstance;
 }
diff --git a/core/java/android/view/ContextMenu.java b/core/java/android/view/ContextMenu.java
index dd1d7db..decabcb 100644
--- a/core/java/android/view/ContextMenu.java
+++ b/core/java/android/view/ContextMenu.java
@@ -29,6 +29,12 @@
  * To show a context menu on long click, most clients will want to call
  * {@link Activity#registerForContextMenu} and override
  * {@link Activity#onCreateContextMenu}.
+ *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For information about creating menus, read the
+ * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
+ * </div>
  */
 public interface ContextMenu extends Menu {
     /**
diff --git a/core/java/android/view/DragEvent.java b/core/java/android/view/DragEvent.java
index 8f491ef..f559e21 100644
--- a/core/java/android/view/DragEvent.java
+++ b/core/java/android/view/DragEvent.java
@@ -114,6 +114,12 @@
  *  {@link android.view.DragEvent#writeToParcel(Parcel,int)}, and
  *  {@link android.view.DragEvent#toString()} methods always return valid data.
  * </p>
+ *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For a guide to implementing drag and drop features, read the
+ * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
+ * </div>
  */
 public class DragEvent implements Parcelable {
     private static final boolean TRACK_RECYCLED_LOCATION = false;
diff --git a/core/java/android/view/Menu.java b/core/java/android/view/Menu.java
index 97825e6..7157bc5 100644
--- a/core/java/android/view/Menu.java
+++ b/core/java/android/view/Menu.java
@@ -41,6 +41,12 @@
  * item check marks are discouraged.
  * <li><b>Sub menus</b>: Do not support item icons, or nested sub menus.
  * </ol>
+ *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For more information about creating menus, read the
+ * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
+ * </div>
  */
 public interface Menu {
 
diff --git a/core/java/android/view/MenuItem.java b/core/java/android/view/MenuItem.java
index ccd8353..2dfbcb5 100644
--- a/core/java/android/view/MenuItem.java
+++ b/core/java/android/view/MenuItem.java
@@ -29,6 +29,12 @@
  * methods.
  * <p>
  * For a feature set of specific menu types, see {@link Menu}.
+ *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For information about creating menus, read the
+ * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
+ * </div>
  */
 public interface MenuItem {
     /*
diff --git a/core/java/android/view/SubMenu.java b/core/java/android/view/SubMenu.java
index e981486..196a183 100644
--- a/core/java/android/view/SubMenu.java
+++ b/core/java/android/view/SubMenu.java
@@ -22,6 +22,12 @@
  * Subclass of {@link Menu} for sub menus.
  * <p>
  * Sub menus do not support item icons, or nested sub menus.
+ *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For information about creating menus, read the
+ * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
+ * </div>
  */
 
 public interface SubMenu extends Menu {
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 4385d5a..a2f9b36 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -418,7 +418,7 @@
  * <h3>Drawing</h3>
  * <p>
  * Drawing is handled by walking the tree and rendering each view that
- * intersects the the invalid region. Because the tree is traversed in-order,
+ * intersects the invalid region. Because the tree is traversed in-order,
  * this means that parents will draw before (i.e., behind) their children, with
  * siblings drawn in the order they appear in the tree.
  * If you set a background drawable for a View, then the View will draw it for you
@@ -1891,12 +1891,10 @@
      * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
      * out of the public fields to keep the undefined bits out of the developer's way.
      *
-     * Flag to hide only the navigation buttons.  Don't use this
+     * Flag to hide only the home button.  Don't use this
      * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
-     *
-     * THIS DOES NOT DISABLE THE BACK BUTTON
      */
-    public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000;
+    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
 
     /**
      * @hide
@@ -1904,7 +1902,7 @@
      * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
      * out of the public fields to keep the undefined bits out of the developer's way.
      *
-     * Flag to hide only the back button.  Don't use this
+     * Flag to hide only the back button. Don't use this
      * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
      */
     public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
@@ -1922,6 +1920,28 @@
 
     /**
      * @hide
+     *
+     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
+     * out of the public fields to keep the undefined bits out of the developer's way.
+     *
+     * Flag to hide only the recent apps button. Don't use this
+     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
+     */
+    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
+
+    /**
+     * @hide
+     *
+     * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc.
+     *
+     * This hides HOME and RECENT and is provided for compatibility with interim implementations.
+     */
+    @Deprecated
+    public static final int STATUS_BAR_DISABLE_NAVIGATION = 
+            STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT;
+
+    /**
+     * @hide
      */
     public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
 
@@ -3810,7 +3830,10 @@
      * responsible for handling this call.
      * </p>
      *
-     * @param eventType The type of the event to send.
+     * @param eventType The type of the event to send, as defined by several types from
+     * {@link android.view.accessibility.AccessibilityEvent}, such as
+     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
+     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
      *
      * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
      * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
@@ -3923,27 +3946,28 @@
     /**
      * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
      * giving a chance to this View to populate the accessibility event with its
-     * text content. While the implementation is free to modify other event
-     * attributes this should be performed in
+     * text content. While this method is free to modify event
+     * attributes other than text content, doing so should normally be performed in
      * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
      * <p>
      * Example: Adding formatted date string to an accessibility event in addition
-     *          to the text added by the super implementation.
-     * </p><p><pre><code>
-     * public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
+     *          to the text added by the super implementation:
+     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
      *     super.onPopulateAccessibilityEvent(event);
      *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
      *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
      *         mCurrentDate.getTimeInMillis(), flags);
      *     event.getText().add(selectedDateUtterance);
-     * }
-     * </code></pre></p>
+     * }</pre>
      * <p>
      * If an {@link AccessibilityDelegate} has been specified via calling
      * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
      * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
      * is responsible for handling this call.
      * </p>
+     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
+     * information to the event, in case the default implementation has basic information to add.
+     * </p>
      *
      * @param event The accessibility event which to populate.
      *
@@ -3974,20 +3998,20 @@
      * the event.
      * <p>
      * Example: Setting the password property of an event in addition
-     *          to properties set by the super implementation.
-     * </p><p><pre><code>
-     * public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
-     *    super.onInitializeAccessibilityEvent(event);
-     *    event.setPassword(true);
-     * }
-     * </code></pre></p>
+     *          to properties set by the super implementation:
+     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
+     *     super.onInitializeAccessibilityEvent(event);
+     *     event.setPassword(true);
+     * }</pre>
      * <p>
      * If an {@link AccessibilityDelegate} has been specified via calling
      * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
      * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
      * is responsible for handling this call.
      * </p>
-     *
+     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
+     * information to the event, in case the default implementation has basic information to add.
+     * </p>
      * @param event The event to initialize.
      *
      * @see #sendAccessibilityEvent(int)
@@ -6159,8 +6183,7 @@
      * are delivered to the view under the pointer.  All other generic motion events are
      * delivered to the focused view.
      * </p>
-     * <code>
-     * public boolean onGenericMotionEvent(MotionEvent event) {
+     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
      *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
      *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
      *             // process the joystick movement...
@@ -6178,8 +6201,7 @@
      *         }
      *     }
      *     return super.onGenericMotionEvent(event);
-     * }
-     * </code>
+     * }</pre>
      *
      * @param event The generic motion event being processed.
      * @return True if the event was handled, false otherwise.
@@ -8344,7 +8366,7 @@
                         !((ViewGroup) mParent).isViewTransitioning(this));
     }
     /**
-     * Mark the the area defined by dirty as needing to be drawn. If the view is
+     * Mark the area defined by dirty as needing to be drawn. If the view is
      * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
      * in the future. This must be called from a UI thread. To call from a non-UI
      * thread, call {@link #postInvalidate()}.
@@ -8389,7 +8411,7 @@
     }
 
     /**
-     * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
+     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
      * The coordinates of the dirty rect are relative to the view.
      * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
      * will be called at some point in the future. This must be called from
@@ -13087,6 +13109,12 @@
      *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
      *  so that your application can draw the shadow image in the Canvas.
      * </p>
+     *
+     * <div class="special reference">
+     * <h3>Developer Guides</h3>
+     * <p>For a guide to implementing drag and drop features, read the
+     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
+     * </div>
      */
     public static class DragShadowBuilder {
         private final WeakReference<View> mView;
@@ -14078,6 +14106,12 @@
      * to this view.  The callback will be invoked before the hosting view's own
      * onDrag(event) method.  If the listener wants to fall back to the hosting view's
      * onDrag(event) behavior, it should return 'false' from this callback.
+     *
+     * <div class="special reference">
+     * <h3>Developer Guides</h3>
+     * <p>For a guide to implementing drag and drop features, read the
+     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
+     * </div>
      */
     public interface OnDragListener {
         /**
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 9266ae2..62b20b3 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -60,6 +60,12 @@
  * Also see {@link LayoutParams} for layout attributes.
  * </p>
  *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For more information about creating user interface layouts, read the
+ * <a href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts</a> developer
+ * guide.</p></div>
+ *
  * @attr ref android.R.styleable#ViewGroup_clipChildren
  * @attr ref android.R.styleable#ViewGroup_clipToPadding
  * @attr ref android.R.styleable#ViewGroup_layoutAnimation
@@ -5158,7 +5164,13 @@
      * </ul>
      * There are subclasses of LayoutParams for different subclasses of
      * ViewGroup. For example, AbsoluteLayout has its own subclass of
-     * LayoutParams which adds an X and Y value.
+     * LayoutParams which adds an X and Y value.</p>
+     *
+     * <div class="special reference">
+     * <h3>Developer Guides</h3>
+     * <p>For more information about creating user interface layouts, read the
+     * <a href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts</a> developer
+     * guide.</p></div>
      *
      * @attr ref android.R.styleable#ViewGroup_Layout_layout_height
      * @attr ref android.R.styleable#ViewGroup_Layout_layout_width
diff --git a/core/java/android/view/VolumePanel.java b/core/java/android/view/VolumePanel.java
index 122865e..83df8a5 100644
--- a/core/java/android/view/VolumePanel.java
+++ b/core/java/android/view/VolumePanel.java
@@ -97,6 +97,7 @@
     protected AudioService mAudioService;
     private boolean mRingIsSilent;
     private boolean mShowCombinedVolumes;
+    private boolean mVoiceCapable;
 
     /** Dialog containing all the sliders */
     private final Dialog mDialog;
@@ -117,40 +118,62 @@
     /** All the slider controls mapped by stream type */
     private HashMap<Integer,StreamControl> mStreamControls;
 
+    private enum StreamResources {
+        BluetoothSCOStream(AudioManager.STREAM_BLUETOOTH_SCO,
+                R.string.volume_icon_description_bluetooth,
+                R.drawable.ic_audio_bt,
+                R.drawable.ic_audio_bt,
+                false),
+        RingerStream(AudioManager.STREAM_RING,
+                R.string.volume_icon_description_ringer,
+                R.drawable.ic_audio_ring_notif,
+                R.drawable.ic_audio_ring_notif_mute,
+                false),
+        VoiceStream(AudioManager.STREAM_VOICE_CALL,
+                R.string.volume_icon_description_incall,
+                R.drawable.ic_audio_phone,
+                R.drawable.ic_audio_phone,
+                false),
+        AlarmStream(AudioManager.STREAM_ALARM,
+                R.string.volume_alarm,
+                R.drawable.ic_audio_alarm,
+                R.drawable.ic_audio_alarm_mute,
+                false),
+        MediaStream(AudioManager.STREAM_MUSIC,
+                R.string.volume_icon_description_media,
+                R.drawable.ic_audio_vol,
+                R.drawable.ic_audio_vol_mute,
+                true),
+        NotificationStream(AudioManager.STREAM_NOTIFICATION,
+                R.string.volume_icon_description_notification,
+                R.drawable.ic_audio_notification,
+                R.drawable.ic_audio_notification_mute,
+                true);
+
+        int streamType;
+        int descRes;
+        int iconRes;
+        int iconMuteRes;
+        // RING, VOICE_CALL & BLUETOOTH_SCO are hidden unless explicitly requested
+        boolean show;
+
+        StreamResources(int streamType, int descRes, int iconRes, int iconMuteRes, boolean show) {
+            this.streamType = streamType;
+            this.descRes = descRes;
+            this.iconRes = iconRes;
+            this.iconMuteRes = iconMuteRes;
+            this.show = show;
+        }
+    };
+
     // List of stream types and their order
-    // RING, VOICE_CALL & BLUETOOTH_SCO are hidden unless explicitly requested
-    private static final int [] STREAM_TYPES = {
-        AudioManager.STREAM_BLUETOOTH_SCO,
-        AudioManager.STREAM_RING,
-        AudioManager.STREAM_VOICE_CALL,
-        AudioManager.STREAM_MUSIC,
-        AudioManager.STREAM_NOTIFICATION
-    };
-
-    private static final int [] CONTENT_DESCRIPTIONS = {
-        R.string.volume_icon_description_bluetooth,
-        R.string.volume_icon_description_ringer,
-        R.string.volume_icon_description_incall,
-        R.string.volume_icon_description_media,
-        R.string.volume_icon_description_notification
-    };
-
-    // These icons need to correspond to the ones above.
-    private static final int [] STREAM_ICONS_NORMAL = {
-        R.drawable.ic_audio_bt,
-        R.drawable.ic_audio_ring_notif,
-        R.drawable.ic_audio_phone,
-        R.drawable.ic_audio_vol,
-        R.drawable.ic_audio_notification,
-    };
-
-    // These icons need to correspond to the ones above.
-    private static final int [] STREAM_ICONS_MUTED = {
-        R.drawable.ic_audio_bt,
-        R.drawable.ic_audio_ring_notif_mute,
-        R.drawable.ic_audio_phone,
-        R.drawable.ic_audio_vol_mute,
-        R.drawable.ic_audio_notification_mute,
+    private static final StreamResources[] STREAMS = {
+        StreamResources.BluetoothSCOStream,
+        StreamResources.RingerStream,
+        StreamResources.VoiceStream,
+        StreamResources.MediaStream,
+        StreamResources.NotificationStream,
+        StreamResources.AlarmStream
     };
 
     /** Object that contains data for each slider */
@@ -221,7 +244,8 @@
         mToneGenerators = new ToneGenerator[AudioSystem.getNumStreamTypes()];
         mVibrator = new Vibrator();
 
-        mShowCombinedVolumes = !context.getResources().getBoolean(R.bool.config_voice_capable);
+        mVoiceCapable = context.getResources().getBoolean(R.bool.config_voice_capable);
+        mShowCombinedVolumes = !mVoiceCapable;
         // If we don't want to show multiple volumes, hide the settings button and divider
         if (!mShowCombinedVolumes) {
             mMoreButton.setVisibility(View.GONE);
@@ -260,10 +284,14 @@
 
         LayoutInflater inflater = (LayoutInflater) mContext
                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-        mStreamControls = new HashMap<Integer,StreamControl>(STREAM_TYPES.length);
+        mStreamControls = new HashMap<Integer, StreamControl>(STREAMS.length);
         Resources res = mContext.getResources();
-        for (int i = 0; i < STREAM_TYPES.length; i++) {
-            final int streamType = STREAM_TYPES[i];
+        for (int i = 0; i < STREAMS.length; i++) {
+            StreamResources streamRes = STREAMS[i];
+            int streamType = streamRes.streamType;
+            if (mVoiceCapable && streamRes == StreamResources.NotificationStream) {
+                streamRes = StreamResources.RingerStream;
+            }
             StreamControl sc = new StreamControl();
             sc.streamType = streamType;
             sc.group = (ViewGroup) inflater.inflate(R.layout.volume_adjust_item, null);
@@ -273,9 +301,9 @@
                 sc.icon.setOnClickListener(this);
             }
             sc.icon.setTag(sc);
-            sc.icon.setContentDescription(res.getString(CONTENT_DESCRIPTIONS[i]));
-            sc.iconRes = STREAM_ICONS_NORMAL[i];
-            sc.iconMuteRes = STREAM_ICONS_MUTED[i];
+            sc.icon.setContentDescription(res.getString(streamRes.descRes));
+            sc.iconRes = streamRes.iconRes;
+            sc.iconMuteRes = streamRes.iconMuteRes;
             sc.icon.setImageResource(sc.iconRes);
             sc.seekbarView = (SeekBar) sc.group.findViewById(R.id.seekbar);
             int plusOne = (streamType == AudioSystem.STREAM_BLUETOOTH_SCO ||
@@ -307,13 +335,10 @@
     private void addOtherVolumes() {
         if (!mShowCombinedVolumes) return;
 
-        for (int i = 0; i < STREAM_TYPES.length; i++) {
+        for (int i = 0; i < STREAMS.length; i++) {
             // Skip the phone specific ones and the active one
-            final int streamType = STREAM_TYPES[i];
-            if (streamType == AudioManager.STREAM_RING
-                    || streamType == AudioManager.STREAM_VOICE_CALL
-                    || streamType == AudioManager.STREAM_BLUETOOTH_SCO
-                    || streamType == mActiveStreamType) {
+            final int streamType = STREAMS[i].streamType;
+            if (!STREAMS[i].show || streamType == mActiveStreamType) {
                 continue;
             }
             StreamControl sc = mStreamControls.get(streamType);
diff --git a/core/java/android/view/accessibility/AccessibilityManager.java b/core/java/android/view/accessibility/AccessibilityManager.java
index a80c2a7..e37de6f 100644
--- a/core/java/android/view/accessibility/AccessibilityManager.java
+++ b/core/java/android/view/accessibility/AccessibilityManager.java
@@ -49,10 +49,8 @@
  * </p>
  * <p>
  * <code>
- * <pre>
- *   AccessibilityManager accessibilityManager =
- *           (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
- * </pre>
+ * <pre>AccessibilityManager accessibilityManager =
+ *        (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);</pre>
  * </code>
  * </p>
  *
@@ -91,7 +89,10 @@
         new CopyOnWriteArrayList<AccessibilityStateChangeListener>();
 
     /**
-     * Listener for the accessibility state.
+     * Listener for the system accessibility state. To listen for changes to the accessibility
+     * state on the device, implement this interface and register it with the system by
+     * calling {@link AccessibilityManager#addAccessibilityStateChangeListener
+     * addAccessibilityStateChangeListener()}.
      */
     public interface AccessibilityStateChangeListener {
 
diff --git a/core/java/android/webkit/HTML5Audio.java b/core/java/android/webkit/HTML5Audio.java
index 9fc48a1..97d61ba 100644
--- a/core/java/android/webkit/HTML5Audio.java
+++ b/core/java/android/webkit/HTML5Audio.java
@@ -238,24 +238,27 @@
         switch (focusChange) {
         case AudioManager.AUDIOFOCUS_GAIN:
             // resume playback
-            if (mMediaPlayer == null) resetMediaPlayer();
-            else if (!mMediaPlayer.isPlaying()) mMediaPlayer.start();
-            mState = STARTED;
+            if (mMediaPlayer == null) {
+                resetMediaPlayer();
+            } else if (mState != ERROR && !mMediaPlayer.isPlaying()) {
+                mMediaPlayer.start();
+                mState = STARTED;
+            }
             break;
 
         case AudioManager.AUDIOFOCUS_LOSS:
-            // Lost focus for an unbounded amount of time: stop playback and release media player
-            if (mMediaPlayer.isPlaying()) mMediaPlayer.stop();
-            mMediaPlayer.release();
-            mMediaPlayer = null;
+            // Lost focus for an unbounded amount of time: stop playback.
+            if (mState != ERROR && mMediaPlayer.isPlaying()) {
+                mMediaPlayer.stop();
+                mState = STOPPED;
+            }
             break;
 
         case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
         case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
             // Lost focus for a short time, but we have to stop
-            // playback. We don't release the media player because playback
-            // is likely to resume
-            if (mMediaPlayer.isPlaying()) mMediaPlayer.pause();
+            // playback.
+            if (mState != ERROR && mMediaPlayer.isPlaying()) pause();
             break;
         }
     }
@@ -273,10 +276,7 @@
             int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                 AudioManager.AUDIOFOCUS_GAIN);
 
-            if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
-                // could not get audio focus.
-                teardown();
-            } else {
+            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                 mMediaPlayer.start();
                 mState = STARTED;
             }
@@ -299,8 +299,13 @@
         }
     }
 
+    /**
+     * Called only over JNI when WebKit is happy to
+     * destroy the media player.
+     */
     private void teardown() {
         mMediaPlayer.release();
+        mMediaPlayer = null;
         mState = ERROR;
         mNativePointer = 0;
     }
diff --git a/core/java/android/webkit/WebChromeClient.java b/core/java/android/webkit/WebChromeClient.java
index ae40ded..3d129f7 100644
--- a/core/java/android/webkit/WebChromeClient.java
+++ b/core/java/android/webkit/WebChromeClient.java
@@ -95,27 +95,33 @@
     public void onHideCustomView() {}
 
     /**
-     * Request the host application to create a new Webview. The host
-     * application should handle placement of the new WebView in the view
-     * system. The default behavior returns null.
-     * @param view The WebView that initiated the callback.
-     * @param dialog True if the new window is meant to be a small dialog
-     *               window.
-     * @param userGesture True if the request was initiated by a user gesture
-     *                    such as clicking a link.
-     * @param resultMsg The message to send when done creating a new WebView.
-     *                  Set the new WebView through resultMsg.obj which is 
-     *                  WebView.WebViewTransport() and then call
-     *                  resultMsg.sendToTarget();
-     * @return Similar to javscript dialogs, this method should return true if
-     *         the client is going to handle creating a new WebView. Note that
-     *         the WebView will halt processing if this method returns true so
-     *         make sure to call resultMsg.sendToTarget(). It is undefined
-     *         behavior to call resultMsg.sendToTarget() after returning false
-     *         from this method.
+     * Request the host application to create a new window. If the host
+     * application chooses to honor this request, it should return true from
+     * this method, create a new WebView to host the window, insert it into the
+     * View system and send the supplied resultMsg message to its target with
+     * the new WebView as an argument. If the host application chooses not to
+     * honor the request, it should return false from this method. The default
+     * implementation of this method does nothing and hence returns false.
+     * @param view The WebView from which the request for a new window
+     *             originated.
+     * @param isDialog True if the new window should be a dialog, rather than
+     *                 a full-size window.
+     * @param isUserGesture True if the request was initiated by a user gesture,
+     *                      such as the user clicking a link.
+     * @param resultMsg The message to send when once a new WebView has been
+     *                  created. resultMsg.obj is a
+     *                  {@link WebView.WebViewTransport} object. This should be
+     *                  used to transport the new WebView, by calling
+     *                  {@link WebView.WebViewTransport#setWebView(WebView)
+     *                  WebView.WebViewTransport.setWebView(WebView)}.
+     * @return This method should return true if the host application will
+     *         create a new window, in which case resultMsg should be sent to
+     *         its target. Otherwise, this method should return false. Returning
+     *         false from this method but also sending resultMsg will result in
+     *         undefined behavior.
      */
-    public boolean onCreateWindow(WebView view, boolean dialog,
-            boolean userGesture, Message resultMsg) {
+    public boolean onCreateWindow(WebView view, boolean isDialog,
+            boolean isUserGesture, Message resultMsg) {
         return false;
     }
 
diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java
index 9c44138..f1c2bde 100644
--- a/core/java/android/webkit/WebSettings.java
+++ b/core/java/android/webkit/WebSettings.java
@@ -211,6 +211,7 @@
     private ZoomDensity     mDefaultZoom = ZoomDensity.MEDIUM;
     private RenderPriority  mRenderPriority = RenderPriority.NORMAL;
     private int             mOverrideCacheMode = LOAD_DEFAULT;
+    private int             mDoubleTapZoom = 100;
     private boolean         mSaveFormData = true;
     private boolean         mAutoFillEnabled = false;
     private boolean         mSavePassword = true;
@@ -769,6 +770,27 @@
     }
 
     /**
+     * Set the double-tap zoom of the page in percent. Default is 100.
+     * @param doubleTapZoom A percent value for increasing or decreasing the double-tap zoom.
+     * @hide
+     */
+    public void setDoubleTapZoom(int doubleTapZoom) {
+        if (mDoubleTapZoom != doubleTapZoom) {
+            mDoubleTapZoom = doubleTapZoom;
+            mWebView.updateDoubleTapZoom();
+        }
+    }
+
+    /**
+     * Get the double-tap zoom of the page in percent.
+     * @return A percent value describing the double-tap zoom.
+     * @hide
+     */
+    public int getDoubleTapZoom() {
+        return mDoubleTapZoom;
+    }
+
+    /**
      * Set the default zoom density of the page. This should be called from UI
      * thread.
      * @param zoom A ZoomDensity value
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index 9648cd0..cf6e187 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -2003,15 +2003,18 @@
     }
 
     /**
-     * Load the given url with the extra headers.
-     * @param url The url of the resource to load.
-     * @param extraHeaders The extra headers sent with this url. This should not
-     *            include the common headers like "user-agent". If it does, it
-     *            will be replaced by the intrinsic value of the WebView.
+     * Load the given URL with the specified additional HTTP headers.
+     * @param url The URL of the resource to load.
+     * @param additionalHttpHeaders The additional headers to be used in the
+     *            HTTP request for this URL, specified as a map from name to
+     *            value. Note that if this map contains any of the headers
+     *            that are set by default by the WebView, such as those
+     *            controlling caching, accept types or the User-Agent, their
+     *            values may be overriden by the WebView's defaults.
      */
-    public void loadUrl(String url, Map<String, String> extraHeaders) {
+    public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
         checkThread();
-        loadUrlImpl(url, extraHeaders);
+        loadUrlImpl(url, additionalHttpHeaders);
     }
 
     private void loadUrlImpl(String url, Map<String, String> extraHeaders) {
@@ -2024,8 +2027,8 @@
     }
 
     /**
-     * Load the given url.
-     * @param url The url of the resource to load.
+     * Load the given URL.
+     * @param url The URL of the resource to load.
      */
     public void loadUrl(String url) {
         checkThread();
@@ -2079,10 +2082,12 @@
      * <p>
      * The 'data' scheme URL formed by this method uses the default US-ASCII
      * charset. If you need need to set a different charset, you should form a
-     * 'data' scheme URL which specifies a charset parameter and call
-     * {@link #loadUrl(String)} instead.
+     * 'data' scheme URL which explicitly specifies a charset parameter in the
+     * mediatype portion of the URL and call {@link #loadUrl(String)} instead.
+     * Note that the charset obtained from the mediatype portion of a data URL
+     * always overrides that specified in the HTML or XML document itself.
      * @param data A String of data in the given encoding.
-     * @param mimeType The MIMEType of the data, e.g. 'text/html'.
+     * @param mimeType The MIME type of the data, e.g. 'text/html'.
      * @param encoding The encoding of the data.
      */
     public void loadData(String data, String mimeType, String encoding) {
@@ -2986,6 +2991,13 @@
         return false;
     }
 
+    /**
+     * Update the double-tap zoom.
+     */
+    /* package */ void updateDoubleTapZoom() {
+        mZoomManager.updateDoubleTapZoom();
+    }
+
     private int computeRealHorizontalScrollRange() {
         if (mDrawHistory) {
             return mHistoryWidth;
@@ -4492,6 +4504,9 @@
             if (mHeldMotionless == MOTIONLESS_FALSE) {
                 mPrivateHandler.sendMessageDelayed(mPrivateHandler
                         .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
+                mPrivateHandler.sendMessageDelayed(mPrivateHandler
+                        .obtainMessage(AWAKEN_SCROLL_BARS),
+                            ViewConfiguration.getScrollDefaultDelay());
                 mHeldMotionless = MOTIONLESS_PENDING;
             }
         }
@@ -4505,7 +4520,7 @@
         boolean UIAnimationsRunning = false;
         // Currently for each draw we compute the animation values;
         // We may in the future decide to do that independently.
-        if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) {
+        if (mNativeClass != 0 && nativeEvaluateLayersAnimations(mNativeClass)) {
             UIAnimationsRunning = true;
             // If we have unfinished (or unstarted) animations,
             // we ask for a repaint. We only need to do this in software
@@ -4521,9 +4536,9 @@
             extras = DRAW_EXTRAS_FIND;
         } else if (mSelectingText && !USE_JAVA_TEXT_SELECTION) {
             extras = DRAW_EXTRAS_SELECTION;
-            nativeSetSelectionPointer(mDrawSelectionPointer,
-                    mZoomManager.getInvScale(),
-                    mSelectX, mSelectY - getTitleHeight());
+            nativeSetSelectionPointer(mNativeClass,
+                    mDrawSelectionPointer,
+                    mZoomManager.getInvScale(), mSelectX, mSelectY - getTitleHeight());
         } else if (drawCursorRing) {
             extras = DRAW_EXTRAS_CURSOR_RING;
         }
@@ -4537,8 +4552,8 @@
         }
 
         if (canvas.isHardwareAccelerated()) {
-            int functor = nativeGetDrawGLFunction(mGLViewportEmpty ? null : mGLRectViewport,
-                    mGLViewportEmpty ? null : mViewRectViewport, getScale(), extras);
+            int functor = nativeGetDrawGLFunction(mNativeClass,
+                    mGLViewportEmpty ? null : mGLRectViewport, mGLViewportEmpty ? null : mViewRectViewport, getScale(), extras);
             ((HardwareCanvas) canvas).callDrawGLFunction(functor);
 
             if (mHardwareAccelSkia != getSettings().getHardwareAccelSkiaEnabled()) {
@@ -5989,6 +6004,7 @@
                     mTouchMode = TOUCH_DRAG_START_MODE;
                     mConfirmMove = true;
                     mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
+                    nativeSetIsScrolling(false);
                 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
                     mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
                     if (USE_WEBKIT_RINGS || getSettings().supportTouchOnly()) {
@@ -6271,9 +6287,16 @@
                     }
                     mLastTouchX = x;
                     mLastTouchY = y;
-                    if ((deltaX | deltaY) != 0) {
+
+                    if (deltaX * deltaX + deltaY * deltaY > mTouchSlopSquare) {
                         mHeldMotionless = MOTIONLESS_FALSE;
+                        nativeSetIsScrolling(true);
+                    } else {
+                        mHeldMotionless = MOTIONLESS_TRUE;
+                        nativeSetIsScrolling(false);
+                        keepScrollBarsVisible = true;
                     }
+
                     mLastTouchTime = eventTime;
                 }
 
@@ -6289,9 +6312,15 @@
                     // keep the scrollbar on the screen even there is no scroll
                     awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
                             false);
+                    // Post a message so that we'll keep them alive while we're not scrolling.
+                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
+                            .obtainMessage(AWAKEN_SCROLL_BARS),
+                            ViewConfiguration.getScrollDefaultDelay());
                     // return false to indicate that we can't pan out of the
                     // view space
                     return !done;
+                } else {
+                    mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
                 }
                 break;
             }
@@ -9407,9 +9436,9 @@
             // We never want to change button state if we are hardware accelerated,
             // but we DO want to invalidate as necessary so that the GL ring
             // can be drawn
-            nativeRecordButtons(false, false, inval);
+            nativeRecordButtons(mNativeClass, false, false, inval);
         } else {
-            nativeRecordButtons(focus, pressed, inval);
+            nativeRecordButtons(mNativeClass, focus, pressed, inval);
         }
     }
 
@@ -9444,9 +9473,9 @@
     private native int nativeDraw(Canvas canvas, int color, int extra,
             boolean splitIfNeeded);
     private native void     nativeDumpDisplayTree(String urlOrNull);
-    private native boolean  nativeEvaluateLayersAnimations();
-    private native int      nativeGetDrawGLFunction(Rect rect, Rect viewRect,
-            float scale, int extras);
+    private native boolean  nativeEvaluateLayersAnimations(int nativeInstance);
+    private native int      nativeGetDrawGLFunction(int nativeInstance, Rect rect,
+            Rect viewRect, float scale, int extras);
     private native void     nativeUpdateDrawGLFunction(Rect rect, Rect viewRect);
     private native void     nativeExtendSelection(int x, int y);
     private native int      nativeFindAll(String findLower, String findUpper,
@@ -9509,8 +9538,8 @@
     private native boolean  nativePointInNavCache(int x, int y, int slop);
     // Like many other of our native methods, you must make sure that
     // mNativeClass is not null before calling this method.
-    private native void     nativeRecordButtons(boolean focused,
-            boolean pressed, boolean invalidate);
+    private native void     nativeRecordButtons(int nativeInstance,
+            boolean focused, boolean pressed, boolean invalidate);
     private native void     nativeResetSelection();
     private native Point    nativeSelectableText();
     private native void     nativeSelectAll();
@@ -9531,8 +9560,8 @@
     private native void     nativeReplaceBaseContent(int content);
     private native void     nativeCopyBaseContentToPicture(Picture pict);
     private native boolean  nativeHasContent();
-    private native void     nativeSetSelectionPointer(boolean set,
-            float scale, int x, int y);
+    private native void     nativeSetSelectionPointer(int nativeInstance,
+            boolean set, float scale, int x, int y);
     private native boolean  nativeStartSelection(int x, int y);
     private native void     nativeStopGL();
     private native Rect     nativeSubtractLayers(Rect content);
diff --git a/core/java/android/webkit/ZoomManager.java b/core/java/android/webkit/ZoomManager.java
index 7f526e7..206142a 100644
--- a/core/java/android/webkit/ZoomManager.java
+++ b/core/java/android/webkit/ZoomManager.java
@@ -145,11 +145,11 @@
     private float mInvDefaultScale;
 
     /*
-     * The scale factor that is used to determine the zoom level for reading text.
-     * The value is initially set to equal the display density.
-     * TODO: Support changing this in WebSettings
+     * The logical density of the display. This is a scaling factor for the
+     * Density Independent Pixel unit, where one DIP is one pixel on an
+     * approximately 160 dpi screen (see android.util.DisplayMetrics.density)
      */
-    private float mReadingLevelScale;
+    private float mDisplayDensity;
 
     /*
      * The scale factor that is used as the minimum increment when going from
@@ -233,11 +233,11 @@
     public void init(float density) {
         assert density > 0;
 
+        mDisplayDensity = density;
         setDefaultZoomScale(density);
         mActualScale = density;
         mInvActualScale = 1 / density;
-        mReadingLevelScale = density;
-        mTextWrapScale = density;
+        mTextWrapScale = getReadingLevelScale();
     }
 
     /**
@@ -310,8 +310,11 @@
         return mInitialScale > 0 ? mInitialScale : mDefaultScale;
     }
 
+    /**
+     * Returns the zoom scale used for reading text on a double-tap.
+     */
     public final float getReadingLevelScale() {
-        return mReadingLevelScale;
+        return mDisplayDensity * mWebView.getSettings().getDoubleTapZoom() / 100.0f;
     }
 
     public final float getInvDefaultScale() {
@@ -510,6 +513,13 @@
         return mZoomScale != 0 || mInHWAcceleratedZoom;
     }
 
+    public void updateDoubleTapZoom() {
+        if (mInZoomOverview) {
+            mTextWrapScale = getReadingLevelScale();
+            refreshZoomScale(true);
+        }
+    }
+
     public void refreshZoomScale(boolean reflowText) {
         setZoomScale(mActualScale, reflowText, true);
     }
diff --git a/core/java/android/widget/AbsSeekBar.java b/core/java/android/widget/AbsSeekBar.java
index 475b8ee..bdaf89e 100644
--- a/core/java/android/widget/AbsSeekBar.java
+++ b/core/java/android/widget/AbsSeekBar.java
@@ -335,7 +335,9 @@
                     mTouchDownX = event.getX();
                 } else {
                     setPressed(true);
-                    invalidate(mThumb.getBounds()); // This may be within the padding region
+                    if (mThumb != null) {
+                        invalidate(mThumb.getBounds()); // This may be within the padding region
+                    }
                     onStartTrackingTouch();
                     trackTouchEvent(event);
                     attemptClaimDrag();
@@ -349,7 +351,9 @@
                     final float x = event.getX();
                     if (Math.abs(x - mTouchDownX) > mScaledTouchSlop) {
                         setPressed(true);
-                        invalidate(mThumb.getBounds()); // This may be within the padding region
+                        if (mThumb != null) {
+                            invalidate(mThumb.getBounds()); // This may be within the padding region
+                        }
                         onStartTrackingTouch();
                         trackTouchEvent(event);
                         attemptClaimDrag();
diff --git a/core/java/android/widget/ImageView.java b/core/java/android/widget/ImageView.java
index a5d6c9a..b24dd69 100644
--- a/core/java/android/widget/ImageView.java
+++ b/core/java/android/widget/ImageView.java
@@ -147,6 +147,11 @@
             setColorFilter(tint);
         }
         
+        int alpha = a.getInt(com.android.internal.R.styleable.ImageView_drawableAlpha, 255);
+        if (alpha != 255) {
+            setAlpha(alpha);
+        }
+
         mCropToPadding = a.getBoolean(
                 com.android.internal.R.styleable.ImageView_cropToPadding, false);
         
diff --git a/core/java/android/widget/SpellChecker.java b/core/java/android/widget/SpellChecker.java
index 1da18aa..5fbbe4d 100644
--- a/core/java/android/widget/SpellChecker.java
+++ b/core/java/android/widget/SpellChecker.java
@@ -32,6 +32,7 @@
 import com.android.internal.util.ArrayUtils;
 
 import java.text.BreakIterator;
+import java.util.Locale;
 
 
 /**
@@ -45,7 +46,7 @@
 
     private final TextView mTextView;
 
-    final SpellCheckerSession mSpellCheckerSession;
+    SpellCheckerSession mSpellCheckerSession;
     final int mCookie;
 
     // Paired arrays for the (id, spellCheckSpan) pair. A negative id means the associated
@@ -61,23 +62,54 @@
 
     private int mSpanSequenceCounter = 0;
 
+    private Locale mCurrentLocale;
+
+    // Shared by all SpellParsers. Cannot be shared with TextView since it may be used
+    // concurrently due to the asynchronous nature of onGetSuggestions.
+    private WordIterator mWordIterator;
+
     public SpellChecker(TextView textView) {
         mTextView = textView;
 
-        final TextServicesManager textServicesManager = (TextServicesManager) textView.getContext().
-                getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);
-        mSpellCheckerSession = textServicesManager.newSpellCheckerSession(
-                null /* not currently used by the textServicesManager */,
-                null /* null locale means use the languages defined in Settings
-                        if referToSpellCheckerLanguageSettings is true */,
-                        this, true /* means use the languages defined in Settings */);
-        mCookie = hashCode();
-
-        // Arbitrary: 4 simultaneous spell check spans. Will automatically double size on demand
+        // Arbitrary: these arrays will automatically double their sizes on demand
         final int size = ArrayUtils.idealObjectArraySize(1);
         mIds = new int[size];
         mSpellCheckSpans = new SpellCheckSpan[size];
+
+        setLocale(mTextView.getLocale());
+
+        mCookie = hashCode();
+    }
+
+    private void setLocale(Locale locale) {
+        final TextServicesManager textServicesManager = (TextServicesManager)
+                mTextView.getContext().getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);
+        mSpellCheckerSession = textServicesManager.newSpellCheckerSession(
+                null /* Bundle not currently used by the textServicesManager */,
+                locale, this, false /* means any available languages from current spell checker */);
+        mCurrentLocale = locale;
+
+        // Restore SpellCheckSpans in pool
+        for (int i = 0; i < mLength; i++) {
+            mSpellCheckSpans[i].setSpellCheckInProgress(false);
+            mIds[i] = -1;
+        }
         mLength = 0;
+
+        // Change SpellParsers' wordIterator locale
+        mWordIterator = new WordIterator(locale);
+
+        // Stop all SpellParsers
+        final int length = mSpellParsers.length;
+        for (int i = 0; i < length; i++) {
+            mSpellParsers[i].finish();
+        }
+
+        // Remove existing misspelled SuggestionSpans
+        mTextView.removeMisspelledSpans((Editable) mTextView.getText());
+
+        // This class is the listener for locale change: warn other locale-aware objects
+        mTextView.onLocaleChanged();
     }
 
     /**
@@ -95,7 +127,7 @@
 
         final int length = mSpellParsers.length;
         for (int i = 0; i < length; i++) {
-            mSpellParsers[i].close();
+            mSpellParsers[i].finish();
         }
     }
 
@@ -140,12 +172,20 @@
     }
 
     public void spellCheck(int start, int end) {
+        final Locale locale = mTextView.getLocale();
+        if (mCurrentLocale == null || (!(mCurrentLocale.equals(locale)))) {
+            setLocale(locale);
+            // Re-check the entire text
+            start = 0;
+            end = mTextView.getText().length();
+        }
+
         if (!isSessionActive()) return;
 
         final int length = mSpellParsers.length;
         for (int i = 0; i < length; i++) {
             final SpellParser spellParser = mSpellParsers[i];
-            if (spellParser.isDone()) {
+            if (spellParser.isFinished()) {
                 spellParser.init(start, end);
                 spellParser.parse();
                 return;
@@ -229,7 +269,7 @@
         final int length = mSpellParsers.length;
         for (int i = 0; i < length; i++) {
             final SpellParser spellParser = mSpellParsers[i];
-            if (!spellParser.isDone()) {
+            if (!spellParser.isFinished()) {
                 spellParser.parse();
             }
         }
@@ -301,7 +341,6 @@
     }
 
     private class SpellParser {
-        private WordIterator mWordIterator = new WordIterator(/*TODO Locale*/);
         private Object mRange = new Object();
 
         public void init(int start, int end) {
@@ -309,11 +348,11 @@
                     Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
         }
 
-        public void close() {
+        public void finish() {
             ((Editable) mTextView.getText()).removeSpan(mRange);
         }
 
-        public boolean isDone() {
+        public boolean isFinished() {
             return ((Editable) mTextView.getText()).getSpanStart(mRange) < 0;
         }
 
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 324198f..55e49ea 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -132,6 +132,7 @@
 import android.view.inputmethod.ExtractedTextRequest;
 import android.view.inputmethod.InputConnection;
 import android.view.inputmethod.InputMethodManager;
+import android.view.inputmethod.InputMethodSubtype;
 import android.widget.AdapterView.OnItemClickListener;
 import android.widget.RemoteViews.RemoteView;
 
@@ -147,6 +148,7 @@
 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.HashMap;
+import java.util.Locale;
 
 /**
  * Displays text to the user and optionally allows them to edit it.  A TextView
@@ -357,6 +359,8 @@
 
     private SpellChecker mSpellChecker;
 
+    private boolean mShowSoftInputOnFocus = true;
+
     // The alignment to pass to Layout, or null if not resolved.
     private Layout.Alignment mLayoutAlignment;
 
@@ -605,6 +609,12 @@
                 mLinksClickable = a.getBoolean(attr, true);
                 break;
 
+//            TODO uncomment when this attribute is made public in the next release
+//                 also add TextView_showSoftInputOnFocus to the list of attributes above
+//            case com.android.internal.R.styleable.TextView_showSoftInputOnFocus:
+//                setShowSoftInputOnFocus(a.getBoolean(attr, true));
+//                break;
+
             case com.android.internal.R.styleable.TextView_drawableLeft:
                 drawableLeft = a.getDrawable(attr);
                 break;
@@ -2368,6 +2378,29 @@
     }
 
     /**
+     * Sets whether the soft input method will be made visible when this
+     * TextView gets focused. The default is true.
+     *
+     * @attr ref android.R.styleable#TextView_showSoftInputOnFocus
+     * @hide
+     */
+    @android.view.RemotableViewMethod
+    public final void setShowSoftInputOnFocus(boolean show) {
+        mShowSoftInputOnFocus = show;
+    }
+
+    /**
+     * Returns whether the soft input method will be made visible when this
+     * TextView gets focused. The default is true.
+     *
+     * @attr ref android.R.styleable#TextView_showSoftInputOnFocus
+     * @hide
+     */
+    public final boolean getShowSoftInputOnFocus() {
+        return mShowSoftInputOnFocus;
+    }
+
+    /**
      * Returns the list of URLSpans attached to the text
      * (by {@link Linkify} or otherwise) if any.  You can call
      * {@link URLSpan#getURL} on them to find where they link to
@@ -2942,15 +2975,7 @@
                     sp.removeSpan(cw);
                 }
 
-                SuggestionSpan[] suggestionSpans = sp.getSpans(0, sp.length(), SuggestionSpan.class);
-                for (int i = 0; i < suggestionSpans.length; i++) {
-                    int flags = suggestionSpans[i].getFlags();
-                    if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0
-                            && (flags & SuggestionSpan.FLAG_MISSPELLED) != 0) {
-                        sp.removeSpan(suggestionSpans[i]);
-                    }
-                }
-
+                removeMisspelledSpans(sp);
                 sp.removeSpan(mSuggestionRangeSpan);
 
                 ss.text = sp;
@@ -2970,6 +2995,18 @@
         return superState;
     }
 
+    void removeMisspelledSpans(Spannable spannable) {
+        SuggestionSpan[] suggestionSpans = spannable.getSpans(0, spannable.length(),
+                SuggestionSpan.class);
+        for (int i = 0; i < suggestionSpans.length; i++) {
+            int flags = suggestionSpans[i].getFlags();
+            if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0
+                    && (flags & SuggestionSpan.FLAG_MISSPELLED) != 0) {
+                spannable.removeSpan(suggestionSpans[i]);
+            }
+        }
+    }
+
     @Override
     public void onRestoreInstanceState(Parcelable state) {
         if (!(state instanceof SavedState)) {
@@ -5465,7 +5502,7 @@
                                 && mLayout != null && onCheckIsTextEditor()) {
                             InputMethodManager imm = InputMethodManager.peekInstance();
                             viewClicked(imm);
-                            if (imm != null) {
+                            if (imm != null && mShowSoftInputOnFocus) {
                                 imm.showSoftInput(this, 0);
                             }
                         }
@@ -7683,8 +7720,9 @@
             }
         }
         
-        if (what instanceof UpdateAppearance ||
-            what instanceof ParagraphStyle) {
+        if (what instanceof UpdateAppearance || what instanceof ParagraphStyle
+                || (what instanceof SuggestionSpan && (((SuggestionSpan)what).getFlags()
+                        & SuggestionSpan.FLAG_AUTO_CORRECTION) != 0)) {
             if (ims == null || ims.mBatchEditNesting == 0) {
                 invalidate();
                 mHighlightPathBogus = true;
@@ -8206,6 +8244,9 @@
             }
 
             hideControllers();
+            if (mSuggestionsPopupWindow != null) {
+                mSuggestionsPopupWindow.onParentLostFocus();
+            }
         }
 
         startStopMarquee(hasWindowFocus);
@@ -8303,7 +8344,7 @@
                 // Show the IME, except when selecting in read-only text.
                 final InputMethodManager imm = InputMethodManager.peekInstance();
                 viewClicked(imm);
-                if (!mTextIsSelectable) {
+                if (!mTextIsSelectable && mShowSoftInputOnFocus) {
                     handled |= imm != null && imm.showSoftInput(this, 0);
                 }
 
@@ -8839,15 +8880,13 @@
             selectionStart = ((Spanned) mText).getSpanStart(urlSpan);
             selectionEnd = ((Spanned) mText).getSpanEnd(urlSpan);
         } else {
-            if (mWordIterator == null) {
-                mWordIterator = new WordIterator();
-            }
-            mWordIterator.setCharSequence(mText, minOffset, maxOffset);
+            final WordIterator wordIterator = getWordIterator();
+            wordIterator.setCharSequence(mText, minOffset, maxOffset);
 
-            selectionStart = mWordIterator.getBeginning(minOffset);
+            selectionStart = wordIterator.getBeginning(minOffset);
             if (selectionStart == BreakIterator.DONE) return false;
 
-            selectionEnd = mWordIterator.getEnd(maxOffset);
+            selectionEnd = wordIterator.getEnd(maxOffset);
             if (selectionEnd == BreakIterator.DONE) return false;
 
             if (selectionStart == selectionEnd) {
@@ -8862,6 +8901,43 @@
         return selectionEnd > selectionStart;
     }
 
+    /**
+     * This is a temporary method. Future versions may support multi-locale text.
+     *
+     * @return The current locale used in this TextView, based on the current IME's locale,
+     * or the system default locale if this is not defined.
+     * @hide
+     */
+    public Locale getLocale() {
+        Locale locale = Locale.getDefault();
+        final InputMethodManager imm = InputMethodManager.peekInstance();
+        if (imm != null) {
+            final InputMethodSubtype currentInputMethodSubtype = imm.getCurrentInputMethodSubtype();
+            if (currentInputMethodSubtype != null) {
+                String localeString = currentInputMethodSubtype.getLocale();
+                if (!TextUtils.isEmpty(localeString)) {
+                    locale = new Locale(localeString);
+                }
+            }
+        }
+        return locale;
+    }
+
+    void onLocaleChanged() {
+        // Will be re-created on demand in getWordIterator with the proper new locale
+        mWordIterator = null;
+    }
+
+    /**
+     * @hide
+     */
+    public WordIterator getWordIterator() {
+        if (mWordIterator == null) {
+            mWordIterator = new WordIterator(getLocale());
+        }
+        return mWordIterator;
+    }
+
     private long getCharRange(int offset) {
         final int textLength = mText.length();
         if (offset + 1 < textLength) {
@@ -9546,6 +9622,7 @@
         private SuggestionInfo[] mSuggestionInfos;
         private int mNumberOfSuggestions;
         private boolean mCursorWasVisibleBeforeSuggestions;
+        private boolean mIsShowingUp = false;
         private SuggestionAdapter mSuggestionsAdapter;
         private final Comparator<SuggestionSpan> mSuggestionSpanComparator;
         private final HashMap<SuggestionSpan, Integer> mSpansLengths;
@@ -9601,6 +9678,14 @@
             }
         }
 
+        public boolean isShowingUp() {
+            return mIsShowingUp;
+        }
+
+        public void onParentLostFocus() {
+            mIsShowingUp = false;
+        }
+
         private class SuggestionInfo {
             int suggestionStart, suggestionEnd; // range of actual suggestion within text
             SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents
@@ -9704,6 +9789,7 @@
             updateSuggestions();
             mCursorWasVisibleBeforeSuggestions = mCursorVisible;
             setCursorVisible(false);
+            mIsShowingUp = true;
             super.show();
         }
 
@@ -9881,14 +9967,16 @@
             if (suggestionInfo.suggestionIndex == DELETE_TEXT) {
                 final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan);
                 int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan);
-                // Do not leave two adjacent spaces after deletion, or one at beginning of text
-                if (spanUnionEnd < editable.length() &&
-                        Character.isSpaceChar(editable.charAt(spanUnionEnd)) &&
-                        (spanUnionStart == 0 ||
-                        Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) {
+                if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) {
+                    // Do not leave two adjacent spaces after deletion, or one at beginning of text
+                    if (spanUnionEnd < editable.length() &&
+                            Character.isSpaceChar(editable.charAt(spanUnionEnd)) &&
+                            (spanUnionStart == 0 ||
+                            Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) {
                         spanUnionEnd = spanUnionEnd + 1;
+                    }
+                    editable.replace(spanUnionStart, spanUnionEnd, "");
                 }
-                editable.replace(spanUnionStart, spanUnionEnd, "");
                 hide();
                 return;
             }
@@ -10114,7 +10202,7 @@
         final boolean selectionStarted = mSelectionActionMode != null ||
                 extractedTextModeWillBeStartedFullScreen;
 
-        if (selectionStarted && !mTextIsSelectable && imm != null) {
+        if (selectionStarted && !mTextIsSelectable && imm != null && mShowSoftInputOnFocus) {
             // Show the IME to be able to replace text, except when selecting non editable text.
             imm.showSoftInput(this, 0, null);
         }
@@ -11114,6 +11202,10 @@
     }
 
     private void hideCursorControllers() {
+        if (mSuggestionsPopupWindow != null && !mSuggestionsPopupWindow.isShowingUp()) {
+            // Should be done before hide insertion point controller since it triggers a show of it
+            mSuggestionsPopupWindow.hide();
+        }
         hideInsertionPointCursorController();
         stopSelectionActionMode();
     }
diff --git a/core/java/android/widget/Toast.java b/core/java/android/widget/Toast.java
index bb23173..88d7e05 100644
--- a/core/java/android/widget/Toast.java
+++ b/core/java/android/widget/Toast.java
@@ -48,6 +48,13 @@
  * <p>
  * The easiest way to use this class is to call one of the static methods that constructs
  * everything you need and returns a new Toast object.
+ *
+ * <div class="special reference">
+ * <h3>Developer Guides</h3>
+ * <p>For information about creating Toast notifications, read the
+ * <a href="{@docRoot}guide/topics/ui/notifiers/toasts.html">Toast Notifications</a> developer
+ * guide.</p>
+ * </div>
  */ 
 public class Toast {
     static final String TAG = "Toast";
diff --git a/core/java/com/android/internal/policy/IFaceLockCallback.aidl b/core/java/com/android/internal/policy/IFaceLockCallback.aidl
index add3f1c..25adbb6 100644
--- a/core/java/com/android/internal/policy/IFaceLockCallback.aidl
+++ b/core/java/com/android/internal/policy/IFaceLockCallback.aidl
@@ -21,5 +21,6 @@
 oneway interface IFaceLockCallback {
     void unlock();
     void cancel();
+    void reportFailedAttempt();
     void pokeWakelock();
 }
diff --git a/core/java/com/android/internal/policy/IFaceLockInterface.aidl b/core/java/com/android/internal/policy/IFaceLockInterface.aidl
index 921b8c7..3958cda 100644
--- a/core/java/com/android/internal/policy/IFaceLockInterface.aidl
+++ b/core/java/com/android/internal/policy/IFaceLockInterface.aidl
@@ -23,4 +23,5 @@
     void startUi(IBinder containingWindowToken, int x, int y, int width, int height);
     void stopUi();
     void registerCallback(IFaceLockCallback cb);
+    void unregisterCallback(IFaceLockCallback cb);
 }
diff --git a/core/java/com/android/internal/view/menu/ExpandedMenuView.java b/core/java/com/android/internal/view/menu/ExpandedMenuView.java
index 723ece4..47058ad 100644
--- a/core/java/com/android/internal/view/menu/ExpandedMenuView.java
+++ b/core/java/com/android/internal/view/menu/ExpandedMenuView.java
@@ -63,11 +63,6 @@
         setChildrenDrawingCacheEnabled(false);
     }
 
-    @Override
-    protected boolean recycleOnMeasure() {
-        return false;
-    }
-
     public boolean invokeItem(MenuItemImpl item) {
         return mMenu.performItemAction(item, 0);
     }
diff --git a/core/java/com/android/internal/view/menu/ListMenuItemView.java b/core/java/com/android/internal/view/menu/ListMenuItemView.java
index a1e16d4..df579c6 100644
--- a/core/java/com/android/internal/view/menu/ListMenuItemView.java
+++ b/core/java/com/android/internal/view/menu/ListMenuItemView.java
@@ -34,6 +34,7 @@
  * The item view for each item in the ListView-based MenuViews.
  */
 public class ListMenuItemView extends LinearLayout implements MenuView.ItemView {
+    private static final String TAG = "ListMenuItemView";
     private MenuItemImpl mItemData; 
     
     private ImageView mIconView;
@@ -121,27 +122,25 @@
     }
 
     public void setCheckable(boolean checkable) {
-        
         if (!checkable && mRadioButton == null && mCheckBox == null) {
             return;
         }
         
-        if (mRadioButton == null) {
-            insertRadioButton();
-        }
-        if (mCheckBox == null) {
-            insertCheckBox();
-        }
-        
         // Depending on whether its exclusive check or not, the checkbox or
         // radio button will be the one in use (and the other will be otherCompoundButton)
         final CompoundButton compoundButton;
         final CompoundButton otherCompoundButton; 
 
         if (mItemData.isExclusiveCheckable()) {
+            if (mRadioButton == null) {
+                insertRadioButton();
+            }
             compoundButton = mRadioButton;
             otherCompoundButton = mCheckBox;
         } else {
+            if (mCheckBox == null) {
+                insertCheckBox();
+            }
             compoundButton = mCheckBox;
             otherCompoundButton = mRadioButton;
         }
@@ -155,12 +154,12 @@
             }
             
             // Make sure the other compound button isn't visible
-            if (otherCompoundButton.getVisibility() != GONE) {
+            if (otherCompoundButton != null && otherCompoundButton.getVisibility() != GONE) {
                 otherCompoundButton.setVisibility(GONE);
             }
         } else {
-            mCheckBox.setVisibility(GONE);
-            mRadioButton.setVisibility(GONE);
+            if (mCheckBox != null) mCheckBox.setVisibility(GONE);
+            if (mRadioButton != null) mRadioButton.setVisibility(GONE);
         }
     }
     
diff --git a/core/java/com/android/internal/widget/LockPatternView.java b/core/java/com/android/internal/widget/LockPatternView.java
index 5b49bff..a2fc6e2 100644
--- a/core/java/com/android/internal/widget/LockPatternView.java
+++ b/core/java/com/android/internal/widget/LockPatternView.java
@@ -32,9 +32,9 @@
 import android.os.Parcel;
 import android.os.Parcelable;
 import android.os.SystemClock;
-import android.os.Vibrator;
 import android.util.AttributeSet;
 import android.util.Log;
+import android.view.HapticFeedbackConstants;
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.accessibility.AccessibilityEvent;
@@ -59,9 +59,6 @@
     private static final int ASPECT_LOCK_WIDTH = 1; // Fixed width; height will be minimum of (w,h)
     private static final int ASPECT_LOCK_HEIGHT = 2; // Fixed height; width will be minimum of (w,h)
 
-    // Vibrator pattern for creating a tactile bump
-    private static final long[] DEFAULT_VIBE_PATTERN = {0, 1, 40, 41};
-
     private static final boolean PROFILE_DRAWING = false;
     private boolean mDrawingProfilingStarted = false;
 
@@ -102,7 +99,7 @@
     private DisplayMode mPatternDisplayMode = DisplayMode.Correct;
     private boolean mInputEnabled = true;
     private boolean mInStealthMode = false;
-    private boolean mTactileFeedbackEnabled = true;
+    private boolean mEnableHapticFeedback = true;
     private boolean mPatternInProgress = false;
 
     private float mDiameterFactor = 0.10f; // TODO: move to attrs
@@ -127,11 +124,6 @@
     private int mBitmapWidth;
     private int mBitmapHeight;
 
-
-    private Vibrator vibe; // Vibrator for creating tactile feedback
-
-    private long[] mVibePattern;
-
     private int mAspect;
     private final Matrix mArrowMatrix = new Matrix();
     private final Matrix mCircleMatrix = new Matrix();
@@ -250,7 +242,6 @@
 
     public LockPatternView(Context context, AttributeSet attrs) {
         super(context, attrs);
-        vibe = new Vibrator();
 
         TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LockPatternView);
 
@@ -295,26 +286,6 @@
             mBitmapHeight = Math.max(mBitmapHeight, bitmap.getHeight());
         }
 
-        // allow vibration pattern to be customized
-        mVibePattern = loadVibratePattern(com.android.internal.R.array.config_virtualKeyVibePattern);
-    }
-
-    private long[] loadVibratePattern(int id) {
-        int[] pattern = null;
-        try {
-            pattern = getResources().getIntArray(id);
-        } catch (Resources.NotFoundException e) {
-            Log.e(TAG, "Vibrate pattern missing, using default", e);
-        }
-        if (pattern == null) {
-            return DEFAULT_VIBE_PATTERN;
-        }
-
-        long[] tmpPattern = new long[pattern.length];
-        for (int i = 0; i < pattern.length; i++) {
-            tmpPattern[i] = pattern[i];
-        }
-        return tmpPattern;
     }
 
     private Bitmap getBitmapFor(int resId) {
@@ -332,7 +303,7 @@
      * @return Whether the view has tactile feedback enabled.
      */
     public boolean isTactileFeedbackEnabled() {
-        return mTactileFeedbackEnabled;
+        return mEnableHapticFeedback;
     }
 
     /**
@@ -352,7 +323,7 @@
      * @param tactileFeedbackEnabled Whether tactile feedback is enabled
      */
     public void setTactileFeedbackEnabled(boolean tactileFeedbackEnabled) {
-        mTactileFeedbackEnabled = tactileFeedbackEnabled;
+        mEnableHapticFeedback = tactileFeedbackEnabled;
     }
 
     /**
@@ -573,8 +544,10 @@
                 addCellToPattern(fillInGapCell);
             }
             addCellToPattern(cell);
-            if (mTactileFeedbackEnabled){
-                vibe.vibrate(mVibePattern, -1); // Generate tactile feedback
+            if (mEnableHapticFeedback) {
+                performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY,
+                        HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING
+                        | HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
             }
             return cell;
         }
@@ -1114,7 +1087,7 @@
         return new SavedState(superState,
                 LockPatternUtils.patternToString(mPattern),
                 mPatternDisplayMode.ordinal(),
-                mInputEnabled, mInStealthMode, mTactileFeedbackEnabled);
+                mInputEnabled, mInStealthMode, mEnableHapticFeedback);
     }
 
     @Override
@@ -1127,7 +1100,7 @@
         mPatternDisplayMode = DisplayMode.values()[ss.getDisplayMode()];
         mInputEnabled = ss.isInputEnabled();
         mInStealthMode = ss.isInStealthMode();
-        mTactileFeedbackEnabled = ss.isTactileFeedbackEnabled();
+        mEnableHapticFeedback = ss.isTactileFeedbackEnabled();
     }
 
     /**
diff --git a/core/java/com/android/internal/widget/LockScreenWidgetCallback.java b/core/java/com/android/internal/widget/LockScreenWidgetCallback.java
index d6403e9f..d7ad6c0 100644
--- a/core/java/com/android/internal/widget/LockScreenWidgetCallback.java
+++ b/core/java/com/android/internal/widget/LockScreenWidgetCallback.java
@@ -29,6 +29,9 @@
     // Sends a message to lock screen requesting the view to be hidden.
     public void requestHide(View self);
 
+    // Whether or not this view is currently visible on LockScreen
+    public boolean isVisible(View self);
+
     // Sends a message to lock screen that user has interacted with widget. This should be used
     // exclusively in response to user activity, i.e. user hits a button in the view.
     public void userActivity(View self);
diff --git a/core/java/com/android/internal/widget/PasswordEntryKeyboardHelper.java b/core/java/com/android/internal/widget/PasswordEntryKeyboardHelper.java
index 01df48a..2e7810f 100644
--- a/core/java/com/android/internal/widget/PasswordEntryKeyboardHelper.java
+++ b/core/java/com/android/internal/widget/PasswordEntryKeyboardHelper.java
@@ -26,6 +26,7 @@
 import android.os.Vibrator;
 import android.provider.Settings;
 import android.util.Log;
+import android.view.HapticFeedbackConstants;
 import android.view.KeyCharacterMap;
 import android.view.KeyEvent;
 import android.view.View;
@@ -52,7 +53,7 @@
     private final View mTargetView;
     private final KeyboardView mKeyboardView;
     private long[] mVibratePattern;
-    private final Vibrator mVibrator;
+    private boolean mEnableHaptics = false;
 
     public PasswordEntryKeyboardHelper(Context context, KeyboardView keyboardView, View targetView) {
         this(context, keyboardView, targetView, true);
@@ -71,7 +72,10 @@
                     mKeyboardView.getLayoutParams().height);
         }
         mKeyboardView.setOnKeyboardActionListener(this);
-        mVibrator = new Vibrator();
+    }
+
+    public void setEnableHaptics(boolean enabled) {
+        mEnableHaptics = enabled;
     }
 
     public boolean isAlpha() {
@@ -230,6 +234,7 @@
 
     public void handleBackspace() {
         sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
+        performHapticFeedback();
     }
 
     private void handleShift() {
@@ -272,8 +277,14 @@
     }
 
     public void onPress(int primaryCode) {
-        if (mVibratePattern != null) {
-            mVibrator.vibrate(mVibratePattern, -1);
+        performHapticFeedback();
+    }
+
+    private void performHapticFeedback() {
+        if (mEnableHaptics) {
+            mKeyboardView.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY,
+                    HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING
+                    | HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
         }
     }
 
diff --git a/core/java/com/android/internal/widget/TransportControlView.java b/core/java/com/android/internal/widget/TransportControlView.java
index 73d9f10..63a3aa5 100644
--- a/core/java/com/android/internal/widget/TransportControlView.java
+++ b/core/java/com/android/internal/widget/TransportControlView.java
@@ -34,6 +34,8 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
+import android.os.Parcel;
+import android.os.Parcelable;
 import android.os.RemoteException;
 import android.os.SystemClock;
 import android.text.Spannable;
@@ -61,7 +63,7 @@
     private static final int MSG_SET_GENERATION_ID = 104;
     private static final int MAXDIM = 512;
     private static final int DISPLAY_TIMEOUT_MS = 5000; // 5s
-    protected static final boolean DEBUG = true;
+    protected static final boolean DEBUG = false;
     protected static final String TAG = "TransportControlView";
 
     private ImageView mAlbumArt;
@@ -74,7 +76,7 @@
     private boolean mAttached;
     private PendingIntent mClientIntent;
     private int mTransportControlFlags;
-    private int mPlayState;
+    private int mCurrentPlayState;
     private AudioManager mAudioManager;
     private LockScreenWidgetCallback mWidgetCallbacks;
     private IRemoteControlDisplayWeak mIRCD;
@@ -84,6 +86,11 @@
      */
     private Bundle mPopulateMetadataWhenAttached = null;
 
+    /**
+     * Whether to clear the interface next time it is shown (i.e. the generation id changed)
+     */
+    private boolean mClearOnNextShow;
+
     // This handler is required to ensure messages from IRCD are handled in sequence and on
     // the UI thread.
     private Handler mHandler = new Handler() {
@@ -113,15 +120,10 @@
                 break;
 
             case MSG_SET_GENERATION_ID:
-                if (mWidgetCallbacks != null) {
-                    boolean clearing = msg.arg2 != 0;
-                    if (DEBUG) Log.v(TAG, "New genId = " + msg.arg1 + ", clearing = " + clearing);
-                    if (!clearing) {
-                        mWidgetCallbacks.requestShow(TransportControlView.this);
-                    } else {
-                        mWidgetCallbacks.requestHide(TransportControlView.this);
-                    }
+                if (msg.arg2 != 0) {
+                    mClearOnNextShow = true; // TODO: handle this
                 }
+                if (DEBUG) Log.v(TAG, "New genId = " + msg.arg1 + ", clearing = " + msg.arg2);
                 mClientGeneration = msg.arg1;
                 mClientIntent = (PendingIntent) msg.obj;
                 break;
@@ -195,6 +197,7 @@
         super(context, attrs);
         Log.v(TAG, "Create TCV " + this);
         mAudioManager = new AudioManager(mContext);
+        mCurrentPlayState = RemoteControlClient.PLAYSTATE_NONE; // until we get a callback
         mIRCD = new IRemoteControlDisplayWeak(mHandler);
     }
 
@@ -319,7 +322,7 @@
                 | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                 | RemoteControlClient.FLAG_KEY_MEDIA_STOP);
 
-        updatePlayPauseState(mPlayState);
+        updatePlayPauseState(mCurrentPlayState);
     }
 
     private static void setVisibilityBasedOnFlag(View view, int flags, int flag) {
@@ -332,32 +335,99 @@
 
     private void updatePlayPauseState(int state) {
         if (DEBUG) Log.v(TAG,
-                "updatePlayPauseState(), old=" + mPlayState + ", state=" + state);
-        if (state == mPlayState) {
+                "updatePlayPauseState(), old=" + mCurrentPlayState + ", state=" + state);
+        if (state == mCurrentPlayState) {
             return;
         }
         final int imageResId;
         final int imageDescId;
+        boolean showIfHidden = false;
         switch (state) {
+            case RemoteControlClient.PLAYSTATE_ERROR:
+                imageResId = com.android.internal.R.drawable.stat_sys_warning;
+                // TODO use more specific image description string for warning, but here the "play"
+                //      message is still valid because this button triggers a play command.
+                imageDescId = com.android.internal.R.string.lockscreen_transport_play_description;
+                break;
+
             case RemoteControlClient.PLAYSTATE_PLAYING:
                 imageResId = com.android.internal.R.drawable.ic_media_pause;
                 imageDescId = com.android.internal.R.string.lockscreen_transport_pause_description;
+                showIfHidden = true;
                 break;
 
             case RemoteControlClient.PLAYSTATE_BUFFERING:
                 imageResId = com.android.internal.R.drawable.ic_media_stop;
                 imageDescId = com.android.internal.R.string.lockscreen_transport_stop_description;
+                showIfHidden = true;
                 break;
 
             case RemoteControlClient.PLAYSTATE_PAUSED:
             default:
                 imageResId = com.android.internal.R.drawable.ic_media_play;
                 imageDescId = com.android.internal.R.string.lockscreen_transport_play_description;
+                showIfHidden = false;
                 break;
         }
         mBtnPlay.setImageResource(imageResId);
         mBtnPlay.setContentDescription(getResources().getString(imageDescId));
-        mPlayState = state;
+        if (showIfHidden && mWidgetCallbacks != null && !mWidgetCallbacks.isVisible(this)) {
+            mWidgetCallbacks.requestShow(this);
+        }
+        mCurrentPlayState = state;
+    }
+
+    static class SavedState extends BaseSavedState {
+        boolean wasShowing;
+
+        SavedState(Parcelable superState) {
+            super(superState);
+        }
+
+        private SavedState(Parcel in) {
+            super(in);
+            this.wasShowing = in.readInt() != 0;
+        }
+
+        @Override
+        public void writeToParcel(Parcel out, int flags) {
+            super.writeToParcel(out, flags);
+            out.writeInt(this.wasShowing ? 1 : 0);
+        }
+
+        public static final Parcelable.Creator<SavedState> CREATOR
+                = new Parcelable.Creator<SavedState>() {
+            public SavedState createFromParcel(Parcel in) {
+                return new SavedState(in);
+            }
+
+            public SavedState[] newArray(int size) {
+                return new SavedState[size];
+            }
+        };
+    }
+
+    @Override
+    public Parcelable onSaveInstanceState() {
+        if (DEBUG) Log.v(TAG, "onSaveInstanceState()");
+        Parcelable superState = super.onSaveInstanceState();
+        SavedState ss = new SavedState(superState);
+        ss.wasShowing = mWidgetCallbacks.isVisible(this);
+        return ss;
+    }
+
+    @Override
+    public void onRestoreInstanceState(Parcelable state) {
+        if (DEBUG) Log.v(TAG, "onRestoreInstanceState()");
+        if (!(state instanceof SavedState)) {
+            super.onRestoreInstanceState(state);
+            return;
+        }
+        SavedState ss = (SavedState) state;
+        super.onRestoreInstanceState(ss.getSuperState());
+        if (ss.wasShowing) {
+            mWidgetCallbacks.requestShow(this);
+        }
     }
 
     public void onClick(View v) {
diff --git a/core/jni/android_database_CursorWindow.cpp b/core/jni/android_database_CursorWindow.cpp
index 722aeea..4a9fcf2 100644
--- a/core/jni/android_database_CursorWindow.cpp
+++ b/core/jni/android_database_CursorWindow.cpp
@@ -57,8 +57,7 @@
     jniThrowException(env, "java/lang/IllegalStateException", msg.string());
 }
 
-static jint nativeCreate(JNIEnv* env, jclass clazz,
-        jstring nameObj, jint cursorWindowSize, jboolean localOnly) {
+static jint nativeCreate(JNIEnv* env, jclass clazz, jstring nameObj, jint cursorWindowSize) {
     String8 name;
     if (nameObj) {
         const char* nameStr = env->GetStringUTFChars(nameObj, NULL);
@@ -70,7 +69,7 @@
     }
 
     CursorWindow* window;
-    status_t status = CursorWindow::create(name, cursorWindowSize, localOnly, &window);
+    status_t status = CursorWindow::create(name, cursorWindowSize, &window);
     if (status || !window) {
         LOGE("Could not allocate CursorWindow '%s' of size %d due to error %d.",
                 name.string(), cursorWindowSize, status);
@@ -477,7 +476,7 @@
 static JNINativeMethod sMethods[] =
 {
     /* name, signature, funcPtr */
-    { "nativeCreate", "(Ljava/lang/String;IZ)I",
+    { "nativeCreate", "(Ljava/lang/String;I)I",
             (void*)nativeCreate },
     { "nativeCreateFromParcel", "(Landroid/os/Parcel;)I",
             (void*)nativeCreateFromParcel },
diff --git a/core/res/res/drawable-hdpi/btn_check_on_disabled_focused_holo_dark.png b/core/res/res/drawable-hdpi/btn_check_on_disabled_focused_holo_dark.png
index 52a9800..a7b5cd6 100644
--- a/core/res/res/drawable-hdpi/btn_check_on_disabled_focused_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_check_on_disabled_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_check_on_disabled_focused_holo_light.png b/core/res/res/drawable-hdpi/btn_check_on_disabled_focused_holo_light.png
index 49a2aeb..f96d123 100644
--- a/core/res/res/drawable-hdpi/btn_check_on_disabled_focused_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_check_on_disabled_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_check_on_disabled_holo_dark.png b/core/res/res/drawable-hdpi/btn_check_on_disabled_holo_dark.png
index e6ebb43..b614b18 100644
--- a/core/res/res/drawable-hdpi/btn_check_on_disabled_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_check_on_disabled_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_check_on_disabled_holo_light.png b/core/res/res/drawable-hdpi/btn_check_on_disabled_holo_light.png
index 7069fc5..e4f72f6 100644
--- a/core/res/res/drawable-hdpi/btn_check_on_disabled_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_check_on_disabled_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_check_on_focused_holo_dark.png b/core/res/res/drawable-hdpi/btn_check_on_focused_holo_dark.png
index ec2a7e3..7c1dd9d 100644
--- a/core/res/res/drawable-hdpi/btn_check_on_focused_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_check_on_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_check_on_focused_holo_light.png b/core/res/res/drawable-hdpi/btn_check_on_focused_holo_light.png
index 486334f..0569e08 100644
--- a/core/res/res/drawable-hdpi/btn_check_on_focused_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_check_on_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_check_on_holo.png b/core/res/res/drawable-hdpi/btn_check_on_holo.png
index 1f11a78..3d9afa8 100644
--- a/core/res/res/drawable-hdpi/btn_check_on_holo.png
+++ b/core/res/res/drawable-hdpi/btn_check_on_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_check_on_holo_dark.png b/core/res/res/drawable-hdpi/btn_check_on_holo_dark.png
index a17100c..206e43f 100644
--- a/core/res/res/drawable-hdpi/btn_check_on_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_check_on_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_check_on_holo_light.png b/core/res/res/drawable-hdpi/btn_check_on_holo_light.png
index 130ab4f..58103c8 100644
--- a/core/res/res/drawable-hdpi/btn_check_on_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_check_on_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_check_on_pressed_holo_dark.png b/core/res/res/drawable-hdpi/btn_check_on_pressed_holo_dark.png
index 96abcda..2ffe7a6 100644
--- a/core/res/res/drawable-hdpi/btn_check_on_pressed_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_check_on_pressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_check_on_pressed_holo_light.png b/core/res/res/drawable-hdpi/btn_check_on_pressed_holo_light.png
index 0a22f02..7a92c9a 100644
--- a/core/res/res/drawable-hdpi/btn_check_on_pressed_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_check_on_pressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_code_lock_default_holo.png b/core/res/res/drawable-hdpi/btn_code_lock_default_holo.png
index 28b2578..e77921c 100644
--- a/core/res/res/drawable-hdpi/btn_code_lock_default_holo.png
+++ b/core/res/res/drawable-hdpi/btn_code_lock_default_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_off_disabled_focused_holo_dark.png b/core/res/res/drawable-hdpi/btn_star_off_disabled_focused_holo_dark.png
index 8906c4d..45a8d86 100644
--- a/core/res/res/drawable-hdpi/btn_star_off_disabled_focused_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_star_off_disabled_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_off_disabled_focused_holo_light.png b/core/res/res/drawable-hdpi/btn_star_off_disabled_focused_holo_light.png
index 2bcb98e..94a0c12 100644
--- a/core/res/res/drawable-hdpi/btn_star_off_disabled_focused_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_star_off_disabled_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_off_disabled_holo_dark.png b/core/res/res/drawable-hdpi/btn_star_off_disabled_holo_dark.png
index 2e36821..70a6e90 100644
--- a/core/res/res/drawable-hdpi/btn_star_off_disabled_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_star_off_disabled_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_off_disabled_holo_light.png b/core/res/res/drawable-hdpi/btn_star_off_disabled_holo_light.png
index 6a50bd8..4b76e28 100644
--- a/core/res/res/drawable-hdpi/btn_star_off_disabled_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_star_off_disabled_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_off_focused_holo_dark.png b/core/res/res/drawable-hdpi/btn_star_off_focused_holo_dark.png
index 8595dd0..bc2f696 100644
--- a/core/res/res/drawable-hdpi/btn_star_off_focused_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_star_off_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_off_focused_holo_light.png b/core/res/res/drawable-hdpi/btn_star_off_focused_holo_light.png
index 1dda090..6f83c05 100644
--- a/core/res/res/drawable-hdpi/btn_star_off_focused_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_star_off_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_off_normal_holo_dark.png b/core/res/res/drawable-hdpi/btn_star_off_normal_holo_dark.png
index 942722e..86d42bb 100644
--- a/core/res/res/drawable-hdpi/btn_star_off_normal_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_star_off_normal_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_off_normal_holo_light.png b/core/res/res/drawable-hdpi/btn_star_off_normal_holo_light.png
index e46f035..9e3b006 100644
--- a/core/res/res/drawable-hdpi/btn_star_off_normal_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_star_off_normal_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_off_pressed_holo_dark.png b/core/res/res/drawable-hdpi/btn_star_off_pressed_holo_dark.png
index 5cfe146..1729228 100644
--- a/core/res/res/drawable-hdpi/btn_star_off_pressed_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_star_off_pressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_off_pressed_holo_light.png b/core/res/res/drawable-hdpi/btn_star_off_pressed_holo_light.png
index 20d0eb3..ff78fc5 100644
--- a/core/res/res/drawable-hdpi/btn_star_off_pressed_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_star_off_pressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_on_disabled_focused_holo_dark.png b/core/res/res/drawable-hdpi/btn_star_on_disabled_focused_holo_dark.png
index 3b478d6..9a136d9 100644
--- a/core/res/res/drawable-hdpi/btn_star_on_disabled_focused_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_star_on_disabled_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_on_disabled_focused_holo_light.png b/core/res/res/drawable-hdpi/btn_star_on_disabled_focused_holo_light.png
index 52a9f44..d49952b 100644
--- a/core/res/res/drawable-hdpi/btn_star_on_disabled_focused_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_star_on_disabled_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_on_disabled_holo_dark.png b/core/res/res/drawable-hdpi/btn_star_on_disabled_holo_dark.png
index 9810029..2014422 100644
--- a/core/res/res/drawable-hdpi/btn_star_on_disabled_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_star_on_disabled_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_on_disabled_holo_light.png b/core/res/res/drawable-hdpi/btn_star_on_disabled_holo_light.png
index 445af7b..80885d1 100644
--- a/core/res/res/drawable-hdpi/btn_star_on_disabled_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_star_on_disabled_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_on_focused_holo_dark.png b/core/res/res/drawable-hdpi/btn_star_on_focused_holo_dark.png
index d3884f6..35239da 100644
--- a/core/res/res/drawable-hdpi/btn_star_on_focused_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_star_on_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_on_focused_holo_light.png b/core/res/res/drawable-hdpi/btn_star_on_focused_holo_light.png
index eea174a..09aecf4 100644
--- a/core/res/res/drawable-hdpi/btn_star_on_focused_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_star_on_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_on_normal_holo_light.png b/core/res/res/drawable-hdpi/btn_star_on_normal_holo_light.png
index 58b2b09..b667738 100644
--- a/core/res/res/drawable-hdpi/btn_star_on_normal_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_star_on_normal_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_on_pressed_holo_dark.png b/core/res/res/drawable-hdpi/btn_star_on_pressed_holo_dark.png
index a39a620..392f852 100644
--- a/core/res/res/drawable-hdpi/btn_star_on_pressed_holo_dark.png
+++ b/core/res/res/drawable-hdpi/btn_star_on_pressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/btn_star_on_pressed_holo_light.png b/core/res/res/drawable-hdpi/btn_star_on_pressed_holo_light.png
index 1ffe7fe..b36bc53 100644
--- a/core/res/res/drawable-hdpi/btn_star_on_pressed_holo_light.png
+++ b/core/res/res/drawable-hdpi/btn_star_on_pressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/fastscroll_label_left_holo_dark.9.png b/core/res/res/drawable-hdpi/fastscroll_label_left_holo_dark.9.png
index 769cb12..e0f82606 100644
--- a/core/res/res/drawable-hdpi/fastscroll_label_left_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/fastscroll_label_left_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/fastscroll_label_left_holo_light.9.png b/core/res/res/drawable-hdpi/fastscroll_label_left_holo_light.9.png
index c5372a8..5fb6e96 100644
--- a/core/res/res/drawable-hdpi/fastscroll_label_left_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/fastscroll_label_left_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/fastscroll_label_right_holo_dark.9.png b/core/res/res/drawable-hdpi/fastscroll_label_right_holo_dark.9.png
index 1dee51b..8c80ea1 100644
--- a/core/res/res/drawable-hdpi/fastscroll_label_right_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/fastscroll_label_right_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/fastscroll_label_right_holo_light.9.png b/core/res/res/drawable-hdpi/fastscroll_label_right_holo_light.9.png
index 3c1e25a..80e1fba 100644
--- a/core/res/res/drawable-hdpi/fastscroll_label_right_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/fastscroll_label_right_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_bullet_key_permission.png b/core/res/res/drawable-hdpi/ic_bullet_key_permission.png
index a7eaec5..4b9bf53 100644
--- a/core/res/res/drawable-hdpi/ic_bullet_key_permission.png
+++ b/core/res/res/drawable-hdpi/ic_bullet_key_permission.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_answer_active.png b/core/res/res/drawable-hdpi/ic_lockscreen_answer_active.png
index 683a575..d2ced31 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_answer_active.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_answer_active.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_answer_focused.png b/core/res/res/drawable-hdpi/ic_lockscreen_answer_focused.png
index bdece9f..4ec4508 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_answer_focused.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_answer_focused.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_answer_normal.png b/core/res/res/drawable-hdpi/ic_lockscreen_answer_normal.png
index 6a8ab24..7b8168c 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_answer_normal.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_answer_normal.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_decline_focused.png b/core/res/res/drawable-hdpi/ic_lockscreen_decline_focused.png
index f2fceaa..22783c9 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_decline_focused.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_decline_focused.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_decline_normal.png b/core/res/res/drawable-hdpi/ic_lockscreen_decline_normal.png
index e005ffc..c6a2e17 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_decline_normal.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_decline_normal.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_handle_normal.png b/core/res/res/drawable-hdpi/ic_lockscreen_handle_normal.png
index f41ad95..5805ce1 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_handle_normal.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_handle_normal.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_handle_pressed.png b/core/res/res/drawable-hdpi/ic_lockscreen_handle_pressed.png
index 98ab6e9..6429517 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_handle_pressed.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_handle_pressed.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_silent_focused.png b/core/res/res/drawable-hdpi/ic_lockscreen_silent_focused.png
index 651b837..c995c87 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_silent_focused.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_silent_focused.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_silent_normal.png b/core/res/res/drawable-hdpi/ic_lockscreen_silent_normal.png
index babab1d..c75363b 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_silent_normal.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_silent_normal.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_soundon_focused.png b/core/res/res/drawable-hdpi/ic_lockscreen_soundon_focused.png
index d000866..69885ea 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_soundon_focused.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_soundon_focused.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_soundon_normal.png b/core/res/res/drawable-hdpi/ic_lockscreen_soundon_normal.png
index 82133d0..8cf2b4b 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_soundon_normal.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_soundon_normal.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_text_focusde.png b/core/res/res/drawable-hdpi/ic_lockscreen_text_focusde.png
index 26df6b2..60873dd7 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_text_focusde.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_text_focusde.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_lockscreen_unlock_activated.png b/core/res/res/drawable-hdpi/ic_lockscreen_unlock_activated.png
index 9e36918..374a62a 100644
--- a/core/res/res/drawable-hdpi/ic_lockscreen_unlock_activated.png
+++ b/core/res/res/drawable-hdpi/ic_lockscreen_unlock_activated.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_media_next.png b/core/res/res/drawable-hdpi/ic_media_next.png
index c74703e..f5ba824 100644
--- a/core/res/res/drawable-hdpi/ic_media_next.png
+++ b/core/res/res/drawable-hdpi/ic_media_next.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_media_previous.png b/core/res/res/drawable-hdpi/ic_media_previous.png
index 15dc390..40ecb00 100644
--- a/core/res/res/drawable-hdpi/ic_media_previous.png
+++ b/core/res/res/drawable-hdpi/ic_media_previous.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_menu_cut_holo_dark.png b/core/res/res/drawable-hdpi/ic_menu_cut_holo_dark.png
index 81c52b0..3e00747 100644
--- a/core/res/res/drawable-hdpi/ic_menu_cut_holo_dark.png
+++ b/core/res/res/drawable-hdpi/ic_menu_cut_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_menu_cut_holo_light.png b/core/res/res/drawable-hdpi/ic_menu_cut_holo_light.png
index 15500c3..c760936 100644
--- a/core/res/res/drawable-hdpi/ic_menu_cut_holo_light.png
+++ b/core/res/res/drawable-hdpi/ic_menu_cut_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/indicator_code_lock_point_area_default_holo.png b/core/res/res/drawable-hdpi/indicator_code_lock_point_area_default_holo.png
index 28b2578..e77921c 100644
--- a/core/res/res/drawable-hdpi/indicator_code_lock_point_area_default_holo.png
+++ b/core/res/res/drawable-hdpi/indicator_code_lock_point_area_default_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/indicator_code_lock_point_area_green_holo.png b/core/res/res/drawable-hdpi/indicator_code_lock_point_area_green_holo.png
index 545cc09..b5e714a 100644
--- a/core/res/res/drawable-hdpi/indicator_code_lock_point_area_green_holo.png
+++ b/core/res/res/drawable-hdpi/indicator_code_lock_point_area_green_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/indicator_code_lock_point_area_red_holo.png b/core/res/res/drawable-hdpi/indicator_code_lock_point_area_red_holo.png
index 9176b33..c659d94 100644
--- a/core/res/res/drawable-hdpi/indicator_code_lock_point_area_red_holo.png
+++ b/core/res/res/drawable-hdpi/indicator_code_lock_point_area_red_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/list_selector_background_disabled.9.png b/core/res/res/drawable-hdpi/list_selector_background_disabled.9.png
index f8092ea..05b1419 100644
--- a/core/res/res/drawable-hdpi/list_selector_background_disabled.9.png
+++ b/core/res/res/drawable-hdpi/list_selector_background_disabled.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_disabled_focused_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_down_disabled_focused_holo_dark.png
index fb34a6d..9584649 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_disabled_focused_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_disabled_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_disabled_focused_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_down_disabled_focused_holo_light.png
index 87b2ad67..5c37873 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_disabled_focused_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_disabled_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_disabled_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_down_disabled_holo_dark.png
index 1655fea..b5faf6f 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_disabled_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_disabled_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_disabled_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_down_disabled_holo_light.png
index 61cfe7a..041412b 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_disabled_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_disabled_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_focused_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_down_focused_holo_dark.png
index 43e2e89..9ff4cce 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_focused_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_focused_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_down_focused_holo_light.png
index 7d80ff6..a556e00 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_focused_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_longpressed_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_down_longpressed_holo_dark.png
index cc21a1c..9353511 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_longpressed_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_longpressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_longpressed_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_down_longpressed_holo_light.png
index cc21a1c..9353511 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_longpressed_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_longpressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_normal_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_down_normal_holo_dark.png
index 3c9c192..2ca591f 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_normal_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_normal_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_normal_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_down_normal_holo_light.png
index 6511cd2..1275a2f 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_normal_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_normal_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_pressed_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_down_pressed_holo_dark.png
index 7b135ea..9c23a18 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_pressed_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_pressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_down_pressed_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_down_pressed_holo_light.png
index 7b135ea..9c23a18 100644
--- a/core/res/res/drawable-hdpi/numberpicker_down_pressed_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_down_pressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_disabled_focused_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_up_disabled_focused_holo_dark.png
index b6a85a2..159913c 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_disabled_focused_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_disabled_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_disabled_focused_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_up_disabled_focused_holo_light.png
index 50d979e..cfee4b7 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_disabled_focused_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_disabled_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_disabled_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_up_disabled_holo_dark.png
index 608dd52..e5f0430 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_disabled_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_disabled_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_disabled_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_up_disabled_holo_light.png
index 96ff781..7e4ec4a 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_disabled_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_disabled_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_focused_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_up_focused_holo_dark.png
index a48bf2e..df374c4 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_focused_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_focused_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_up_focused_holo_light.png
index b69589b..d6b9c67 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_focused_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_longpressed_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_up_longpressed_holo_dark.png
index 5adfb04..69474e3 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_longpressed_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_longpressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_longpressed_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_up_longpressed_holo_light.png
index 5adfb04..69474e3 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_longpressed_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_longpressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_normal_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_up_normal_holo_dark.png
index ff34463..a2fc32a 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_normal_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_normal_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_normal_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_up_normal_holo_light.png
index 0bcfd67..c4b58b7 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_normal_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_normal_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_pressed_holo_dark.png b/core/res/res/drawable-hdpi/numberpicker_up_pressed_holo_dark.png
index 00092cc..358a13f 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_pressed_holo_dark.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_pressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/numberpicker_up_pressed_holo_light.png b/core/res/res/drawable-hdpi/numberpicker_up_pressed_holo_light.png
index 00092cc..358a13f 100644
--- a/core/res/res/drawable-hdpi/numberpicker_up_pressed_holo_light.png
+++ b/core/res/res/drawable-hdpi/numberpicker_up_pressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/presence_away.png b/core/res/res/drawable-hdpi/presence_away.png
index fe5b880..455fec1 100644
--- a/core/res/res/drawable-hdpi/presence_away.png
+++ b/core/res/res/drawable-hdpi/presence_away.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_big_half_holo_dark.png b/core/res/res/drawable-hdpi/rate_star_big_half_holo_dark.png
index e3131b1..c6d1cd1 100644
--- a/core/res/res/drawable-hdpi/rate_star_big_half_holo_dark.png
+++ b/core/res/res/drawable-hdpi/rate_star_big_half_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_big_half_holo_light.png b/core/res/res/drawable-hdpi/rate_star_big_half_holo_light.png
index cdc94a1..89afee8 100644
--- a/core/res/res/drawable-hdpi/rate_star_big_half_holo_light.png
+++ b/core/res/res/drawable-hdpi/rate_star_big_half_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_big_off_holo_dark.png b/core/res/res/drawable-hdpi/rate_star_big_off_holo_dark.png
index d83522a..58a2d40 100644
--- a/core/res/res/drawable-hdpi/rate_star_big_off_holo_dark.png
+++ b/core/res/res/drawable-hdpi/rate_star_big_off_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_big_off_holo_light.png b/core/res/res/drawable-hdpi/rate_star_big_off_holo_light.png
index 2af7814..fdbc011 100644
--- a/core/res/res/drawable-hdpi/rate_star_big_off_holo_light.png
+++ b/core/res/res/drawable-hdpi/rate_star_big_off_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_big_on_holo_dark.png b/core/res/res/drawable-hdpi/rate_star_big_on_holo_dark.png
index e4b766d..ec3394e 100644
--- a/core/res/res/drawable-hdpi/rate_star_big_on_holo_dark.png
+++ b/core/res/res/drawable-hdpi/rate_star_big_on_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_big_on_holo_light.png b/core/res/res/drawable-hdpi/rate_star_big_on_holo_light.png
index edd264a..3e90f35 100644
--- a/core/res/res/drawable-hdpi/rate_star_big_on_holo_light.png
+++ b/core/res/res/drawable-hdpi/rate_star_big_on_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_med_half_holo_light.png b/core/res/res/drawable-hdpi/rate_star_med_half_holo_light.png
index 3ff3bbd..ae5e49b 100644
--- a/core/res/res/drawable-hdpi/rate_star_med_half_holo_light.png
+++ b/core/res/res/drawable-hdpi/rate_star_med_half_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_med_off_holo_light.png b/core/res/res/drawable-hdpi/rate_star_med_off_holo_light.png
index ce9fc25..73183ad 100644
--- a/core/res/res/drawable-hdpi/rate_star_med_off_holo_light.png
+++ b/core/res/res/drawable-hdpi/rate_star_med_off_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_med_on_holo_light.png b/core/res/res/drawable-hdpi/rate_star_med_on_holo_light.png
index a6fdcff..279427b 100644
--- a/core/res/res/drawable-hdpi/rate_star_med_on_holo_light.png
+++ b/core/res/res/drawable-hdpi/rate_star_med_on_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_small_half_holo_dark.png b/core/res/res/drawable-hdpi/rate_star_small_half_holo_dark.png
index 4fb14f9..e0edec9 100644
--- a/core/res/res/drawable-hdpi/rate_star_small_half_holo_dark.png
+++ b/core/res/res/drawable-hdpi/rate_star_small_half_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_small_half_holo_light.png b/core/res/res/drawable-hdpi/rate_star_small_half_holo_light.png
index 667b8e2..d61b613 100644
--- a/core/res/res/drawable-hdpi/rate_star_small_half_holo_light.png
+++ b/core/res/res/drawable-hdpi/rate_star_small_half_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_small_off_holo_dark.png b/core/res/res/drawable-hdpi/rate_star_small_off_holo_dark.png
index e19cf7a..0bba5ba 100644
--- a/core/res/res/drawable-hdpi/rate_star_small_off_holo_dark.png
+++ b/core/res/res/drawable-hdpi/rate_star_small_off_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_small_off_holo_light.png b/core/res/res/drawable-hdpi/rate_star_small_off_holo_light.png
index 8886006..f8d978a 100644
--- a/core/res/res/drawable-hdpi/rate_star_small_off_holo_light.png
+++ b/core/res/res/drawable-hdpi/rate_star_small_off_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_small_on_holo_dark.png b/core/res/res/drawable-hdpi/rate_star_small_on_holo_dark.png
index bc5d3db..b7f8e62 100644
--- a/core/res/res/drawable-hdpi/rate_star_small_on_holo_dark.png
+++ b/core/res/res/drawable-hdpi/rate_star_small_on_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/rate_star_small_on_holo_light.png b/core/res/res/drawable-hdpi/rate_star_small_on_holo_light.png
index 1041008..d8cdd19 100644
--- a/core/res/res/drawable-hdpi/rate_star_small_on_holo_light.png
+++ b/core/res/res/drawable-hdpi/rate_star_small_on_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/scrubber_control_focused_holo.png b/core/res/res/drawable-hdpi/scrubber_control_focused_holo.png
index 4048260..f830a03 100644
--- a/core/res/res/drawable-hdpi/scrubber_control_focused_holo.png
+++ b/core/res/res/drawable-hdpi/scrubber_control_focused_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/scrubber_control_normal_holo.png b/core/res/res/drawable-hdpi/scrubber_control_normal_holo.png
index 90e9c9c..03f030b 100644
--- a/core/res/res/drawable-hdpi/scrubber_control_normal_holo.png
+++ b/core/res/res/drawable-hdpi/scrubber_control_normal_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/spinner_16_inner_holo.png b/core/res/res/drawable-hdpi/spinner_16_inner_holo.png
index 0166938..604490d 100644
--- a/core/res/res/drawable-hdpi/spinner_16_inner_holo.png
+++ b/core/res/res/drawable-hdpi/spinner_16_inner_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/spinner_20_inner_holo.png b/core/res/res/drawable-hdpi/spinner_20_inner_holo.png
index ffad720..2705a06 100644
--- a/core/res/res/drawable-hdpi/spinner_20_inner_holo.png
+++ b/core/res/res/drawable-hdpi/spinner_20_inner_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/spinner_20_outer_holo.png b/core/res/res/drawable-hdpi/spinner_20_outer_holo.png
index f2523f4..1954c8c 100644
--- a/core/res/res/drawable-hdpi/spinner_20_outer_holo.png
+++ b/core/res/res/drawable-hdpi/spinner_20_outer_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/spinner_48_inner_holo.png b/core/res/res/drawable-hdpi/spinner_48_inner_holo.png
index f8e3fef..df1573b 100644
--- a/core/res/res/drawable-hdpi/spinner_48_inner_holo.png
+++ b/core/res/res/drawable-hdpi/spinner_48_inner_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/spinner_48_outer_holo.png b/core/res/res/drawable-hdpi/spinner_48_outer_holo.png
index 04c5fb5..8dcdc17 100644
--- a/core/res/res/drawable-hdpi/spinner_48_outer_holo.png
+++ b/core/res/res/drawable-hdpi/spinner_48_outer_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/spinner_76_inner_holo.png b/core/res/res/drawable-hdpi/spinner_76_inner_holo.png
index a28a6d1..eff7117 100644
--- a/core/res/res/drawable-hdpi/spinner_76_inner_holo.png
+++ b/core/res/res/drawable-hdpi/spinner_76_inner_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/spinner_76_outer_holo.png b/core/res/res/drawable-hdpi/spinner_76_outer_holo.png
index 3d5aa46..50461b5 100644
--- a/core/res/res/drawable-hdpi/spinner_76_outer_holo.png
+++ b/core/res/res/drawable-hdpi/spinner_76_outer_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_notify_call_mute.png b/core/res/res/drawable-hdpi/stat_notify_call_mute.png
index 1446fa7..7f87ee7 100644
--- a/core/res/res/drawable-hdpi/stat_notify_call_mute.png
+++ b/core/res/res/drawable-hdpi/stat_notify_call_mute.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_notify_wifi_in_range.png b/core/res/res/drawable-hdpi/stat_notify_wifi_in_range.png
index f3aaa27..8148ab8 100644
--- a/core/res/res/drawable-hdpi/stat_notify_wifi_in_range.png
+++ b/core/res/res/drawable-hdpi/stat_notify_wifi_in_range.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_download_anim1.png b/core/res/res/drawable-hdpi/stat_sys_download_anim1.png
index 3e27c52..ff29bbf 100644
--- a/core/res/res/drawable-hdpi/stat_sys_download_anim1.png
+++ b/core/res/res/drawable-hdpi/stat_sys_download_anim1.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_speakerphone.png b/core/res/res/drawable-hdpi/stat_sys_speakerphone.png
index a9af4a8..765be61 100644
--- a/core/res/res/drawable-hdpi/stat_sys_speakerphone.png
+++ b/core/res/res/drawable-hdpi/stat_sys_speakerphone.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_tether_wifi.png b/core/res/res/drawable-hdpi/stat_sys_tether_wifi.png
index 0b8dbf5..e0bd38b 100644
--- a/core/res/res/drawable-hdpi/stat_sys_tether_wifi.png
+++ b/core/res/res/drawable-hdpi/stat_sys_tether_wifi.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_upload_anim1.png b/core/res/res/drawable-hdpi/stat_sys_upload_anim1.png
index 2754428..fff81d7 100644
--- a/core/res/res/drawable-hdpi/stat_sys_upload_anim1.png
+++ b/core/res/res/drawable-hdpi/stat_sys_upload_anim1.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_sys_upload_anim3.png b/core/res/res/drawable-hdpi/stat_sys_upload_anim3.png
index 3590062..cabdc39 100644
--- a/core/res/res/drawable-hdpi/stat_sys_upload_anim3.png
+++ b/core/res/res/drawable-hdpi/stat_sys_upload_anim3.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/sym_def_app_icon.png b/core/res/res/drawable-hdpi/sym_def_app_icon.png
index c8a38ed..96a442e 100644
--- a/core/res/res/drawable-hdpi/sym_def_app_icon.png
+++ b/core/res/res/drawable-hdpi/sym_def_app_icon.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/text_cursor_holo_dark.9.png b/core/res/res/drawable-hdpi/text_cursor_holo_dark.9.png
deleted file mode 100644
index ae77fa0..0000000
--- a/core/res/res/drawable-hdpi/text_cursor_holo_dark.9.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/text_cursor_holo_light.9.png b/core/res/res/drawable-hdpi/text_cursor_holo_light.9.png
deleted file mode 100644
index c6bdfcc..0000000
--- a/core/res/res/drawable-hdpi/text_cursor_holo_light.9.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/text_select_handle_left.png b/core/res/res/drawable-hdpi/text_select_handle_left.png
index 5adc2e1..eead92c 100644
--- a/core/res/res/drawable-hdpi/text_select_handle_left.png
+++ b/core/res/res/drawable-hdpi/text_select_handle_left.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/text_select_handle_middle.png b/core/res/res/drawable-hdpi/text_select_handle_middle.png
index b7a472a..185d839 100644
--- a/core/res/res/drawable-hdpi/text_select_handle_middle.png
+++ b/core/res/res/drawable-hdpi/text_select_handle_middle.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/text_select_handle_right.png b/core/res/res/drawable-hdpi/text_select_handle_right.png
index cf94179..e9fceec 100644
--- a/core/res/res/drawable-hdpi/text_select_handle_right.png
+++ b/core/res/res/drawable-hdpi/text_select_handle_right.png
Binary files differ
diff --git a/core/res/res/drawable-ldpi/stat_sys_adb.png b/core/res/res/drawable-ldpi/stat_sys_adb.png
index aec8d90..86b945b 100644
--- a/core/res/res/drawable-ldpi/stat_sys_adb.png
+++ b/core/res/res/drawable-ldpi/stat_sys_adb.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ab_share_pack_holo_light.9.png b/core/res/res/drawable-mdpi/ab_share_pack_holo_light.9.png
index 1983c68..8f10bd5 100644
--- a/core/res/res/drawable-mdpi/ab_share_pack_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/ab_share_pack_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_check_on_pressed_holo_dark.png b/core/res/res/drawable-mdpi/btn_check_on_pressed_holo_dark.png
index b70db89..9835b0f 100644
--- a/core/res/res/drawable-mdpi/btn_check_on_pressed_holo_dark.png
+++ b/core/res/res/drawable-mdpi/btn_check_on_pressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_code_lock_touched.png b/core/res/res/drawable-mdpi/btn_code_lock_touched.png
index 98a3b6d..2dfe0f6 100644
--- a/core/res/res/drawable-mdpi/btn_code_lock_touched.png
+++ b/core/res/res/drawable-mdpi/btn_code_lock_touched.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_rating_star_on_disabled_focused_holo_light.png b/core/res/res/drawable-mdpi/btn_rating_star_on_disabled_focused_holo_light.png
index 816e146..26841bd 100644
--- a/core/res/res/drawable-mdpi/btn_rating_star_on_disabled_focused_holo_light.png
+++ b/core/res/res/drawable-mdpi/btn_rating_star_on_disabled_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_rating_star_on_disabled_holo_light.png b/core/res/res/drawable-mdpi/btn_rating_star_on_disabled_holo_light.png
index 4f4eff2..4fe7483 100644
--- a/core/res/res/drawable-mdpi/btn_rating_star_on_disabled_holo_light.png
+++ b/core/res/res/drawable-mdpi/btn_rating_star_on_disabled_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_rating_star_on_focused_holo_light.png b/core/res/res/drawable-mdpi/btn_rating_star_on_focused_holo_light.png
index afaa8ca..ec3b84d 100644
--- a/core/res/res/drawable-mdpi/btn_rating_star_on_focused_holo_light.png
+++ b/core/res/res/drawable-mdpi/btn_rating_star_on_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_rating_star_on_normal_holo_light.png b/core/res/res/drawable-mdpi/btn_rating_star_on_normal_holo_light.png
index b7d9079..537f4f0 100644
--- a/core/res/res/drawable-mdpi/btn_rating_star_on_normal_holo_light.png
+++ b/core/res/res/drawable-mdpi/btn_rating_star_on_normal_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_rating_star_on_pressed_holo_light.png b/core/res/res/drawable-mdpi/btn_rating_star_on_pressed_holo_light.png
index 994eb0c..0409d4b 100644
--- a/core/res/res/drawable-mdpi/btn_rating_star_on_pressed_holo_light.png
+++ b/core/res/res/drawable-mdpi/btn_rating_star_on_pressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/fastscroll_label_left_holo_light.9.png b/core/res/res/drawable-mdpi/fastscroll_label_left_holo_light.9.png
index 987c097..cee85bb 100644
--- a/core/res/res/drawable-mdpi/fastscroll_label_left_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/fastscroll_label_left_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/fastscroll_label_right_holo_dark.9.png b/core/res/res/drawable-mdpi/fastscroll_label_right_holo_dark.9.png
index 8d87032..bd496f8 100644
--- a/core/res/res/drawable-mdpi/fastscroll_label_right_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/fastscroll_label_right_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_bullet_key_permission.png b/core/res/res/drawable-mdpi/ic_bullet_key_permission.png
index 47913f6..22f25ca 100644
--- a/core/res/res/drawable-mdpi/ic_bullet_key_permission.png
+++ b/core/res/res/drawable-mdpi/ic_bullet_key_permission.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_media_next.png b/core/res/res/drawable-mdpi/ic_media_next.png
index a6feed0..acef506 100644
--- a/core/res/res/drawable-mdpi/ic_media_next.png
+++ b/core/res/res/drawable-mdpi/ic_media_next.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_media_previous.png b/core/res/res/drawable-mdpi/ic_media_previous.png
index 0163d09..940d6a4 100644
--- a/core/res/res/drawable-mdpi/ic_media_previous.png
+++ b/core/res/res/drawable-mdpi/ic_media_previous.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_menu_cut_holo_dark.png b/core/res/res/drawable-mdpi/ic_menu_cut_holo_dark.png
index 85f3cb2..baa5427 100644
--- a/core/res/res/drawable-mdpi/ic_menu_cut_holo_dark.png
+++ b/core/res/res/drawable-mdpi/ic_menu_cut_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_menu_cut_holo_light.png b/core/res/res/drawable-mdpi/ic_menu_cut_holo_light.png
index 77f92fb..8e6a93f 100644
--- a/core/res/res/drawable-mdpi/ic_menu_cut_holo_light.png
+++ b/core/res/res/drawable-mdpi/ic_menu_cut_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/indicator_code_lock_point_area_red_holo.png b/core/res/res/drawable-mdpi/indicator_code_lock_point_area_red_holo.png
index 8434741..989e76b 100644
--- a/core/res/res/drawable-mdpi/indicator_code_lock_point_area_red_holo.png
+++ b/core/res/res/drawable-mdpi/indicator_code_lock_point_area_red_holo.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/list_selector_background_disabled.9.png b/core/res/res/drawable-mdpi/list_selector_background_disabled.9.png
index dbe3953..8ad0b32 100644
--- a/core/res/res/drawable-mdpi/list_selector_background_disabled.9.png
+++ b/core/res/res/drawable-mdpi/list_selector_background_disabled.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_disabled_focused_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_down_disabled_focused_holo_dark.png
index 1f29da2..7d9637a 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_disabled_focused_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_disabled_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_disabled_focused_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_down_disabled_focused_holo_light.png
index a27f5aa..f7409e4 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_disabled_focused_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_disabled_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_disabled_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_down_disabled_holo_dark.png
index 34268af..9c2b833 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_disabled_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_disabled_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_disabled_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_down_disabled_holo_light.png
index 304f800..dcf2fb7 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_disabled_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_disabled_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_focused_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_down_focused_holo_dark.png
index 583542b..b63c510d 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_focused_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_focused_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_down_focused_holo_light.png
index d15bd16..55312a1 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_focused_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_longpressed_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_down_longpressed_holo_dark.png
index 9a5d79f..48e300c 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_longpressed_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_longpressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_longpressed_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_down_longpressed_holo_light.png
index 9a5d79f..48e300c 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_longpressed_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_longpressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_normal_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_down_normal_holo_dark.png
index 8051d64..1558d3d 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_normal_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_normal_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_normal_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_down_normal_holo_light.png
index bcd34e9..6b6e7e1 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_normal_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_normal_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_pressed_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_down_pressed_holo_dark.png
index cf4bdb6..081ea4e 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_pressed_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_pressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_down_pressed_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_down_pressed_holo_light.png
index cf4bdb6..081ea4e 100644
--- a/core/res/res/drawable-mdpi/numberpicker_down_pressed_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_down_pressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_disabled_focused_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_up_disabled_focused_holo_dark.png
index 0535ff7..739a8d7 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_disabled_focused_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_disabled_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_disabled_focused_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_up_disabled_focused_holo_light.png
index 360284d..bd440f2 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_disabled_focused_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_disabled_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_disabled_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_up_disabled_holo_dark.png
index 1e0e92c..cf856a1 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_disabled_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_disabled_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_disabled_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_up_disabled_holo_light.png
index 14bcce9..6665953 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_disabled_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_disabled_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_focused_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_up_focused_holo_dark.png
index 6ed2cf0..d63d797 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_focused_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_focused_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_up_focused_holo_light.png
index 015a8cf..22b6dbd 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_focused_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_longpressed_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_up_longpressed_holo_dark.png
index 8bb44f2..4bcce98 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_longpressed_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_longpressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_longpressed_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_up_longpressed_holo_light.png
index 8bb44f2..4bcce98 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_longpressed_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_longpressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_normal_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_up_normal_holo_dark.png
index 6ab5f23..12ba823 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_normal_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_normal_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_normal_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_up_normal_holo_light.png
index 65ec302..d841f5a 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_normal_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_normal_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_pressed_holo_dark.png b/core/res/res/drawable-mdpi/numberpicker_up_pressed_holo_dark.png
index 34d3228..0318c5f 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_pressed_holo_dark.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_pressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/numberpicker_up_pressed_holo_light.png b/core/res/res/drawable-mdpi/numberpicker_up_pressed_holo_light.png
index 34d3228..0318c5f 100644
--- a/core/res/res/drawable-mdpi/numberpicker_up_pressed_holo_light.png
+++ b/core/res/res/drawable-mdpi/numberpicker_up_pressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/scrubber_control_pressed_holo.png b/core/res/res/drawable-mdpi/scrubber_control_pressed_holo.png
index ba53c0b..cb99fa3 100644
--- a/core/res/res/drawable-mdpi/scrubber_control_pressed_holo.png
+++ b/core/res/res/drawable-mdpi/scrubber_control_pressed_holo.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_notify_call_mute.png b/core/res/res/drawable-mdpi/stat_notify_call_mute.png
index 8797a09..58e0cbc 100644
--- a/core/res/res/drawable-mdpi/stat_notify_call_mute.png
+++ b/core/res/res/drawable-mdpi/stat_notify_call_mute.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_notify_wifi_in_range.png b/core/res/res/drawable-mdpi/stat_notify_wifi_in_range.png
index 747cb97..b7e2a6a 100644
--- a/core/res/res/drawable-mdpi/stat_notify_wifi_in_range.png
+++ b/core/res/res/drawable-mdpi/stat_notify_wifi_in_range.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_sys_speakerphone.png b/core/res/res/drawable-mdpi/stat_sys_speakerphone.png
index e8c6374..d82704e 100644
--- a/core/res/res/drawable-mdpi/stat_sys_speakerphone.png
+++ b/core/res/res/drawable-mdpi/stat_sys_speakerphone.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/sym_def_app_icon.png b/core/res/res/drawable-mdpi/sym_def_app_icon.png
index b3e10f6..359047d 100644
--- a/core/res/res/drawable-mdpi/sym_def_app_icon.png
+++ b/core/res/res/drawable-mdpi/sym_def_app_icon.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/text_cursor_holo_dark.9.png b/core/res/res/drawable-mdpi/text_cursor_holo_dark.9.png
deleted file mode 100644
index ae77fa0..0000000
--- a/core/res/res/drawable-mdpi/text_cursor_holo_dark.9.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/text_cursor_holo_light.9.png b/core/res/res/drawable-mdpi/text_cursor_holo_light.9.png
deleted file mode 100644
index c6bdfcc..0000000
--- a/core/res/res/drawable-mdpi/text_cursor_holo_light.9.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-nodpi/indicator_code_lock_drag_direction_red_up.png b/core/res/res/drawable-nodpi/indicator_code_lock_drag_direction_red_up.png
new file mode 100644
index 0000000..cc46f19
--- /dev/null
+++ b/core/res/res/drawable-nodpi/indicator_code_lock_drag_direction_red_up.png
Binary files differ
diff --git a/core/res/res/drawable-nodpi/text_cursor_holo_dark.9.png b/core/res/res/drawable-nodpi/text_cursor_holo_dark.9.png
new file mode 100644
index 0000000..450c486
--- /dev/null
+++ b/core/res/res/drawable-nodpi/text_cursor_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-nodpi/text_cursor_holo_light.9.png b/core/res/res/drawable-nodpi/text_cursor_holo_light.9.png
new file mode 100644
index 0000000..22633eb0
--- /dev/null
+++ b/core/res/res/drawable-nodpi/text_cursor_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-sw600dp-hdpi/stat_notify_call_mute.png b/core/res/res/drawable-sw600dp-hdpi/stat_notify_call_mute.png
new file mode 100644
index 0000000..b753764
--- /dev/null
+++ b/core/res/res/drawable-sw600dp-hdpi/stat_notify_call_mute.png
Binary files differ
diff --git a/core/res/res/drawable-sw600dp-hdpi/stat_sys_speakerphone.png b/core/res/res/drawable-sw600dp-hdpi/stat_sys_speakerphone.png
new file mode 100644
index 0000000..b47a9f6
--- /dev/null
+++ b/core/res/res/drawable-sw600dp-hdpi/stat_sys_speakerphone.png
Binary files differ
diff --git a/core/res/res/drawable-sw600dp-mdpi/stat_notify_call_mute.png b/core/res/res/drawable-sw600dp-mdpi/stat_notify_call_mute.png
new file mode 100644
index 0000000..951197c
--- /dev/null
+++ b/core/res/res/drawable-sw600dp-mdpi/stat_notify_call_mute.png
Binary files differ
diff --git a/core/res/res/drawable-sw600dp-mdpi/stat_sys_speakerphone.png b/core/res/res/drawable-sw600dp-mdpi/stat_sys_speakerphone.png
new file mode 100644
index 0000000..5893db9
--- /dev/null
+++ b/core/res/res/drawable-sw600dp-mdpi/stat_sys_speakerphone.png
Binary files differ
diff --git a/core/res/res/drawable-sw600dp-mdpi/unlock_halo.png b/core/res/res/drawable-sw600dp-mdpi/unlock_halo.png
index c9ed4c7..5ad26b8 100644
--- a/core/res/res/drawable-sw600dp-mdpi/unlock_halo.png
+++ b/core/res/res/drawable-sw600dp-mdpi/unlock_halo.png
Binary files differ
diff --git a/core/res/res/drawable-sw600dp-xhdpi/stat_notify_call_mute.png b/core/res/res/drawable-sw600dp-xhdpi/stat_notify_call_mute.png
new file mode 100644
index 0000000..1d72243
--- /dev/null
+++ b/core/res/res/drawable-sw600dp-xhdpi/stat_notify_call_mute.png
Binary files differ
diff --git a/core/res/res/drawable-sw600dp-xhdpi/stat_sys_speakerphone.png b/core/res/res/drawable-sw600dp-xhdpi/stat_sys_speakerphone.png
new file mode 100644
index 0000000..76dee9e
--- /dev/null
+++ b/core/res/res/drawable-sw600dp-xhdpi/stat_sys_speakerphone.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/fastscroll_label_left_holo_dark.9.png b/core/res/res/drawable-xhdpi/fastscroll_label_left_holo_dark.9.png
index 6e0244f..6a82a64 100644
--- a/core/res/res/drawable-xhdpi/fastscroll_label_left_holo_dark.9.png
+++ b/core/res/res/drawable-xhdpi/fastscroll_label_left_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_bullet_key_permission.png b/core/res/res/drawable-xhdpi/ic_bullet_key_permission.png
index b2db65c..ccbdcc3 100644
--- a/core/res/res/drawable-xhdpi/ic_bullet_key_permission.png
+++ b/core/res/res/drawable-xhdpi/ic_bullet_key_permission.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_media_next.png b/core/res/res/drawable-xhdpi/ic_media_next.png
index 9835c63..726fee7 100644
--- a/core/res/res/drawable-xhdpi/ic_media_next.png
+++ b/core/res/res/drawable-xhdpi/ic_media_next.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_media_previous.png b/core/res/res/drawable-xhdpi/ic_media_previous.png
index 5df5987..59f994d 100644
--- a/core/res/res/drawable-xhdpi/ic_media_previous.png
+++ b/core/res/res/drawable-xhdpi/ic_media_previous.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_menu_cut_holo_dark.png b/core/res/res/drawable-xhdpi/ic_menu_cut_holo_dark.png
index 16632b1..7aa8750 100644
--- a/core/res/res/drawable-xhdpi/ic_menu_cut_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/ic_menu_cut_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/ic_menu_cut_holo_light.png b/core/res/res/drawable-xhdpi/ic_menu_cut_holo_light.png
index 6e007c7..d4e4d81 100644
--- a/core/res/res/drawable-xhdpi/ic_menu_cut_holo_light.png
+++ b/core/res/res/drawable-xhdpi/ic_menu_cut_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/list_selector_background_disabled.9.png b/core/res/res/drawable-xhdpi/list_selector_background_disabled.9.png
index 980bbd7..f039081 100644
--- a/core/res/res/drawable-xhdpi/list_selector_background_disabled.9.png
+++ b/core/res/res/drawable-xhdpi/list_selector_background_disabled.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_disabled.9.png b/core/res/res/drawable-xhdpi/numberpicker_down_disabled.9.png
index 62b267e..ec92ea5 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_disabled.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_disabled.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused.9.png b/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused.9.png
index 5f38c35..03c020d 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused_holo_dark.png
index 1c2f33e..111f57e 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused_holo_light.png
index 4e688bc..d0ef05b 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_disabled_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_disabled_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_down_disabled_holo_dark.png
index dc422f2..ff21941 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_disabled_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_disabled_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_disabled_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_down_disabled_holo_light.png
index afc02db..3e9bdda 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_disabled_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_disabled_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_focused_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_down_focused_holo_dark.png
index 3604013..0462fca 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_focused_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_focused_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_down_focused_holo_light.png
index a16cd38..a488e8e 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_focused_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_longpressed_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_down_longpressed_holo_dark.png
index b975b63..f61b076 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_longpressed_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_longpressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_longpressed_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_down_longpressed_holo_light.png
index b975b63..f61b076 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_longpressed_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_longpressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_normal.9.png b/core/res/res/drawable-xhdpi/numberpicker_down_normal.9.png
index b1d3e7b..8637414 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_normal.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_normal.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_normal_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_down_normal_holo_dark.png
index 39cdb93..211944e 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_normal_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_normal_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_normal_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_down_normal_holo_light.png
index 2a14ac5..12bc11a 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_normal_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_normal_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_pressed.9.png b/core/res/res/drawable-xhdpi/numberpicker_down_pressed.9.png
index e61c469..bb56365 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_pressed.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_pressed.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_pressed_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_down_pressed_holo_dark.png
index 4827377..635184c 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_pressed_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_pressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_pressed_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_down_pressed_holo_light.png
index 4827377..635184c 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_pressed_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_pressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_down_selected.9.png b/core/res/res/drawable-xhdpi/numberpicker_down_selected.9.png
index ed0c016..4a076f6 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_down_selected.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_down_selected.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_input_disabled.9.png b/core/res/res/drawable-xhdpi/numberpicker_input_disabled.9.png
index 279087c..d176022 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_input_disabled.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_input_disabled.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_input_normal.9.png b/core/res/res/drawable-xhdpi/numberpicker_input_normal.9.png
index 1b3467a..dcacfcf 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_input_normal.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_input_normal.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_input_pressed.9.png b/core/res/res/drawable-xhdpi/numberpicker_input_pressed.9.png
index 930415e..f8cb9e5 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_input_pressed.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_input_pressed.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_input_selected.9.png b/core/res/res/drawable-xhdpi/numberpicker_input_selected.9.png
index 5240d08..38c429f 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_input_selected.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_input_selected.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_disabled.9.png b/core/res/res/drawable-xhdpi/numberpicker_up_disabled.9.png
index 4b79112..a1d8ae1 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_disabled.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_disabled.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused.9.png b/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused.9.png
index 6c2f397..0256f32 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused_holo_dark.png
index 97ea0b5..470e569 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused_holo_light.png
index e59e2a7..16df74d 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_disabled_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_disabled_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_up_disabled_holo_dark.png
index 3b8fa7f..edd4c04 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_disabled_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_disabled_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_disabled_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_up_disabled_holo_light.png
index 77a1dd4..d8f459a 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_disabled_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_disabled_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_focused_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_up_focused_holo_dark.png
index 24c2d84..08bf241 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_focused_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_focused_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_focused_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_up_focused_holo_light.png
index b2566dc3..b2c40f1 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_focused_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_focused_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_longpressed_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_up_longpressed_holo_dark.png
index 7075af7..f4f7331 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_longpressed_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_longpressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_longpressed_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_up_longpressed_holo_light.png
index 7075af7..f4f7331 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_longpressed_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_longpressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_normal.9.png b/core/res/res/drawable-xhdpi/numberpicker_up_normal.9.png
index 699a9f5..f6746a6 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_normal.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_normal.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_normal_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_up_normal_holo_dark.png
index 11b60a9..83650b1 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_normal_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_normal_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_normal_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_up_normal_holo_light.png
index 074fae5..78085d3 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_normal_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_normal_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_pressed.9.png b/core/res/res/drawable-xhdpi/numberpicker_up_pressed.9.png
index 5504fee..1071c73 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_pressed.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_pressed.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_pressed_holo_dark.png b/core/res/res/drawable-xhdpi/numberpicker_up_pressed_holo_dark.png
index 2310f83..b8f6849 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_pressed_holo_dark.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_pressed_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_pressed_holo_light.png b/core/res/res/drawable-xhdpi/numberpicker_up_pressed_holo_light.png
index 2310f83..b8f6849 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_pressed_holo_light.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_pressed_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/numberpicker_up_selected.9.png b/core/res/res/drawable-xhdpi/numberpicker_up_selected.9.png
index 585cf30..f446d48 100644
--- a/core/res/res/drawable-xhdpi/numberpicker_up_selected.9.png
+++ b/core/res/res/drawable-xhdpi/numberpicker_up_selected.9.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/spinner_16_inner_holo.png b/core/res/res/drawable-xhdpi/spinner_16_inner_holo.png
index 9afd52f..830aa27 100644
--- a/core/res/res/drawable-xhdpi/spinner_16_inner_holo.png
+++ b/core/res/res/drawable-xhdpi/spinner_16_inner_holo.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/stat_notify_call_mute.png b/core/res/res/drawable-xhdpi/stat_notify_call_mute.png
index 4135fea..adbd7b1 100644
--- a/core/res/res/drawable-xhdpi/stat_notify_call_mute.png
+++ b/core/res/res/drawable-xhdpi/stat_notify_call_mute.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/stat_notify_wifi_in_range.png b/core/res/res/drawable-xhdpi/stat_notify_wifi_in_range.png
index 6bb7512..0dbae57 100644
--- a/core/res/res/drawable-xhdpi/stat_notify_wifi_in_range.png
+++ b/core/res/res/drawable-xhdpi/stat_notify_wifi_in_range.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/stat_sys_speakerphone.png b/core/res/res/drawable-xhdpi/stat_sys_speakerphone.png
index 3ac1b88..51e648c 100644
--- a/core/res/res/drawable-xhdpi/stat_sys_speakerphone.png
+++ b/core/res/res/drawable-xhdpi/stat_sys_speakerphone.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/sym_def_app_icon.png b/core/res/res/drawable-xhdpi/sym_def_app_icon.png
index f381f86..71c6d76 100644
--- a/core/res/res/drawable-xhdpi/sym_def_app_icon.png
+++ b/core/res/res/drawable-xhdpi/sym_def_app_icon.png
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/text_cursor_holo_dark.9.png b/core/res/res/drawable-xhdpi/text_cursor_holo_dark.9.png
deleted file mode 100644
index e7bb0d4..0000000
--- a/core/res/res/drawable-xhdpi/text_cursor_holo_dark.9.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-xhdpi/text_cursor_holo_light.9.png b/core/res/res/drawable-xhdpi/text_cursor_holo_light.9.png
deleted file mode 100644
index f429785..0000000
--- a/core/res/res/drawable-xhdpi/text_cursor_holo_light.9.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/layout/keyguard_transport_control.xml b/core/res/res/layout/keyguard_transport_control.xml
index 6e24ce2..c951c45 100644
--- a/core/res/res/layout/keyguard_transport_control.xml
+++ b/core/res/res/layout/keyguard_transport_control.xml
@@ -63,7 +63,7 @@
                     android:layout_width="wrap_content"
                     android:layout_height="wrap_content"
                     android:layout_gravity="center"
-                    android:src="@drawable/ic_media_rew"
+                    android:src="@drawable/ic_media_previous"
                     android:clickable="true"
                     android:background="?android:attr/selectableItemBackground"
                     android:padding="10dip"
@@ -94,7 +94,7 @@
                     android:layout_height="wrap_content"
                     android:layout_gravity="center"
                     android:clickable="true"
-                    android:src="@drawable/ic_media_ff"
+                    android:src="@drawable/ic_media_next"
                     android:background="?android:attr/selectableItemBackground"
                     android:padding="10dip"
                     android:contentDescription="@string/lockscreen_transport_next_description"/>
diff --git a/core/res/res/layout/status_bar_latest_event_content_large_icon.xml b/core/res/res/layout/status_bar_latest_event_content_large_icon.xml
index f3f1957..6e8c921 100644
--- a/core/res/res/layout/status_bar_latest_event_content_large_icon.xml
+++ b/core/res/res/layout/status_bar_latest_event_content_large_icon.xml
@@ -25,14 +25,12 @@
         android:fadingEdge="horizontal"
         android:ellipsize="marquee"
         android:visibility="gone"
-        android:alpha="0.7"
         />
     <LinearLayout
         android:id="@+id/line3"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
-        android:alpha="0.7"
         >
         <TextView android:id="@+id/text"
             android:textAppearance="@style/TextAppearance.StatusBar.EventContent"
@@ -62,6 +60,7 @@
             android:scaleType="center"
             android:paddingLeft="8dp"
             android:visibility="gone"
+            android:drawableAlpha="180"
             />
     </LinearLayout>
     <ProgressBar
diff --git a/core/res/res/layout/volume_adjust_item.xml b/core/res/res/layout/volume_adjust_item.xml
index fb900f7..d3fa7e9 100644
--- a/core/res/res/layout/volume_adjust_item.xml
+++ b/core/res/res/layout/volume_adjust_item.xml
@@ -27,7 +27,6 @@
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:padding="16dip"
-        android:layout_marginLeft="8dip"
         android:background="?attr/selectableItemBackground"
         />
 
@@ -38,8 +37,6 @@
         android:layout_height="wrap_content"
         android:layout_weight="1"
         android:padding="16dip"
-        android:layout_marginRight="8dip" />
+        android:layout_marginRight="16dip" />
 
 </LinearLayout>
-
-
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 6c7a981..d7691f7 100755
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -2639,6 +2639,9 @@
         <!-- The offset of the baseline within this view. See {see android.view.View#getBaseline}
              for details -->
         <attr name="baseline" format="dimension" />
+        <!-- @hide The alpha value (0-255) set on the ImageView's drawable. Equivalent
+             to calling ImageView.setAlpha(int), not the same as View.setAlpha(float). -->
+        <attr name="drawableAlpha" format="integer" />
     </declare-styleable>
     <declare-styleable name="ToggleButton">
         <!-- The text for the button when it is checked. -->
diff --git a/core/res/res/values/styles.xml b/core/res/res/values/styles.xml
index 20af731..e60e8b2 100644
--- a/core/res/res/values/styles.xml
+++ b/core/res/res/values/styles.xml
@@ -230,10 +230,11 @@
     <style name="TextAppearance.StatusBar.Icon">
     </style>
     <style name="TextAppearance.StatusBar.EventContent">
-        <item name="android:textColor">?android:attr/textColorPrimary</item>
+        <item name="android:textColor">?android:attr/textColorSecondary</item>
         <item name="android:textSize">13sp</item>
     </style>
     <style name="TextAppearance.StatusBar.EventContent.Title">
+        <item name="android:textColor">?android:attr/textColorPrimary</item>
         <item name="android:textSize">16sp</item>
         <item name="android:textStyle">bold</item>
     </style>
diff --git a/core/tests/coretests/src/android/database/CursorWindowTest.java b/core/tests/coretests/src/android/database/CursorWindowTest.java
index 07e75cb..8c8081c 100644
--- a/core/tests/coretests/src/android/database/CursorWindowTest.java
+++ b/core/tests/coretests/src/android/database/CursorWindowTest.java
@@ -16,17 +16,11 @@
 
 package android.database;
 
-import android.database.AbstractCursor;
 import android.test.suitebuilder.annotation.SmallTest;
-import com.android.common.ArrayListCursor;
 import android.database.CursorWindow;
 import android.test.PerformanceTestCase;
 
-import com.google.android.collect.Lists;
-
-import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Random;
 
 import junit.framework.TestCase;
 
@@ -41,48 +35,6 @@
     }
 
     @SmallTest
-    public void testWriteCursorToWindow() throws Exception {
-        // create cursor
-        String[] colNames = new String[]{"name", "number", "profit"};
-        int colsize = colNames.length;
-        ArrayList<ArrayList> list = createTestList(10, colsize);
-        AbstractCursor cursor = new ArrayListCursor(colNames, (ArrayList<ArrayList>) list);
-
-        // fill window
-        CursorWindow window = new CursorWindow(false);
-        cursor.fillWindow(0, window);
-
-        // read from cursor window
-        for (int i = 0; i < list.size(); i++) {
-            ArrayList<Integer> col = list.get(i);
-            for (int j = 0; j < colsize; j++) {
-                String s = window.getString(i, j);
-                int r2 = col.get(j);
-                int r1 = Integer.parseInt(s);
-                assertEquals(r2, r1);
-            }
-        }
-
-        // test cursor window handle startpos != 0 
-        window.clear();
-        cursor.fillWindow(1, window);
-        // read from cursor from window
-        for (int i = 1; i < list.size(); i++) {
-            ArrayList<Integer> col = list.get(i);
-            for (int j = 0; j < colsize; j++) {
-                String s = window.getString(i, j);
-                int r2 = col.get(j);
-                int r1 = Integer.parseInt(s);
-                assertEquals(r2, r1);
-            }
-        }
-
-        // Clear the window and make sure it's empty
-        window.clear();
-        assertEquals(0, window.getNumRows());
-    }
-
-    @SmallTest
     public void testValuesLocalWindow() {
         doTestValues(new CursorWindow(true));
     }
@@ -124,50 +76,4 @@
         assertTrue(window.putBlob(blob, 0, 6));
         assertTrue(Arrays.equals(blob, window.getBlob(0, 6)));
     }
-
-    @SmallTest
-    public void testNull() {
-        CursorWindow window = getOneByOneWindow();
-
-        // Put in a null value and read it back as various types
-        assertTrue(window.putNull(0, 0));
-        assertNull(window.getString(0, 0));
-        assertEquals(0, window.getLong(0, 0));
-        assertEquals(0.0, window.getDouble(0, 0));
-        assertNull(window.getBlob(0, 0));
-    }
-
-    @SmallTest
-    public void testEmptyString() {
-        CursorWindow window = getOneByOneWindow();
-
-        // put size 0 string and read it back as various types
-        assertTrue(window.putString("", 0, 0));
-        assertEquals("", window.getString(0, 0));
-        assertEquals(0, window.getLong(0, 0));
-        assertEquals(0.0, window.getDouble(0, 0));
-    }
-
-    private CursorWindow getOneByOneWindow() {
-        CursorWindow window = new CursorWindow(false);
-        assertTrue(window.setNumColumns(1));
-        assertTrue(window.allocRow());
-        return window;
-    }
-    
-    private static ArrayList<ArrayList> createTestList(int rows, int cols) {
-        ArrayList<ArrayList> list = Lists.newArrayList();
-        Random generator = new Random();
-
-        for (int i = 0; i < rows; i++) {
-            ArrayList<Integer> col = Lists.newArrayList();
-            list.add(col);
-            for (int j = 0; j < cols; j++) {
-                // generate random number
-                Integer r = generator.nextInt();
-                col.add(r);
-            }
-        }
-        return list;
-    }
 }
diff --git a/core/tests/coretests/src/android/webkit/AccessibilityInjectorTest.java b/core/tests/coretests/src/android/webkit/AccessibilityInjectorTest.java
index 2ed7c52..417a85f 100644
--- a/core/tests/coretests/src/android/webkit/AccessibilityInjectorTest.java
+++ b/core/tests/coretests/src/android/webkit/AccessibilityInjectorTest.java
@@ -1677,7 +1677,7 @@
                         }
                     });
                 }
-                mWebView.loadData(html, "text/html", "utf-8");
+                mWebView.loadData(html, "text/html", null);
             }
         });
         synchronized (sTestLock) {
diff --git a/core/tests/coretests/src/android/widget/SimpleCursorAdapterTest.java b/core/tests/coretests/src/android/widget/SimpleCursorAdapterTest.java
index 7726f02..62466f1 100644
--- a/core/tests/coretests/src/android/widget/SimpleCursorAdapterTest.java
+++ b/core/tests/coretests/src/android/widget/SimpleCursorAdapterTest.java
@@ -16,11 +16,11 @@
 
 package android.widget;
 
-import com.android.common.ArrayListCursor;
 import com.google.android.collect.Lists;
 
 import android.content.Context;
 import android.database.Cursor;
+import android.database.MatrixCursor;
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
 
@@ -52,14 +52,14 @@
         super.setUp();
         
         // all the pieces needed for the various tests
-        mFrom = new String[]{"Column1", "Column2"};
+        mFrom = new String[]{"Column1", "Column2", "_id"};
         mTo = new int[]{com.android.internal.R.id.text1, com.android.internal.R.id.text2};
         mLayout = com.android.internal.R.layout.simple_list_item_2;
         mContext = getContext();
 
         // raw data for building a basic test cursor
         mData2x2 = createTestList(2, 2);
-        mCursor2x2 = new ArrayListCursor(mFrom, mData2x2);
+        mCursor2x2 = createCursor(mFrom, mData2x2);
     }
     
     /**
@@ -77,6 +77,7 @@
                 Integer r = generator.nextInt();
                 col.add(r);
             }
+            col.add(i);
         }
         return list;
     }
@@ -115,7 +116,7 @@
         
         // now put in a different cursor (5 rows)
         ArrayList<ArrayList> data2 = createTestList(5, 2);
-        Cursor c2 = new ArrayListCursor(mFrom, data2);
+        Cursor c2 = createCursor(mFrom, data2);
         ca.changeCursor(c2);
         
         // Now see if we can pull 5 rows from the adapter
@@ -155,8 +156,8 @@
         assertEquals(columns[1], 1);
 
         // Now make a new cursor with similar data but rearrange the columns
-        String[] swappedFrom = new String[]{"Column2", "Column1"};
-        Cursor c2 = new ArrayListCursor(swappedFrom, mData2x2);
+        String[] swappedFrom = new String[]{"Column2", "Column1", "_id"};
+        Cursor c2 = createCursor(swappedFrom, mData2x2);
         ca.changeCursor(c2);
         assertEquals(2, ca.getCount());
 
@@ -235,7 +236,15 @@
         assertEquals(1, viewIds.length);
         assertEquals(com.android.internal.R.id.text2, viewIds[0]);
     }
-    
+
+    private static MatrixCursor createCursor(String[] columns, ArrayList<ArrayList> list) {
+        MatrixCursor cursor = new MatrixCursor(columns, list.size());
+        for (ArrayList row : list) {
+            cursor.addRow(row);
+        }
+        return cursor;
+    }
+
     /**
      * This is simply a way to sneak a look at the protected mFrom() array.  A more API-
      * friendly way to do this would be to mock out a View and a ViewBinder and exercise
diff --git a/core/tests/coretests/src/android/widget/focus/ListWithMailMessages.java b/core/tests/coretests/src/android/widget/focus/ListWithMailMessages.java
index 5de4ad5..5c891f9 100644
--- a/core/tests/coretests/src/android/widget/focus/ListWithMailMessages.java
+++ b/core/tests/coretests/src/android/widget/focus/ListWithMailMessages.java
@@ -120,7 +120,6 @@
         }
 
         final String mimeType = "text/html";
-        final String encoding = "utf-8";
 
 
         @Override
@@ -137,7 +136,7 @@
             subject.setText(message.getSubject());
 
             WebView body = (WebView) messageUi.findViewById(R.id.body);
-            body.loadData(message.getBody(), mimeType, encoding);
+            body.loadData(message.getBody(), mimeType, null);
 //            body.setText(message.getBody());
             body.setFocusable(message.isFocusable());
 
diff --git a/docs/html/guide/developing/devices/emulator.jd b/docs/html/guide/developing/devices/emulator.jd
index fe00531..8211275 100644
--- a/docs/html/guide/developing/devices/emulator.jd
+++ b/docs/html/guide/developing/devices/emulator.jd
@@ -32,6 +32,12 @@
         </ol>
       </li>
     </ol>
+
+  <h2>See also</h2>
+  <ol>
+    <li><a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a></li>
+    <li><a href="{@docRoot}guide/developing/devices/managing-avds.html">Managing AVDs with AVD Manager</a></li>
+  </ol>
 </div>
 </div>
 
@@ -63,8 +69,6 @@
 
 
 
-
-
 <h2  id="overview">Overview</h2>
 
 <p>The Android emulator is a QEMU-based application that provides a virtual ARM
@@ -166,7 +170,8 @@
 
 <p>To stop an emulator instance, just close the emulator's window.</p>
 
-
+<p>For a reference of the emulator's startup commands and keyboard mapping, see
+the <a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a> document.</p>
 
 
 
diff --git a/docs/html/guide/developing/tools/emulator.jd b/docs/html/guide/developing/tools/emulator.jd
index ff667f2..5151ec1 100644
--- a/docs/html/guide/developing/tools/emulator.jd
+++ b/docs/html/guide/developing/tools/emulator.jd
@@ -3,6 +3,25 @@
 parent.link=index.html
 @jd:body
 
+<div id="qv-wrapper">
+<div id="qv">
+
+  <h2>In this document</h2>
+  <ol>
+    <li><a href="#startup-options">Emulator Startup Options</a></li>
+    <li><a href="#KeyMapping">Emulator Keyboard Mapping</a></li>
+  </ol>
+
+  <h2>See also</h2>
+  <ol>
+    <li><a href="{@docRoot}guide/developing/devices/emulator.html">Using the Android Emulator</a></li>
+    <li><a href="{@docRoot}guide/developing/devices/index.html">Managing Virtual Devices</a></li>
+  </ol>
+
+</div>
+</div>
+
+
 <p>The Android SDK includes a mobile device emulator &mdash; a virtual mobile device 
 that runs on your computer. The emulator lets you develop and test
 Android applications without using a physical device.</p>
@@ -451,7 +470,10 @@
   <td>See comments for <code>-skin</code>, above.</td></tr>
 </table>
 
-<h2>Emulator Keyboard Mapping</h2>
+
+
+<h2 id="KeyMapping">Emulator Keyboard Mapping</h2>
+
 <p>The table below summarizes the mappings between the emulator keys and and 
 the keys of your keyboard. </p>
 <p class="table-caption"><strong>Table 2.</strong> Emulator keyboard mapping</p>
diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs
index f3540e2..b7710c3 100644
--- a/docs/html/guide/guide_toc.cs
+++ b/docs/html/guide/guide_toc.cs
@@ -262,20 +262,20 @@
         </ul>
       </li>
       <li class="toggle-list">
-	        <div><a href="<?cs var:toroot ?>guide/topics/renderscript/index.html">
-	            <span class="en">RenderScript</span>
-	          </a></div>
-	        <ul>
-	          <li><a href="<?cs var:toroot ?>guide/topics/renderscript/graphics.html">
-	                <span class="en">Graphics</span>
-	              </a>
-	          </li>
-	          <li><a href="<?cs var:toroot ?>guide/topics/renderscript/compute.html">
-	                <span class="en">Compute</span>
-	              </a>
-	          </li>
-	        </ul>
-  	  </li>
+        <div><a href="<?cs var:toroot ?>guide/topics/renderscript/index.html">
+          <span class="en">RenderScript</span></a>
+        </div>
+        <ul>
+          <li><a href="<?cs var:toroot ?>guide/topics/renderscript/graphics.html">
+                <span class="en">Graphics</span>
+              </a>
+          </li>
+          <li><a href="<?cs var:toroot ?>guide/topics/renderscript/compute.html">
+                <span class="en">Compute</span>
+              </a>
+          </li>
+        </ul>
+      </li>
 
       <li class="toggle-list">
           <div><a href="<?cs var:toroot ?>guide/topics/media/index.html">
@@ -332,9 +332,15 @@
       <li><a href="<?cs var:toroot?>guide/topics/wireless/bluetooth.html">
             <span class="en">Bluetooth</span></a>
           </li>
-      <li><a href="<?cs var:toroot?>guide/topics/nfc/index.html">
-            <span class="en">Near Field Communication</span>
-          </a></li>
+      <li class="toggle-list">
+        <div><a href="<?cs var:toroot?>guide/topics/nfc/index.html">
+          <span class="en">Near Field Communication</span></a> <span class="new">updated</span>
+        </div>
+        <ul>
+          <li><a href="<?cs var:toroot ?>guide/topics/nfc/nfc.html">NFC Basics</a></li>
+          <li><a href="<?cs var:toroot ?>guide/topics/nfc/advanced-nfc.html">Advanced NFC</a></li>
+        </ul>
+      </li>
       <li class="toggle-list">
           <div><a href="<?cs var:toroot?>guide/topics/usb/index.html">
             <span class="en">USB</span></a>
@@ -715,7 +721,7 @@
       <li class="toggle-list">
         <div><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/index.html">
                <span class="en">UI Guidelines</span>
-             </a></div>
+             </a> <span class="new-child">updated</span></div>
         <ul>
           <li class="toggle-list">
             <div><a href="<?cs var:toroot ?>guide/practices/ui_guidelines/icon_design.html">
diff --git a/docs/html/guide/practices/screen-compat-mode.jd b/docs/html/guide/practices/screen-compat-mode.jd
index a792386..6a77d60 100644
--- a/docs/html/guide/practices/screen-compat-mode.jd
+++ b/docs/html/guide/practices/screen-compat-mode.jd
@@ -48,7 +48,7 @@
 to resize for larger screens such as tablets. Since Android 1.6, Android has supported a
 variety of screen sizes and does most of the work to resize application layouts so that they
 properly fit each screen. However, if your application does not successfully follow the guide to
-<a href="{@docRoot}guide/topics/practices/screens_support.html">Supporting Multiple Screens</a>,
+<a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple Screens</a>,
 then it might encounter some rendering issues on larger screens. For applications with this
 problem, screen compatibility mode can make the application a little more usable on larger
 screens.</p>
@@ -83,7 +83,7 @@
   <p>This was introduced with Android 3.2 to further
 assist applications on the latest tablet devices when the applications have not yet
 implemented techniques for <a
-href="{@docRoot}guide/topics/practices/screens_support.html">Supporting Multiple
+href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
 Screens</a>.</p>
   <p>In general, large screen devices running Android 3.2 or higher allow users to enable
 screen compatibility mode when the application does not <strong>explicitly declare that it supports
@@ -211,7 +211,7 @@
 which you should want your application to run&mdash;it causes pixelation and blurring in your UI,
 due to zooming. The proper way to make your application work well on large screens is to follow the
 guide to <a
-href="{@docRoot}guide/topics/practices/screens_support.html">Supporting Multiple Screens</a> and
+href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple Screens</a> and
 provide alternative layouts for different screen sizes.</p>
 
 <p>By default, when you've set either <a
diff --git a/docs/html/guide/topics/fundamentals/fragments.jd b/docs/html/guide/topics/fundamentals/fragments.jd
index 8f61945..d34a798 100644
--- a/docs/html/guide/topics/fundamentals/fragments.jd
+++ b/docs/html/guide/topics/fundamentals/fragments.jd
@@ -117,7 +117,7 @@
 two
 fragments in <em>Activity A</em>, when running on an extra large screen (a tablet, for example).
 However, on a normal-sized screen (a phone, for example),
-there's not be enough room for both fragments, so <em>Activity A</em> includes only the fragment for
+there would not be enough room for both fragments, so <em>Activity A</em> includes only the fragment for
 the list of articles, and when the user selects an article, it starts <em>Activity B</em>, which
 includes the fragment to read the article. Thus, the application supports both design patterns
 suggested in figure 1.</p>
diff --git a/docs/html/guide/topics/manifest/activity-element.jd b/docs/html/guide/topics/manifest/activity-element.jd
index 5a9313e..02a8a8e 100644
--- a/docs/html/guide/topics/manifest/activity-element.jd
+++ b/docs/html/guide/topics/manifest/activity-element.jd
@@ -10,8 +10,8 @@
           android:<a href="#clear">clearTaskOnLaunch</a>=["true" | "false"]
           android:<a href="#config">configChanges</a>=["mcc", "mnc", "locale",
                                  "touchscreen", "keyboard", "keyboardHidden",
-                                 "navigation", "orientation", "screenLayout",
-                                 "fontScale", "uiMode"]
+                                 "navigation", "screenLayout", "fontScale", "uiMode",
+                                 "orientation", "screenSize", "smallestScreenSize"]
           android:<a href="#enabled">enabled</a>=["true" | "false"]
           android:<a href="#exclude">excludeFromRecents</a>=["true" | "false"]
           android:<a href="#exported">exported</a>=["true" | "false"]
@@ -205,10 +205,6 @@
    <td>"{@code navigation}"</td>
    <td>The navigation type (trackball/dpad) has changed.  (This should never normally happen.)</td>
 </tr><tr>
-   <td>"{@code orientation}"</td>
-   <td>The screen orientation has changed &mdash; the user has rotated
-       the device.</td>
- </tr><tr>
    <td>"{@code screenLayout}"</td>
    <td>The screen layout has changed &mdash; this might be caused by a
              different display being activated.</td>
@@ -221,7 +217,34 @@
    <td>The user interface mode has changed &mdash; this can be caused when the user places the
 device into a desk/car dock or when the the night mode changes. See {@link
 android.app.UiModeManager}. <em>Introduced in API Level 8</em>.</td>
-  </tr>
+  </tr><tr>
+   <td>"{@code orientation}"</td>
+   <td>The screen orientation has changed &mdash; the user has rotated the device. 
+       <p class="note"><strong>Note:</strong> If your application targets API level 13 or higher (as
+declared by the <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code
+minSdkVersion}</a> and <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code
+targetSdkVersion}</a> attributes), then you should also declare the {@code "screenSize"}
+configuration, because it also changes when a device switches between portrait and landscape
+orientations.</p></td>
+ </tr><tr>
+   <td>"{@code screenSize}"</td>
+   <td>The current available screen size has changed. This represents a change in the currently
+available size, relative to the current aspect ratio, so will change when the user switches between
+landscape and portrait. However, if your application targets API level 12 or lower, then your
+activity always handles this configuration change itself (this configuration change does not restart
+your activity, even when running on an Android 3.2 or higher device).
+  <p><em>Added in API level 13.</em></p></td>
+ </tr><tr>
+   <td>"{@code smallestScreenSize}"</td>
+   <td>The physical screen size has changed. This represents a change in size regardless of
+orientation, so will only change when the actual physical screen size has changed such as switching
+to an external display. A change to this configuration corresponds to a change in the <a
+href="{@docRoot}guide/topics/resources/providing-resources.html#SmallestScreenWidthQualifier">
+smallestWidth configuration</a>. However, if your application targets API level 12 or lower, then
+your activity always handles this configuration change itself (this configuration change does not
+restart your activity, even when running on an Android 3.2 or higher device).
+  <p><em>Added in API level 13.</em></p></td>
+ </tr>
 </table>
 
 <p>
diff --git a/docs/html/guide/topics/nfc/advanced-nfc.jd b/docs/html/guide/topics/nfc/advanced-nfc.jd
new file mode 100644
index 0000000..2b414aa
--- /dev/null
+++ b/docs/html/guide/topics/nfc/advanced-nfc.jd
@@ -0,0 +1,303 @@
+page.title=Advanced NFC
+@jd:body
+
+<div id="qv-wrapper">
+<div id="qv">
+  <h2>In this document</h2>
+  <ol>
+    <li><a href="#tag-tech">Working with Supported Tag Technologies</a>
+      <ol>
+        <li><a href="#tech-intent">Working with tag technologies and the ACTION_TECH_DISCOVERED
+        intent</a></li>
+        <li><a href="#read-write">Reading and writing to tags</a></li>
+      </ol></li>
+    <li><a href="#foreground-dispatch">Using the Foreground Dispatch System</a></li>
+  </ol>
+</div>
+</div>
+
+<p>This document describes advanced NFC topics, such as working with various tag technologies,
+writing to NFC tags, and foreground dispatching, which allows an application in the foreground to
+handle intents even when other applications filter for the same ones.</p>
+
+<h2 id="tag-tech">Working with Supported Tag Technologies</h2>
+<p>When working with NFC tags and Android-powered devices, the main format you use to read
+and write data on tags is NDEF. When a device scans a tag with NDEF data, Android provides support
+in parsing the message and delivering it in an {@link android.nfc.NdefMessage} when
+possible. There are cases, however, when you scan a tag that does not contain
+NDEF data or when the NDEF data could not be mapped to a MIME type or URI.
+In these cases, you need to open communication directly with the tag and read and write to it with
+your own protocol (in raw bytes). Android provides generic support for these use cases with the
+{@link android.nfc.tech} package, which is described in <a href="#tech-table">Table 1</a>. You can
+use the {@link android.nfc.Tag#getTechList getTechList()} method to determine the technologies
+supported by the tag and create the corresponding {@link android.nfc.tech.TagTechnology}
+object with one of classes provided by {@link android.nfc.tech} </p>
+
+
+<table>
+
+<p class="table-caption" id="table1">
+<strong>Table 1.</strong> Supported tag technologies</p>
+<table id="tech-table">
+
+    <tr>
+      <th>Class</th>
+
+      <th>Description</th>
+    </tr>
+
+    <tr>
+      <td>{@link android.nfc.tech.TagTechnology}</td>
+
+      <td>The interface that all tag technology classes must implement.</td>
+    </tr>
+
+    <tr>
+      <td>{@link android.nfc.tech.NfcA}</td>
+
+      <td>Provides access to NFC-A (ISO 14443-3A) properties and I/O operations.</td>
+    </tr>
+
+    <tr>
+      <td>{@link android.nfc.tech.NfcB}</td>
+
+      <td>Provides access to NFC-B (ISO 14443-3B) properties and I/O operations.</td>
+    </tr>
+
+    <tr>
+      <td>{@link android.nfc.tech.NfcF}</td>
+
+      <td>Provides access to NFC-F (JIS 6319-4) properties and I/O operations.</td>
+    </tr>
+
+    <tr>
+      <td>{@link android.nfc.tech.NfcV}</td>
+
+      <td>Provides access to NFC-V (ISO 15693) properties and I/O operations.</td>
+    </tr>
+
+    <tr>
+      <td>{@link android.nfc.tech.IsoDep}</td>
+
+      <td>Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations.</td>
+    </tr>
+
+    <tr>
+      <td>{@link android.nfc.tech.Ndef}</td>
+
+      <td>Provides access to NDEF data and operations on NFC tags that have been formatted as
+      NDEF.</td>
+    </tr>
+
+    <tr>
+      <td>{@link android.nfc.tech.NdefFormatable}</td>
+
+      <td>Provides a format operations for tags that may be NDEF formattable.</td>
+    </tr>
+  </table>
+<p>The following tag technlogies are not required to be supported by Android-powered devices.</p>
+  <p class="table-caption" id="table2">
+<strong>Table 2.</strong> Optional supported tag technologies</p>
+  <table>
+    <tr>
+      <th>Class</th>
+
+      <th>Description</th>
+    </tr>
+    <tr>
+      <td>{@link android.nfc.tech.MifareClassic}</td>
+
+      <td>Provides access to MIFARE Classic properties and I/O operations, if this Android device
+      supports MIFARE.</td>
+    </tr>
+
+    <tr>
+      <td>{@link android.nfc.tech.MifareUltralight}</td>
+
+      <td>Provides access to MIFARE Ultralight properties and I/O operations, if this Android
+      device supports MIFARE.</td>
+    </tr>
+  </table>
+
+<h3 id="tech-intent">Working with tag technologies and the ACTION_TECH_DISCOVERED intent</h3>
+<p>When a device scans a tag that has NDEF data on it, but could not be mapped to a MIME or URI,
+the tag dispatch system tries to start an activity with the {@link
+android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}
+intent. The {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} is also used when a tag
+with non-NDEF data is scanned. Having this fallback allows you to work with the data on the tag
+directly if the tag dispatch system could not parse it for you. The basic steps when working with
+tag technologies are as follows:</p>
+
+<ol>
+  <li>Filter for an {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent specifying the
+tag technologies that you want to handle. See <a
+href="{@docRoot}guide/topics/nfc/nfc.html#tech-disc">Filtering for NFC
+intents</a> for more information. In general, the tag dispatch system tries to start a {@link
+android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent when an NDEF message
+cannot be mapped to a MIME type or URI, or if the tag scanned did not contain NDEF data. For
+more information on how this is determined, see <a
+href="{@docRoot}guide/topics/nfc/nfc.html#tag-dispatch">The Tag Dispatch System</a>.</li>
+  <li>When your application receives the intent, obtain the {@link android.nfc.Tag} object from
+the intent:
+<pre>Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);</pre></li>
+<li>Obtain an instance of a {@link android.nfc.tech.TagTechnology}, by calling one of the
+<code>get</code> factory methods of the classes in the {@link android.nfc.tech} package. You can
+enumerate the supported technologies of the tag by calling {@link android.nfc.Tag#getTechList
+getTechList()} before calling a <code>get</code> factory method. For example, to obtain an instance
+of {@link android.nfc.tech.MifareUltralight} from a {@link android.nfc.Tag}, do the following:
+
+<pre>
+MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
+</pre>
+</li>
+</ol>
+
+
+
+<h3 id="read-write">Reading and writing to tags</h3>
+
+<p>Reading and writing to an NFC tag involves obtaining the tag from the intent and
+opening communication with the tag. You must define your own protocol stack to read and write data
+to the tag. Keep in mind, however, that you can still read and write NDEF data when working
+directly with a tag. It is up to you how you want to structure things. The
+following example shows how to work with a MIFARE Ultralight tag.</p>
+
+<pre>
+package com.example.android.nfc;
+
+import android.nfc.Tag;
+import android.nfc.tech.MifareUltralight;
+import android.util.Log;
+import java.io.IOException;
+import java.nio.charset.Charset;
+
+public class MifareUltralightTagTester {
+
+    private static final String TAG = MifareUltralightTagTester.class.getSimpleName();
+
+    public void writeTag(Tag tag, String tagText) {
+        MifareUltralight ultralight = MifareUltralight.get(tag);
+        try {
+            ultralight.connect();
+            ultralight.writePage(4, "abcd".getBytes(Charset.forName("US-ASCII")));
+            ultralight.writePage(5, "efgh".getBytes(Charset.forName("US-ASCII")));
+            ultralight.writePage(6, "ijkl".getBytes(Charset.forName("US-ASCII")));
+            ultralight.writePage(7, "mnop".getBytes(Charset.forName("US-ASCII")));
+        } catch (IOException e) {
+            Log.e(TAG, "IOException while closing MifareUltralight...", e);
+        } finally {
+            try {
+                ultralight.close();
+            } catch (IOException e) {
+                Log.e(TAG, "IOException while closing MifareUltralight...", e);
+            }
+        }
+    }
+
+    public String readTag(Tag tag) {
+        MifareUltralight mifare = MifareUltralight.get(tag);
+        try {
+            mifare.connect();
+            byte[] payload = mifare.readPages(4);
+            return new String(payload, Charset.forName("US-ASCII"));
+        } catch (IOException e) {
+            Log.e(TAG, "IOException while writing MifareUltralight
+            message...", e);
+        } finally {
+            if (mifare != null) {
+               try {
+                   mifare.close();
+               }
+               catch (IOException e) {
+                   Log.e(TAG, "Error closing tag...", e);
+               }
+            }
+        }
+        return null;
+    }
+}
+</pre>
+
+</pre>
+
+  <h2 id="foreground-dispatch">Using the Foreground Dispatch System</h2>
+
+  <p>The foreground dispatch system allows an activity to intercept an intent and claim
+priority over other activities that handle the same intent. Using this system involves
+  constructing a few data structures for the Android system to be able to send the appropriate
+  intents to your application. To enable the foreground dispatch system:</p>
+
+  <ol>
+    <li>Add the following code in the <code>onCreate()</code> method of your activity:
+
+      <ol type="a">
+        <li>Create a {@link android.app.PendingIntent} object so the Android system can populate it
+        with the details of the tag when it is scanned.
+          <pre>
+PendingIntent pendingIntent = PendingIntent.getActivity(
+    this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
+</pre>
+        </li>
+
+        <li>Declare intent filters to handle the intents that you want to intercept. The foreground
+        dispatch system checks the specified intent filters with the intent that is received when
+        the device scans a tag. If it matches, then your application handles the intent. If it does
+        not match, the foreground dispatch system falls back to the intent dispatch system.
+        Specifying a <code>null</code> array of intent filters and technology filters, specifies
+        that you want to filter for all tags that fallback to the <code>TAG_DISCOVERED</code>
+        intent. The code snippet below handles all MIME types for <code>NDEF_DISCOVERED</code>. You
+        should only handle the ones that you need.
+<pre>
+IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
+    try {
+        ndef.addDataType("*/*");    /* Handles all MIME based dispatches.
+                                       You should specify only the ones that you need. */
+    }
+    catch (MalformedMimeTypeException e) {
+        throw new RuntimeException("fail", e);
+    }
+   intentFiltersArray = new IntentFilter[] {ndef, };
+</pre>
+        </li>
+
+        <li>Set up an array of tag technologies that your application wants to handle. Call the
+        <code>Object.class.getName()</code> method to obtain the class of the technology that you
+        want to support.
+<pre>
+techListsArray = new String[][] { new String[] { NfcF.class.getName() } };
+</pre>
+        </li>
+      </ol>
+    </li>
+
+    <li>Override the following activity lifecycle callbacks and add logic to enable and disable the
+    foreground dispatch when the activity loses ({@link android.app.Activity#onPause onPause()})
+    and regains ({@link android.app.Activity#onResume onResume()}) focus. {@link
+    android.nfc.NfcAdapter#enableForegroundDispatch enableForegroundDispatch()} must be called from
+the main thread and only  when the activity is in the foreground (calling in {@link
+android.app.Activity#onResume onResume()} guarantees this). You also need to implement the {@link
+    android.app.Activity#onNewIntent onNewIntent} callback to process the data from the scanned NFC
+    tag.</li>
+
+<pre>
+public void onPause() {
+    super.onPause();
+    mAdapter.disableForegroundDispatch(this);
+}
+
+public void onResume() {
+    super.onResume();
+    mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
+}
+
+public void onNewIntent(Intent intent) {
+    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
+    //do something with tagFromIntent
+}
+</pre>
+    </li>
+  </ol>
+
+  <p>See the <a href=
+"{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/nfc/ForegroundDispatch.html">
+ForegroundDispatch</a> sample from API Demos for the complete sample.</p>
\ No newline at end of file
diff --git a/docs/html/guide/topics/nfc/index.jd b/docs/html/guide/topics/nfc/index.jd
index b486d3b..b86d72d 100644
--- a/docs/html/guide/topics/nfc/index.jd
+++ b/docs/html/guide/topics/nfc/index.jd
@@ -1,601 +1,33 @@
 page.title=Near Field Communication
 @jd:body
 
-<div id="qv-wrapper">
-<div id="qv">
-  <h2>In this document</h2>
-  <ol>
-    <li><a href="#api">API Overview</a></li>
-    <li><a href="#manifest">Declaring Android Manifest elements</a></li>
-    <li><a href="#dispatch">The Tag Dispatch System</a>
-      <ol>
-        <li><a href="#intent-dispatch">Using the intent dispatch system</a></li>
-        <li><a href="#foreground-dispatch">Using the foreground dispatch system</a></li>
-      </ol></li>
-    <li><a href="#ndef">Working with Data on NFC Tags</a></li>
-    <li><a href="#read">Reading an NFC Tag</a></li>
-    <li><a href="#write">Writing to an NFC Tag</a></li>
-    <li><a href="#p2p">Peer-to-Peer Data Exchange</a></li>
-  </ol>
-</div>
-</div>
-
   <p>Near Field Communication (NFC) is a set of short-range wireless technologies, typically
-  requiring a distance of 4cm or less. NFC operates at 13.56mhz, and at rates ranging from 106
-  kbit/s to 848 kbit/s. NFC communication always involves an initiator and a target. The initiator
-  actively generates an RF field that can power a passive target. This enables NFC targets to take
-  very simple form factors such as tags, stickers or cards that do not require power. NFC
-  peer-to-peer communication is also possible, where both devices are powered.</p>
+  requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small
+  payloads of data between an NFC tag and an Android-powered device, or between two Android-powered
+  devices.
 
-  <p>Compared to other wireless technologies such as Bluetooth or WiFi, NFC provides much lower
-  bandwidth and range, but enables low-cost, un-powered targets and does not require discovery or
-  pairing. Interactions can be initiated with just a tap.</p>
-
-  <p>An Android device with NFC hardware will typically act as an initiator when the screen is on.
-  This mode is also known as NFC reader/writer. It will actively look for NFC tags and start
-  activities to handle them. Android 2.3.3 also has some limited P2P support.</p>
-
-  <p>Tags can range in complexity, simple tags just offer read/write semantics, sometimes with
+  <p>Tags can range in complexity. Simple tags offer just read and write semantics, sometimes with
   one-time-programmable areas to make the card read-only. More complex tags offer math operations,
   and have cryptographic hardware to authenticate access to a sector. The most sophisticated tags
-  contain operating environments, allowing complex interactions with code executing on the tag.</p>
+  contain operating environments, allowing complex interactions with code executing on the tag.
+  The data stored in the tag can also be written in a variety of formats, but many of the Android
+  framework APIs are based around a <a href="http://www.nfc-forum.org/">NFC Forum</a> standard
+  called NDEF (NFC Data Exchange Format).</p>
 
-  <h2 id="api">API Overview</h2>
+  <dl>
+    <dt><strong><a href="{@docRoot}guide/topics/nfc/nfc.html">NFC Basics</a></strong></dt>
+    <dd>This document describes how Android handles discovered NFC tags and how it notifies
+applications of data that is relevant to the application. It also goes over how to work with the
+NDEF data in your applications and gives an overview of the framework APIs that support the basic
+NFC feature set of Android.</dd>
 
-  <p>The {@link android.nfc} package contains the high-level classes to interact with the local
-  device's NFC adapter, to represent discovered tags, and to use the NDEF data format.</p>
-
-  <table>
-    <tr>
-      <th>Class</th>
-
-      <th>Description</th>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.NfcManager}</td>
-
-      <td>A high level manager class that enumerates the NFC adapters on this Android device. Since
-      most Android devices only have one NFC adapter, you can just use the static helper {@link
-      android.nfc.NfcAdapter#getDefaultAdapter(Context)} for most situations.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.NfcAdapter}</td>
-
-      <td>Represents the local NFC adapter. Defines the intent's used to request tag dispatch to
-      your activity, and provides methods to register for foreground tag dispatch and foreground
-      NDEF push. Foreground NDEF push is the only peer-to-peer support that is currently provided
-      in Android.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.NdefMessage} and {@link android.nfc.NdefRecord}</td>
-
-      <td>NDEF is an NFC Forum defined data structure, designed to efficiently store data on NFC
-      tags, such as text, URL's, and other MIME types. A {@link android.nfc.NdefMessage} acts as a
-      container for the data that you want to transmit or read. One {@link android.nfc.NdefMessage}
-      object contains zero or more {@link android.nfc.NdefRecord}s. Each NDEF record has a type
-      such as text, URL, smart poster, or any MIME data. The type of the first NDEF record in the
-      NDEF message is used to dispatch a tag to an activity on Android.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.Tag}</td>
-
-      <td>Represents a passive NFC target. These can come in many form factors such as a tag, card,
-      key fob, or even a phone doing card emulation. When a tag is discovered, a {@link
-      android.nfc.Tag} object is created and wrapped inside an Intent. The NFC dispatch system
-      sends the intent to a compatible activity using <code>startActivity()</code>. You can use the
-      {@link android.nfc.Tag#getTechList getTechList()} method to determine the technologies
-      supported by this tag and create the corresponding {@link android.nfc.tech.TagTechnology}
-      object with one of classes provided by {@link android.nfc.tech}.</td>
-    </tr>
-  </table>
-
-  <p>The {@link android.nfc.tech} package contains classes to query properties and perform I/O
-  operations on a tag. The classes are divided to represent different NFC technologies that can be
-  available on a Tag:</p>
-
-  <table>
-    <tr>
-      <th>Class</th>
-
-      <th>Description</th>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.tech.TagTechnology}</td>
-
-      <td>The interface that all tag technology classes must implement.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.tech.NfcA}</td>
-
-      <td>Provides access to NFC-A (ISO 14443-3A) properties and I/O operations.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.tech.NfcB}</td>
-
-      <td>Provides access to NFC-B (ISO 14443-3B) properties and I/O operations.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.tech.NfcF}</td>
-
-      <td>Provides access to NFC-F (JIS 6319-4) properties and I/O operations.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.tech.NfcV}</td>
-
-      <td>Provides access to NFC-V (ISO 15693) properties and I/O operations.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.tech.IsoDep}</td>
-
-      <td>Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.tech.Ndef}</td>
-
-      <td>Provides access to NDEF data and operations on NFC tags that have been formatted as
-      NDEF.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.tech.NdefFormatable}</td>
-
-      <td>Provides a format operations for tags that may be NDEF formattable.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.tech.MifareClassic}</td>
-
-      <td>Provides access to MIFARE Classic properties and I/O operations, if this Android device
-      supports MIFARE.</td>
-    </tr>
-
-    <tr>
-      <td>{@link android.nfc.tech.MifareUltralight}</td>
-
-      <td>Provides access to MIFARE Ultralight properties and I/O operations, if this Android
-      device supports MIFARE.</td>
-    </tr>
-  </table>
-
-  <h2 id="manifest">Declaring Android Manifest elements</h2>
-
-  <p>Before you can access a device's NFC hardware and properly handle NFC intents, declare these
-  items in your <code>AndroidManifest.xml</code> file:</p>
-
-  <ol>
-    <li>The NFC <code>&lt;uses-permission&gt;</code> element to access the NFC hardware:
-      <pre>
-&lt;uses-permission android:name="android.permission.NFC" /&gt;
-</pre>
-    </li>
-
-    <li>The minimum SDK version that your application can support. API level 9 only supports
-    limited tag dispatch via {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}, and only gives
-    access to NDEF messages via the {@link android.nfc.NfcAdapter#EXTRA_NDEF_MESSAGES} extra. No
-    other tag properties or I/O operations are accessible. You probably want to use API level 10
-    which includes comprehensive reader/writer support.
-      <pre class="pretty-print">
-&lt;uses-sdk android:minSdkVersion="10"/&gt;
-</pre>
-    </li>
-
-    <li>The uses-feature element so that your application can show up in the Android Market for
-    devices that have NFC hardware:
-      <pre>
-&lt;uses-feature android:name="android.hardware.nfc" android:required="true" /&gt;
-</pre>
-    </li>
-
-    <li>The NFC intent filter to tell the Android system your Activity can handle NFC data. Specify
-    one or more of these three intent filters:
-      <pre>
-&lt;intent-filter&gt;
-  &lt;action android:name="android.nfc.action.NDEF_DISCOVERED"/&gt;
-  &lt;data android:mimeType="<em>mime/type</em>" /&gt;
-&lt;/intent-filter&gt;
-
-&lt;intent-filter&gt;
-  &lt;action android:name="android.nfc.action.TECH_DISCOVERED"/&gt;
-  &lt;meta-data android:name="android.nfc.action.TECH_DISCOVERED"
-                android:resource="@xml/<em>nfc_tech_filter</em>.xml" /&gt;
-&lt;/intent-filter&gt;
-
-&lt;intent-filter&gt;
-  &lt;action android:name="android.nfc.action.TAG_DISCOVERED"/&gt;
-&lt;/intent-filter&gt;
-</pre>
-
-      <p>The three intent filters are prioritized and behave in specific ways. Declare only the
-      ones that your Activity needs to handle. For more information on how to handle these filters,
-      see the section about <a href="#dispatch">The Tag Dispatch System</a>.</p>
-    </li>
-  </ol>
-
-  <p>View the <a href=
-  "../../../resources/samples/NFCDemo/AndroidManifest.html">AndroidManifest.xml</a> from the
-  NFCDemo sample to see a complete example.</p>
-
-  <h2 id="dispatch">The Tag Dispatch System</h2>
-
-  <p>When an Android device scans an NFC tag, the desired behavior is to have the most appropriate
-  Activity handle the intent without asking the user what application to use. Because devices scan
-  NFC tags at a very short range, it is likely that making users manually select an Activity forces
-  them to move the device away from the tag and break the connection. You should develop your
-  Activity to only handle the NFC tags that your Activity cares about to prevent the Activity
-  Chooser from appearing. Android provides two systems to help you correctly identify an NFC tag
-  that your Activity should handle: the Intent dispatch system and the foreground Activity dispatch
-  system.</p>
-
-  <p>The intent dispatch system checks the intent filters of all the Activities along with the
-  types of data that the Activities support to find the best Activity that can handle the NFC tag.
-  If multiple Activities specify the same intent filter and data to handle, then the Activity
-  Chooser is presented to the user as a last resort.</p>
-
-  <p>The foreground dispatch system allows an Activity application to override the intent dispatch
-  system and have priority when an NFC tag is scanned. The Activity handling the request must be
-  running in the foreground of the device. When an NFC tag is scanned and matches the intent and
-  data type that the foreground dispatch Activity defines, the intent is immediately sent to the
-  Activity even if another Activity can handle the intent. If the Activity cannot handle the
-  intent, the foreground dispatch system falls back to the intent dispatch system.</p>
-
-  <h3 id="intent-dispatch">Using the intent dispatch system</h3>
-
-  <p>The intent dispatch system specifies three intents that each have a priority. The intents that
-  start when a device scans a tag depend on the type of tag scanned. In general, the intents are
-  started in the following manner:</p>
-
-  <ul>
-    <li>
-      <code>android.nfc.action.NDEF_DISCOVERED</code>: This intent starts when a tag that contains
-      an NDEF payload is scanned. This is the highest priority intent. The Android system does not
-      let you specify this intent generically to handle all data types. You must specify
-      <code>&lt;data&gt;</code> elements in the <code>AndroidManifest.xml</code> along with this
-      intent to correctly handle NFC tags that start this intent. For example, to handle a
-      <code>NDEF_DISCOVERED</code> intent that contains plain text, specify the following filter in
-      your <code>AndroidManifest.xml</code> file:
-      <pre>
-&lt;intent-filter&gt;
-    &lt;action android:name="android.nfc.action.NDEF_DISCOVERED"/&gt;
-    &lt;data android:mimeType="text/plain" /&gt;
-&lt;/intent-filter&gt;
-</pre>
-
-      <p>If the <code>NDEF_DISCOVERED</code> intent is started, the <code>TECH_DISCOVERED</code>
-      and <code>TAG_DISCOVERED</code> intents are not started. This intent does not start if an
-      unknown tag is scanned or if the tag does not contain an NDEF payload.</p>
-    </li>
-
-    <li><code>android.nfc.action.TECH_DISCOVERED</code>: If the <code>NDEF_DISCOVERED</code> intent
-    does not start or is not filtered by any Activity on the device, this intent starts if the tag
-    is known. The <code>TECH_DISCOVERED</code> intent requires that you specify the technologies
-    that you want to support in an XML resource file. For more information, see the section about
-    <a href="#technology-resources">Specifying tag technologies to handle</a>.</li>
-
-    <li><code>android.nfc.action.TAG_DISCOVERED</code>: This intent starts if no Activities handle
-    the <code>NDEF_DISCOVERED</code> and <code>TECH_DISCOVERED</code> intents or if the tag that is
-    scanned is unknown.</li>
-  </ul>
-
-  <h4 id="tech">Specifying tag technologies to handle</h4>
-
-  <p>If your Activity declares the <code>android.nfc.action.TECH_DISCOVERED</code> intent in your
-  <code>AndroidManifest.xml</code> file, you must create an XML resource file that specifies the
-  technologies that your Activity supports within a <code>tech-list</code> set. Your Activity is
-  considered a match if a <code>tech-list</code> set is a subset of the technologies that are
-  supported by the tag, which you can obtain by calling {@link android.nfc.Tag#getTechList
-  getTechList()}.</p>
-
-  <p>For example, if the tag that is scanned supports MifareClassic, NdefFormatable, and NfcA, your
-  <code>tech-list</code> set must specify all three, two, or one of the technologies (and nothing
-  else) in order for your Activity to be matched.</p>
-
-  <p>The following sample defines all of the technologies. You can remove the ones that you do not
-  need. Save this file (you can name it anything you wish) in the
-  <code>&lt;project-root&gt;/res/xml</code> folder.</p>
-  <pre>
-&lt;resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"&gt;
-    &lt;tech-list&gt;
-        &lt;tech&gt;android.nfc.tech.IsoDep&lt;/tech&gt;
-        &lt;tech&gt;android.nfc.tech.NfcA&lt;/tech&gt;        
-        &lt;tech&gt;android.nfc.tech.NfcB&lt;/tech&gt;
-        &lt;tech&gt;android.nfc.tech.NfcF&lt;/tech&gt;
-        &lt;tech&gt;android.nfc.tech.NfcV&lt;/tech&gt;
-        &lt;tech&gt;android.nfc.tech.Ndef&lt;/tech&gt;
-        &lt;tech&gt;android.nfc.tech.NdefFormatable&lt;/tech&gt;
-        &lt;tech&gt;android.nfc.tech.MifareClassic&lt;/tech&gt;
-        &lt;tech&gt;android.nfc.tech.MifareUltralight&lt;/tech&gt;
-    &lt;/tech-list&gt;
-&lt;/resources&gt;
-</pre>
-
-  <p>You can also specify multiple <code>tech-list</code> sets. Each of the <code>tech-list</code>
-  sets is considered independently, and your Activity is considered a match if any single
-  <code>tech-list</code> set is a subset of the technologies that are returned by {@link
-  android.nfc.Tag#getTechList getTechList()}. This provides <code>AND</code> and <code>OR</code>
-  semantics for matching technologies. The following example matches tags that can support the
-  NfcA and Ndef technologies or can support the NfcB and Ndef technologies:</p>
-  <pre>
-&lt;resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"&gt;
-    &lt;tech-list&gt;
-        &lt;tech&gt;android.nfc.tech.NfcA&lt;/tech&gt;        
-        &lt;tech&gt;android.nfc.tech.Ndef&lt;/tech&gt;
-    &lt;/tech-list&gt;
-&lt;/resources&gt;
-
-&lt;resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"&gt;
-    &lt;tech-list&gt;
-        &lt;tech&gt;android.nfc.tech.NfcB&lt;/tech&gt;        
-        &lt;tech&gt;android.nfc.tech.Ndef&lt;/tech&gt;
-    &lt;/tech-list&gt;
-&lt;/resources&gt;
-</pre>
-
-  <p>In your <code>AndroidManifest.xml</code> file, specify the resource file that you just created
-  in the <code>&lt;meta-data&gt;</code> element inside the <code>&lt;activity&gt;</code>
-  element like in the following example:</p>
-  <pre>
-&lt;activity&gt;
-...
-&lt;intent-filter&gt;
-    &lt;action android:name="android.nfc.action.TECH_DISCOVERED"/&gt;
-&lt;/intent-filter&gt;
-
-&lt;meta-data android:name="android.nfc.action.TECH_DISCOVERED"
-    android:resource="@xml/nfc_tech_filter" /&gt;
-...
-&lt;/activity&gt;
-</pre>
-
-  <h3 id="foreground-dispatch">Using the foreground dispatch system</h3>
-
-  <p>The foreground dispatch system allows an Activity to intercept an intent and claim priority
-  over other Activities that handle the same intent. The system is easy to use and involves
-  constructing a few data structures for the Android system to be able to send the appropriate
-  intents to your application. To enable the foreground dispatch system:</p>
-
-  <ol>
-    <li>Add the following code in the onCreate() method of your Activity:
-
-      <ol type="a">
-        <li>Create a {@link android.app.PendingIntent} object so the Android system can populate it
-        with the details of the tag when it is scanned
-          <pre>
-PendingIntent pendingIntent = PendingIntent.getActivity(
-    this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
-</pre>
-        </li>
-
-        <li>Declare intent filters to handle the intents that you want to intercept. The foreground
-        dispatch system checks the specified intent filters with the intent that is received when
-        the device scans a tag. If they match, then your application handles the intent. If it does
-        not match, the foreground dispatch system falls back to the intent dispatch system.
-        Specifying a <code>null</code> array of intent filters and for the technology filters, you
-        receive a <code>TAG_DISCOVERED</code> intent for all tags discovered. Note that the snippet
-        below handles all MIME types. You should only handle the ones that you need.
-          <pre>
-    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
-        try {
-            ndef.addDataType("*/*");    /* Handles all MIME based dispatches. 
-                                           You should specify only the ones that you need. */
-        }
-        catch (MalformedMimeTypeException e) {
-            throw new RuntimeException("fail", e);
-        }
-        intentFiltersArray = new IntentFilter[] {
-                ndef,
-        };
-</pre>
-        </li>
-
-        <li>Set up an array of tag technologies that your application wants to handle. Call the
-        <code>Object.class.getName()</code> method to obtain the class of the technology that you
-        want to support.
-          <pre>
-
-  techListsArray = new String[][] { new String[] { NfcF.class.getName() } };
-  
-</pre>
-        </li>
-      </ol>
-    </li>
-
-    <li>Override the following Activity lifecycle callbacks and add logic to enable and disable the
-    foreground dispatch when the Activity loses ({@link android.app.Activity#onPause onPause()})
-    and regains ({@link android.app.Activity#onResume onResume()}) focus. {@link
-    android.nfc.NfcAdapter#enableForegroundDispatch} must be called from the main thread and only
-    when the activity is in the foreground (calling in {@link android.app.Activity#onResume
-    onResume()} guarantees this). You also need to implement the {@link
-    android.app.Activity#onNewIntent onNewIntent} callback to process the data from the scanned NFC
-    tag.
-      <pre>
-public void onPause() {
-    super.onPause();
-    mAdapter.disableForegroundDispatch(this);
-}   
-
-public void onResume() {
-    super.onResume();
-    mAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
-}
-
-public void onNewIntent(Intent intent) {
-    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
-    //do something with tagFromIntent
-}
-</pre>
-    </li>
-  </ol>
-
-  <p>See the <a href=
-  "{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/nfc/ForegroundDispatch.html">ForegroundDispatch</a>
-  sample from API Demos for the complete sample.</p>
-
-  <h2 id="ndef">Working with Data on NFC Tags</h2>
-
-  <p>Data on NFC tags are encoded in raw bytes, so you must convert the bytes to something human
-  readable if you are presenting the data to the user. When writing to NFC tags, you must write
-  them in bytes as well. Android provides APIs to help write messages that conform to the NDEF
-  standard, which was developed by the <a href="http://www.nfc-forum.org/specs/">NFC Forum</a> to
-  standardized data on tags. Using this standard ensures that your data will be supported by all
-  Android NFC devices if you are writing to tags. However, many tag technologies use their own
-  standard for storing data and are supported by Android as well, but you have to implement your
-  own protocol stack to read and write to these tags. You can find a full list of the supported
-  technologies in {@link android.nfc.tech} and an overview of the technologies in the {@link
-  android.nfc.tech.TagTechnology} interface. This section is a brief overview of how to work with
-  NDEF messages in the context of the Android system. It is not meant to be a complete discussion
-  of the NDEF specification, but highlights the main things that you need to be aware of when
-  working with NDEF messages in Android.</p>
-
-  <p>To facilitate working with NDEF messages, Android provides the {@link android.nfc.NdefRecord}
-  and {@link android.nfc.NdefMessage} to encapsulate the raw bytes that represent NDEF messages. An
-  {@link android.nfc.NdefMessage} is the container for zero or more {@link
-  android.nfc.NdefRecord}s. Each {@link android.nfc.NdefRecord} has its own unique type name
-  format, record type, and ID to distinguish them from other records within the same {@link
-  android.nfc.NdefMessage}. You can store different types of records of varying length in a single
-  {@link android.nfc.NdefMessage}. The size constraint of the NFC tag determines how big your
-  {@link android.nfc.NdefMessage} can be.</p>
-
-  <p>Tags that support the {@link android.nfc.tech.Ndef} and {@link
-  android.nfc.tech.NdefFormatable} technologies return and accept {@link android.nfc.NdefMessage}
-  objects as parameters for read and write operations. You need to create your own logic to read
-  and write bytes for other tag technologies in {@link android.nfc.tech}.</p>
-
-  <p>You can download technical specifications for different types of NDEF message standards, such
-  as plain text and Smart Posters, at the <a href="http://www.nfc-forum.org/specs/">NFC Forum</a>
-  website. The NFCDemo sample application also declares sample <a href=
-  "{@docRoot}resources/samples/NFCDemo/src/com/example/android/nfc/simulator/MockNdefMessages.html">
-  plain text and SmartPoster NDEF messages.</a></p>
-
-  <h2 id="read">Reading an NFC Tag</h2>
-
-  <p>When a device comes in proximity to an NFC tag, the appropriate intent is started on the
-  device, notifying interested applications that a NFC tag was scanned. By previously declaring the
-  appropriate intent filter in your <code>AndroidManifest.xml</code> file or using foreground
-  dispatching, your application can request to handle the intent.</p>
-
-  <p>The following method (slightly modified from the NFCDemo sample application), handles the
-  <code>TAG_DISCOVERED</code> intent and iterates through an array obtained from the intent that
-  contains the NDEF payload:</p>
-  <pre>
-NdefMessage[] getNdefMessages(Intent intent) {
-    // Parse the intent
-    NdefMessage[] msgs = null;
-    String action = intent.getAction();
-    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
-        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
-        if (rawMsgs != null) {
-            msgs = new NdefMessage[rawMsgs.length];
-            for (int i = 0; i &lt; rawMsgs.length; i++) {
-                msgs[i] = (NdefMessage) rawMsgs[i];
-            }
-        }
-        else {
-        // Unknown tag type
-            byte[] empty = new byte[] {};
-            NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
-            NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
-            msgs = new NdefMessage[] {msg};
-        }
-    }        
-    else {
-        Log.e(TAG, "Unknown intent " + intent);
-        finish();
-    }
-    return msgs;
-}
-</pre>
-
-  <p>Keep in mind that the data that the device reads is in bytes, so you must implement your own
-  logic if you need to present the data in a readable format to the user. The classes in
-  <code>com.example.android.nfc.record</code> of the NFCDemo sample show you how to parse some
-  common types of NDEF messages such as plain text or a SmartPoster.</p>
-
-  <h2 id="write">Writing to an NFC Tag</h2>
-
-  <p>Writing to an NFC tag involves constructing your NDEF message in bytes and using the
-  appropriate tag technology for the tag that you are writing to. The following code sample shows
-  you how to write a simple text message to a {@link android.nfc.tech.NdefFormatable} tag:</p>
-  <pre>
-NdefFormatable tag = NdefFormatable.get(t);
-Locale locale = Locale.US;
-final byte[] langBytes = locale.getLanguage().getBytes(Charsets.US_ASCII);
-String text = "Tag, you're it!";
-final byte[] textBytes = text.getBytes(Charsets.UTF_8);
-final int utfBit = 0;
-final char status = (char) (utfBit + langBytes.length);
-final byte[] data = Bytes.concat(new byte[] {(byte) status}, langBytes, textBytes);
-NdefRecord record = NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
-try {
-    NdefRecord[] records = {text};
-    NdefMessage message = new NdefMessage(records);
-    tag.connect();
-    tag.format(message);
-}
-catch (Exception e){
-    //do error handling
-}
-</pre>
-
-  <h2 id="p2p">Peer-to-Peer Data Exchange</h2>
-
-  <p>Support for simple peer-to-peer data exchange is supported by the foreground push feature,
-  which is enabled with the {@link android.nfc.NfcAdapter#enableForegroundNdefPush} method. To use
-  this feature:</p>
-
-  <ul>
-    <li>The Activity that is pushing the data must be in the foreground</li>
-
-    <li>You must encapsulate the data that you are sending in an {@link android.nfc.NdefMessage}
-    object</li>
-
-    <li>The NFC device that is receiving the pushed data (the scanned device) must support the
-    <code>com.android.npp</code> NDEF push protocol, which is optional for Android devices.</li>
-  </ul>
-
-  <p class="note">If your Activity enables the foreground push feature and is in the foreground,
-  the standard intent dispatch system is disabled. However, if your Activity also enables
-  foreground dispatching, then it can still scan tags that match the intent filters set in the
-  foreground dispatching.</p>
-
-  <p>To enable foreground dispatching:</p>
-
-  <ol>
-    <li>Create an NdefMessage that contains the NdefRecords that you want to push onto the other
-    device.</li>
-
-    <li>Implement the {@link android.app.Activity#onResume onResume()} and {@link
-    android.app.Activity#onPause onPause()} callbacks in your Activity to appropriately handle the
-    foreground pushing lifecycle. You must call {@link
-    android.nfc.NfcAdapter#enableForegroundNdefPush} from the main thread and only when the
-    activity is in the foreground (calling in {@link android.app.Activity#onResume onResume()}
-    guarantees this).
-      <pre>
-public void onResume() {
-    super.onResume();
-    if (mAdapter != null)
-        mAdapter.enableForegroundNdefPush(this, myNdefMessage);
-}
-public void onPause() {
-    super.onPause();
-    if (mAdapter != null)
-        mAdapter.disableForegroundNdefPush(this);
-}
-</pre>
-    </li>
-  </ol>
-
-  <p>When the Activity is in the foreground, you can now tap the device to another device and push
-  the data to it. See the <a href=
-  "../../../resources/samples/ApiDemos/src/com/example/android/apis/nfc/ForegroundNdefPush.html">ForegroundNdefPush</a>
-  sample in API Demos for a simple example of peer-to-peer data exchange.</p>
\ No newline at end of file
+    <dt><strong><a href="{@docRoot}guide/topics/nfc/advanced-nfc.html">Advanced
+    NFC</a></strong></dt>
+    <dd>This document goes over the APIs that enable use of the various tag technologies that
+    Android supports. When you are not working with NDEF data, or when you are working with NDEF
+    data that Android cannot fully understand, you have to manually read or write to the tag in raw
+    bytes using your own protocol stack. In these cases, Android provides support to detect
+    certain tag technologies and to open communication with the tag using your own protocol
+    stack.</dd>
+  </dl>
+</p>
\ No newline at end of file
diff --git a/docs/html/guide/topics/nfc/nfc.jd b/docs/html/guide/topics/nfc/nfc.jd
new file mode 100644
index 0000000..892e418
--- /dev/null
+++ b/docs/html/guide/topics/nfc/nfc.jd
@@ -0,0 +1,922 @@
+page.title=NFC Basics
+@jd:body
+
+
+<div id="qv-wrapper">
+<div id="qv">
+  <h2>In this document</h2>
+  <ol>
+    <li><a href="#tag-dispatch">The Tag Dispatch System</a>
+      <ol>
+        <li><a href="#ndef">How NFC tags are mapped to MIME types and URIs</a></li>
+        <li><a href="#dispatching">How NFC Tags are Dispatched to Applications</a></li>
+      </ol>
+    </li>
+    <li><a href="#filtering-intents">Filtering for Intents</a>
+      <ol>
+        <li><a href="#ndef-disc">ACTION_NDEF_DISCOVERED</a></li>
+        <li><a href="#tech-disc">ACTION_TECH_DISCOVERED</a></li>
+        <li><a href="#tag-disc">ACTION_TAG_DISCOVERED</a></li>
+        <li><a href="#obtain-info">Obtaining information from intents</a></li>
+      </ol>
+    </li>
+    <li><a href="#creating-records">Creating Common Types of NDEF Records</a>
+      <ol>
+        <li><a href="#abs-uri">TNF_ABSOLUTE_URI</a></li>
+        <li><a href="#mime">TNF_MIME_MEDIA</a></li>
+        <li><a href="#well-known-text">TNF_WELL_KNOWN with RTD_TEXT</a></li>
+        <li><a href="#well-known-uri">TNF_WELL_KNOWN with RTD_URI</a></li>
+        <li><a href="#ext-type">TNF_EXTERNAL_TYPE</a></li>
+        <li><a href="#aar">Android Application Records</a></li>
+      </ol>
+    </li>
+    <li><a href="#p2p">Beaming NDEF Messages to Other Devices</a></li>
+  </ol>
+</div>
+</div>
+
+<p>This document describes the basic NFC tasks you perform in Android. It explains how to send and
+receive NFC data in the form of NDEF messages and describes the Android framework APIs that support
+these features. For more advanced topics, including a discussion of working with non-NDEF data,
+see <a href="{@docRoot}guide/topics/nfc/advanced-nfc.html">Advanced NFC</a>.</p>
+
+
+<p>There are two major uses cases when working with NDEF data and Android:</p>
+
+<ul>
+  <li>Reading NDEF data from an NFC tag</li>
+  <li>Beaming NDEF messages from one device to another with <a href="#p2p">Android
+Beam&trade;</a></li>
+</ul>
+
+
+<p>Reading NDEF data from an NFC tag is handled with the <a href="#tag-dispatch">tag dispatch
+system</a>, which analyzes discovered NFC tags, appropriately categorizes the data, and starts
+an application that is interested in the categorized data. An application that wants to handle the
+scanned NFC tag can <a href="#filtering-intents">declare an intent filter</a> and
+request to handle the data.</p>
+
+<p>The Android Beam&trade; feature allows a device to push an NDEF message onto
+another device by physically tapping the devices together. This interaction provides an easier way
+to send data than other wireless technologies like Bluetooth, because with NFC, no manual device
+discovery or pairing is required. The connection is automatically started when two devices come
+into range. Android Beam is available through a set of NFC APIs, so any application can transmit
+information between devices. For example, the Contacts, Browser, and YouTube applications use
+Android Beam to share contacts, web pages, and videos with other devices.
+</p>
+
+
+<h2 id="tag-dispatch">The Tag Dispatch System</h2>
+
+<p>Android-powered devices are usually looking for NFC tags when the screen
+is unlocked, unless NFC is disabled in the device's Settings menu.
+When an Android-powered device discovers an NFC tag, the desired behavior
+is to have the most appropriate activity handle the intent without asking the user what application
+to use. Because devices scan NFC tags at a very short range, it is likely that making users manually
+select an activity would force them to move the device away from the tag and break the connection.
+You should develop your activity to only handle the NFC tags that your activity cares about to
+prevent the Activity Chooser from appearing.</p>
+
+<p>To help you with this goal, Android provides a special tag dispatch system that analyzes scanned
+NFC tags, parses them, and tries to locate applications that are interested in the scanned data. It
+does this by:</p>
+
+<ol>
+  <li>Parsing the NFC tag and figuring out the MIME type or a URI that identifies the data payload
+  in the tag.</li>
+  <li>Encapsulating the MIME type or URI and the payload into an intent. These first two
+  steps are described in <a href="#ndef">How NFC tags are mapped to MIME types and URIs</a>.</li>
+  <li>Starts an activity based on the intent. This is described in
+  <a href="#dispatching">How NFC Tags are Dispatched to Applications</a>.</li>
+</ol>
+
+<h3 id="ndef">How NFC tags are mapped to MIME types and URIs</h3>
+<p>Before you begin writing your NFC applications, it is important to understand the different
+types of NFC tags, how the tag dispatch system parses NFC tags, and the special work that the tag
+dispatch system does when it detects an NDEF message. NFC tags come in a
+wide array of technologies and can also have data written to them in many different ways.
+Android has the most support for the NDEF standard, which is defined by the <a
+href="http://www.nfc-forum.org/home">NFC Forum</a>.
+</p>
+
+<p>NDEF data is encapsulated inside a message ({@link android.nfc.NdefMessage}) that contains one
+or more records ({@link android.nfc.NdefRecord}). Each NDEF record must be well-formed according to
+the specification of the type of record that you want to create. Android
+also supports other types of tags that do not contain NDEF data, which you can work with by using
+the classes in the {@link android.nfc.tech} package. To learn more
+about these technologies, see the <a href="{@docRoot}guide/topics/nfc/advanced-nfc.html">Advanced
+NFC</a> topic. Working with these other types of tags involves
+writing your own protocol stack to communicate with the tags, so we recommend using NDEF when
+possible for ease of development and maximum support for Android-powered devices.
+</p>
+
+<p class="note"><strong>Note:</strong>
+To download complete NDEF specifications, go to the <a
+href="http://www.nfc-forum.org/specs/spec_license">NFC Forum Specification Download</a> site and see
+<a href="#creating-records">Creating common types of NDEF records</a> for examples of how to
+construct NDEF records. </p>
+
+<p>Now that you have some background in NFC tags, the following sections describe in more detail how
+Android handles NDEF formatted tags. When an Android-powered device scans an NFC tag containing NDEF
+formatted data, it parses the message and tries to figure out the data's MIME type or identifying
+URI. To do this, the system reads the first {@link android.nfc.NdefRecord} inside the {@link
+android.nfc.NdefMessage} to determine how to interpret the entire NDEF message (an NDEF message can
+have multiple NDEF records). In a well-formed NDEF message, the first {@link android.nfc.NdefRecord}
+contains the following fields:
+<dl>
+  <dt><strong>3-bit TNF (Type Name Format)</strong></dt>
+  <dd>Indicates how to interpret the variable length type field. Valid values are described in
+described in <a href="#table1">Table 1</a>.</dd>
+
+  <dt><strong>Variable length type</strong></dt>
+  <dd>Describes the type of the record. If using {@link android.nfc.NdefRecord#TNF_WELL_KNOWN}, use
+this field to specify the Record Type Definition (RTD). Valid RTD values are described in <a
+href="#table2">Table 2</a>.</dd>
+
+<dt><strong>Variable length ID</strong></dt>
+<dd>A unique identifier for the record. This field is not used often, but
+if you need to uniquely identify a tag, you can create an ID for it.</dd>
+
+<dt><strong>Variable length payload</strong></dt>
+<dd>The actual data payload that you want to read or write. An NDEF
+message can contain multiple NDEF records, so don't assume the full payload is in the first NDEF
+record of the NDEF message.</dd>
+
+</dl>
+
+<p>The tag dispatch system uses the TNF and type fields to try to map a MIME type or URI to the
+NDEF message. If successful, it encapsulates that information inside of a {@link
+android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent along with the actual payload. However, there
+are cases when the tag dispatch system cannot determine the type of data based on the first NDEF
+record. This happens when the NDEF data cannot be mapped to a MIME type or URI, or when the
+NFC tag does not contain NDEF data to begin with. In such cases, a {@link
+android.nfc.Tag} object that has information about the tag's technologies and the payload are
+encapsulated inside of a {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent instead.</p>
+
+<p>
+<a href="#table1">Table 1.</a> describes how the tag dispatch system maps TNF and type
+fields to MIME types or URIs. It also describes which TNFs cannot be mapped to a MIME type or URI.
+In these cases, the tag dispatch system falls back to
+{@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.
+
+<p>For example, if the tag dispatch system encounters a record of type {@link
+android.nfc.NdefRecord#TNF_ABSOLUTE_URI}, it maps the variable length type field of that record
+into a URI. The tag dispatch system encapsulates that URI in the data field of an {@link
+android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent along with other information about the tag,
+such as the payload. On the other hand, if it encounters a record of type {@link
+android.nfc.NdefRecord#TNF_UNKNOWN}, it creates an intent that encapsulates the tag's technologies
+instead.</p>
+
+
+<p class="table-caption" id="table1">
+  <strong>Table 1.</strong> Supported TNFs and their mappings</p>
+<table id="mappings">
+  <tr>
+    <th>Type Name Format (TNF)</th>
+    <th>Mapping</th>
+  </tr>
+  <tr>
+    <td>{@link android.nfc.NdefRecord#TNF_ABSOLUTE_URI}</td>
+    <td>URI based on the type field.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#TNF_EMPTY}</td>
+    <td>Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#TNF_EXTERNAL_TYPE}</td>
+    <td>URI based on the URN in the type field. The URN is encoded into the NDEF type field in
+        a shortened form: <code><em>&lt;domain_name&gt;:&lt;service_name&gt;</em></code>.
+        Android maps this to a URI in the form:
+        <code>vnd.android.nfc://ext/<em>&lt;domain_name&gt;:&lt;service_name&gt;</em></code>.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#TNF_MIME_MEDIA}</td>
+    <td>MIME type based on the type field.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#TNF_UNCHANGED}</td>
+    <td>Invalid in the first record, so falls back to
+        {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#TNF_UNKNOWN}</td>
+    <td>Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#TNF_WELL_KNOWN}</td>
+    <td>MIME type or URI depending on the Record Type Definition (RTD), which you set in the
+type field. See <a  href="#well_known">Table 2.</a> for more information on
+available RTDs and their mappings.</td>
+  </tr>
+</table>
+
+<p class="table-caption" id="table2">
+  <strong>Table 2.</strong> Supported RTDs for TNF_WELL_KNOWN and their
+mappings</p>
+<table id="well-known">
+  <tr>
+    <th>Record Type Definition (RTD)</th>
+    <th>Mapping</th>
+  </tr>
+  <tr>
+    <td>{@link android.nfc.NdefRecord#RTD_ALTERNATIVE_CARRIER}</td>
+    <td>Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#RTD_HANDOVER_CARRIER}</td>
+    <td>Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#RTD_HANDOVER_REQUEST}</td>
+    <td>Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#RTD_HANDOVER_SELECT}</td>
+    <td>Falls back to {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#RTD_SMART_POSTER}</td>
+    <td>URI based on parsing the payload.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#RTD_TEXT}</td>
+    <td>MIME type of <code>text/plain</code>.</td>
+  </tr>
+    <td>{@link android.nfc.NdefRecord#RTD_URI}</td>
+    <td>URI based on payload.</td>
+  </tr>
+</table>
+
+<h3 id="dispatching">How NFC Tags are Dispatched to Applications</h3>
+
+<p>When the tag dispatch system is done creating an intent that encapsulates the NFC tag and its
+identifying information, it sends the intent to an interested application that
+filters for the intent. If more than one application can handle the intent, the Activity Chooser
+is presented so the user can select the Activity. The tag dispatch system defines three intents,
+which are listed in order of highest to lowest priority:</p>
+
+<ol>
+  <li>
+      {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED}: This intent is used to start an
+Activity when a tag that contains an NDEF payload is scanned and is of a recognized type. This is
+the highest priority intent, and the tag dispatch system tries to start an Activity with this
+intent before any other intent, whenever possible.
+  </li>
+
+    <li>{@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}: If no activities register to
+handle the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED}
+intent, the tag dispatch system tries to start an application with this intent. This
+intent is also directly started (without starting {@link
+android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} first) if the tag that is scanned
+contains NDEF data that cannot be mapped to a MIME type or URI, or if the tag does not contain NDEF
+data but is of a known tag technology.
+</li>
+
+    <li>{@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}: This intent is started
+    if no activities handle the {@link
+android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link
+android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}
+    intents.</li>
+  </ol>
+
+<p>The basic way the tag dispatch system works is as follows:</p>
+
+<ol>
+  <li>Try to start an Activity with the intent that was created by the tag dispatch system
+when parsing the NFC tag (either
+{@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link
+android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}).</li>
+  <li>If no activities filter for that intent, try to start an Activity with the next
+  lowest priority intent (either {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} or {@link
+android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}) until an application filters for the
+  intent or until the tag dispatch system tries all possible intents.</li>
+  <li>If no applications filter for any of the intents, do nothing.</li>
+</ol>
+
+<img src="{@docRoot}images/nfc_tag_dispatch.png" />
+
+<p class="figure"><strong>Figure 1. </strong> Tag Dispatch System</p>
+
+
+<p>Whenever possible, work with NDEF messages and the {@link
+android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent, because it is the most specific out of
+the three. This intent allows you to start your application at a more appropriate time than the
+other two intents, giving the user a better experience.</p>
+
+<h2 id="manifest">Requesting NFC Access in the Android Manifest</h2>
+
+  <p>Before you can access a device's NFC hardware and properly handle NFC intents, declare these
+  items in your <code>AndroidManifest.xml</code> file:</p>
+
+  <ul>
+    <li>The NFC <code>&lt;uses-permission&gt;</code> element to access the NFC hardware:
+      <pre>
+&lt;uses-permission android:name="android.permission.NFC" /&gt;
+</pre>
+    </li>
+
+    <li>The minimum SDK version that your application can support. API level 9 only supports
+    limited tag dispatch via {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}, and only gives
+    access to NDEF messages via the {@link android.nfc.NfcAdapter#EXTRA_NDEF_MESSAGES} extra. No
+    other tag properties or I/O operations are accessible. API level 10
+    includes comprehensive reader/writer support as well as foreground NDEF pushing, and API level
+    14 provides an easier way to push NDEF messages to other devices with Android Beam and extra
+    convenience methods to create NDEF records.
+<pre class="pretty-print">
+&lt;uses-sdk android:minSdkVersion="10"/&gt;
+</pre>
+    </li>
+
+    <li>The <code>uses-feature</code> element so that your application shows up in the Android
+Market only for devices that have NFC hardware:
+      <pre>
+&lt;uses-feature android:name="android.hardware.nfc" android:required="true" /&gt;
+</pre>
+<p>If your application uses NFC functionality, but that functionality is not crucial to your
+application, you can omit the <code>uses-feature</code> element and check for NFC avalailbility at
+runtime by checking to see if {@link android.nfc.NfcAdapter#getDefaultAdapter getDefaultAdapter()}
+is <code>null</code>.</p>
+    </li>
+  </ul>
+
+  <h2 id="filtering-intents">Filtering for NFC Intents</h2>
+
+  <p>To start your application when an NFC tag that you want to handle is scanned, your application
+can filter for one, two, or all three of the NFC intents in the Android manifest. However, you
+usually want to filter for the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intent for the
+most control of when your application starts. The {@link
+android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent is a fallback for {@link
+android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} when no applications filter for
+ {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or for when the payload is not
+NDEF. Filtering for {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} is usually too general of a
+category to filter on.  Many applications will filter for {@link
+android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link
+android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} before {@link
+android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED}, so your application has a low probability of
+starting. {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} is only available as a last resort
+for applications to filter for in the cases where no other applications are installed to handle the
+{@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} or {@link
+android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED}intent.</p>
+
+<p>Because NFC tag deployments vary and are many times not under your control, this is not always
+possible, which is why you can fallback to the other two intents when necessary. When you have
+control over the types of tags and data written, it is recommended that you use NDEF to format your
+tags. The following sections describe how to filter for each type of intent.</p>
+
+
+<h3 id="ndef-disc">ACTION_NDEF_DISCOVERED</h3>
+<p>
+To filter for {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED} intents, declare the
+intent filter along with the type of data that you want to filter for. The
+following example filters for {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED}
+intents with a MIME type of <code>text/plain</code>:
+</p>
+<pre>
+&lt;intent-filter&gt;
+    &lt;action android:name="android.nfc.action.NDEF_DISCOVERED"/&gt;
+    &lt;category android:name="android.intent.category.DEFAULT"/&gt;
+    &lt;data android:mimeType="text/plain" /&gt;
+&lt;/intent-filter&gt;
+</pre>
+<p>The following example filters for a URI in the form of
+<code>http://developer.android.com/index.html</code>.
+<pre>
+&lt;intent-filter&gt;
+    &lt;action android:name="android.nfc.action.NDEF_DISCOVERED"/&gt;
+    &lt;category android:name="android.intent.category.DEFAULT"/&gt;
+   &lt;data android:scheme="http"
+              android:host="developer.android.com"
+              android:pathPrefix="/index.html" />
+&lt;/intent-filter&gt;
+</pre>
+
+
+  <h3 id="tech-disc">ACTION_TECH_DISCOVERED</h3>
+
+  <p>If your activity filters for the {@link android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent,
+you must create an XML resource file that specifies the technologies that your activity supports
+within a <code>tech-list</code> set. Your activity is
+  considered a match if a <code>tech-list</code> set is a subset of the technologies that are
+  supported by the tag, which you can obtain by calling {@link android.nfc.Tag#getTechList
+  getTechList()}.</p>
+
+  <p>For example, if the tag that is scanned supports MifareClassic, NdefFormatable, and NfcA, your
+  <code>tech-list</code> set must specify all three, two, or one of the technologies (and nothing
+  else) in order for your activity to be matched.</p>
+
+  <p>The following sample defines all of the technologies. You can remove the ones that you do not
+  need. Save this file (you can name it anything you wish) in the
+  <code>&lt;project-root&gt;/res/xml</code> folder.</p>
+  <pre>
+&lt;resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"&gt;
+    &lt;tech-list&gt;
+        &lt;tech&gt;android.nfc.tech.IsoDep&lt;/tech&gt;
+        &lt;tech&gt;android.nfc.tech.NfcA&lt;/tech&gt;
+        &lt;tech&gt;android.nfc.tech.NfcB&lt;/tech&gt;
+        &lt;tech&gt;android.nfc.tech.NfcF&lt;/tech&gt;
+        &lt;tech&gt;android.nfc.tech.NfcV&lt;/tech&gt;
+        &lt;tech&gt;android.nfc.tech.Ndef&lt;/tech&gt;
+        &lt;tech&gt;android.nfc.tech.NdefFormatable&lt;/tech&gt;
+        &lt;tech&gt;android.nfc.tech.MifareClassic&lt;/tech&gt;
+        &lt;tech&gt;android.nfc.tech.MifareUltralight&lt;/tech&gt;
+    &lt;/tech-list&gt;
+&lt;/resources&gt;
+</pre>
+
+  <p>You can also specify multiple <code>tech-list</code> sets. Each of the <code>tech-list</code>
+  sets is considered independently, and your activity is considered a match if any single
+  <code>tech-list</code> set is a subset of the technologies that are returned by {@link
+  android.nfc.Tag#getTechList getTechList()}. This provides <code>AND</code> and <code>OR</code>
+  semantics for matching technologies. The following example matches tags that can support the
+  NfcA and Ndef technologies or can support the NfcB and Ndef technologies:</p>
+  <pre>
+&lt;resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"&gt;
+    &lt;tech-list&gt;
+        &lt;tech&gt;android.nfc.tech.NfcA&lt;/tech&gt;
+        &lt;tech&gt;android.nfc.tech.Ndef&lt;/tech&gt;
+    &lt;/tech-list&gt;
+&lt;/resources&gt;
+
+&lt;resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"&gt;
+    &lt;tech-list&gt;
+        &lt;tech&gt;android.nfc.tech.NfcB&lt;/tech&gt;
+        &lt;tech&gt;android.nfc.tech.Ndef&lt;/tech&gt;
+    &lt;/tech-list&gt;
+&lt;/resources&gt;
+</pre>
+
+  <p>In your <code>AndroidManifest.xml</code> file, specify the resource file that you just created
+  in the <code>&lt;meta-data&gt;</code> element inside the <code>&lt;activity&gt;</code>
+  element like in the following example:</p>
+  <pre>
+&lt;activity&gt;
+...
+&lt;intent-filter&gt;
+    &lt;action android:name="android.nfc.action.TECH_DISCOVERED"/&gt;
+&lt;/intent-filter&gt;
+
+&lt;meta-data android:name="android.nfc.action.TECH_DISCOVERED"
+    android:resource="@xml/nfc_tech_filter" /&gt;
+...
+&lt;/activity&gt;
+</pre>
+
+<p>For more information about working with tag technologies and the {@link
+android.nfc.NfcAdapter#ACTION_TECH_DISCOVERED} intent, see <a
+href="{@docRoot}guide/topics/nfc/advanced-nfc.html#tag-tech">Working with Supported Tag
+Technologies</a> in the Advanced NFC document.</p>
+<h3 id="tag-disc">ACTION_TAG_DISCOVERED</h3>
+<p>To filter for {@link android.nfc.NfcAdapter#ACTION_TAG_DISCOVERED} use the following intent
+filter:</p>
+
+
+<pre>&lt;intent-filter&gt;
+    &lt;action android:name="android.nfc.action.TAG_DISCOVERED"/&gt;
+&lt;/intent-filter&gt;
+</pre>
+
+
+
+<h3 id="obtain-info">Obtaining information from intents</h3>
+
+<p>If an activity starts because of an NFC intent, you can obtain information about the scanned NFC
+tag from the intent. Intents can contain the following extras depending on the tag that was scanned:
+
+<ul>
+  <li>{@link android.nfc.NfcAdapter#EXTRA_TAG} (required): A {@link android.nfc.Tag} object
+representing the scanned tag.</li>
+  <li>{@link android.nfc.NfcAdapter#EXTRA_NDEF_MESSAGES} (optional): An array of NDEF messages
+parsed from the tag. This extra is mandatory on {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED
+intents.</li>
+  <li>{@link android.nfc.NfcAdapter#EXTRA_ID} (optional): The low-level ID of the tag.</li></ul>
+
+<p>To obtain these extras, check to see if your activity was launched with one of
+the NFC intents to ensure that a tag was scanned, and then obtain the extras out of the
+intent. The following example checks for the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED}
+intent and gets the NDEF messages from an intent extra.</p>
+
+<pre>
+public void onResume() {
+    super.onResume();
+    ...
+    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
+        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
+        if (rawMsgs != null) {
+            msgs = new NdefMessage[rawMsgs.length];
+            for (int i = 0; i &lt; rawMsgs.length; i++) {
+                msgs[i] = (NdefMessage) rawMsgs[i];
+            }
+        }
+    }
+    //process the msgs array
+}
+</pre>
+
+<p>Alternatively, you can obtain a {@link android.nfc.Tag} object from the intent, which will
+contain the payload and allow you to enumerate the tag's technologies:</p>
+
+<pre>Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);</pre>
+
+
+<h2 id="creating-records">Creating Common Types of NDEF Records</h2>
+<p>This section describes how to create common types of NDEF records to help you when writing to
+NFC tags or sending data with Android Beam. It also describes how to create the corresponding
+intent filter for the record. All of these NDEF record examples should be in the first NDEF
+record of the NDEF message that you are writing to a tag or beaming.</p>
+
+<h3 id="abs-uri">TNF_ABSOLUTE_URI</h3>
+<p>Given the following {@link android.nfc.NdefRecord#TNF_ABSOLUTE_URI} NDEF record, which is
+stored as the first record inside of an {@link android.nfc.NdefMessage}:</p>
+
+<pre>
+NdefRecord uriRecord = new NdefRecord(
+    NdefRecord.TNF_ABSOLUTE_URI ,
+    "http://developer.android.com/index.html".getBytes(Charset.forName("US-ASCII")),
+    new byte[0], new byte[0]);
+</pre>
+
+<p>the intent filter would look like this:</p>
+<pre>
+&lt;intent-filter&gt;
+    &lt;action android:name="android.nfc.action.NDEF_DISCOVERED" /&gt;
+    &lt;category android:name="android.intent.category.DEFAULT" /&gt;
+    &lt;data android:scheme="http"
+        android:host="developer.android.com"
+        android:pathPrefix="/index.html" /&gt;
+&lt;/intent-filter&gt;
+</pre>
+
+
+<h3 id="mime">TNF_MIME_MEDIA</h3>
+<p>Given the following {@link android.nfc.NdefRecord#TNF_MIME_MEDIA} NDEF record, which is stored as
+the first record inside
+of an {@link android.nfc.NdefMessage}:</p>
+<pre>
+NdefRecord mimeRecord = new NdefRecord(
+    NdefRecord.TNF_MIME_MEDIA ,
+    "application/com.example.android.beam".getBytes(Charset.forName("US-ASCII")),
+    new byte[0], "Beam me up, Android!".getBytes(Charset.forName("US-ASCII")));
+</pre>
+
+<p>the intent filter would look like this:</p>
+<pre>
+&lt;intent-filter&gt;
+    &lt;action android:name="android.nfc.action.NDEF_DISCOVERED" /&gt;
+    &lt;category android:name="android.intent.category.DEFAULT" /&gt;
+    &lt;data android:mimeType="application/com.example.android.beam" /&gt;
+&lt;/intent-filter&gt;
+</pre>
+
+
+<h3 id="well-known-text">TNF_WELL_KNOWN with RTD_TEXT</h3>
+
+<p>Given the following {@link android.nfc.NdefRecord#TNF_WELL_KNOWN} NDEF record, which is stored as
+the first record inside of an {@link android.nfc.NdefMessage}:</p>
+<pre>
+public NdefRecord createTextRecord(String payload, Locale locale, boolean encodeInUtf8) {
+    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
+    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
+    byte[] textBytes = payload.getBytes(utfEncoding);
+    int utfBit = encodeInUtf8 ? 0 : (1 &lt;&lt; 7);
+    char status = (char) (utfBit + langBytes.length);
+    byte[] data = new byte[1 + langBytes.length + textBytes.length];
+    data[0] = (byte) status;
+    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
+    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
+    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
+    NdefRecord.RTD_TEXT, new byte[0], data);
+    return record;
+}
+</pre>
+
+<p>the intent filter would look like this:</p>
+<pre>
+&lt;intent-filter&gt;
+    &lt;action android:name="android.nfc.action.NDEF_DISCOVERED" /&gt;
+    &lt;category android:name="android.intent.category.DEFAULT" /&gt;
+    &lt;data android:mimeType="text/plain" /&gt;
+&lt;/intent-filter&gt;
+</pre>
+
+
+<h3 id="well-known-uri">TNF_WELL_KNOWN with RTD_URI</h3>
+
+<p>Given the following {@link android.nfc.NdefRecord#TNF_WELL_KNOWN} NDEF record, which is stored as
+the first record inside of an {@link android.nfc.NdefMessage}:</p>
+
+<pre>
+byte[] uriField = "example.com".getBytes(Charset.forName("US-ASCII"));
+byte[] payload = new byte[uriField.length + 1];              //add 1 for the URI Prefix
+byte payload[0] = 0x01;                                      //prefixes http://www. to the URI
+System.arraycopy(uriField, 0, payload, 1, uriField.length);  //appends URI to payload
+NdefRecord rtdUriRecord = new NdefRecord(
+    NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[0], payload);
+</pre>
+
+<p>the intent filter would look like this:</p>
+
+<pre>
+&lt;intent-filter&gt;
+    &lt;action android:name="android.nfc.action.NDEF_DISCOVERED" /&gt;
+    &lt;category android:name="android.intent.category.DEFAULT" /&gt;
+    &lt;data android:scheme="http"
+        android:host="example.com"
+        android:pathPrefix="" /&gt;
+&lt;/intent-filter&gt;
+</pre>
+
+<h3 id="ext-type">TNF_EXTERNAL_TYPE</h3>
+<p>Given the following {@link android.nfc.NdefRecord#TNF_EXTERNAL_TYPE} NDEF record, which is stored
+as the first record inside of an {@link android.nfc.NdefMessage}:</p>
+
+<pre>
+byte[] payload;
+...
+NdefRecord mimeRecord = new NdefRecord(
+    NdefRecord.TNF_EXTERNAL_TYPE, "example.com:externalType", new byte[0], payload);
+</pre>
+
+<p>the intent filter would look like this:</p>
+<pre>
+&lt;intent-filter&gt;
+    &lt;action android:name="android.nfc.action.NDEF_DISCOVERED" /&gt;
+    &lt;category android:name="android.intent.category.DEFAULT" /&gt;
+    &lt;data android:scheme="vnd.android.nfc"
+        android:host="ext"
+        android:pathPrefix="/example.com:externalType"/&gt;
+&lt;/intent-filter&gt;
+</pre>
+
+
+<p>Use TNF_EXTERNAL_TYPE for more generic NFC tag deployments to better support both
+Android-powered and non-Android-powered devices.</p>
+
+<p class="note"><strong>Note</strong>: URNs for {@link
+android.nfc.NdefRecord#TNF_EXTERNAL_TYPE} have a canonical format of:
+<code>urn:nfc:ext:example.com:externalType</code>, however the NFC Forum RTD specification
+declares that the <code>urn:nfc:ext:</code> portion of the URN must be ommitted from the
+NDEF record. So all you need to provide is the domain (<code>example.com</code> in the example)
+and type (<code>externalType</code> in the example) separated by a colon.
+When dispatching TNF_EXTERNAL_TYPE, Android converts the <code>urn:nfc:ext:example.com:externalType</code> URN to a
+<code>vnd.android.nfc://ext/example.com:externalType</code> URI, which is what the intent filter in the example
+declares.</p>
+
+<h3 id="aar">Android Application Records</h3>
+
+<p>
+Introduced in Android 4.0 (API level 14), an Android Application Record (AAR) provides a stronger
+certainty that your application is started when an NFC tag is scanned. An AAR has the package name
+of an application embedded inside an NDEF record. You can add an AAR to any NDEF record of your NDEF message,
+because Android searches the entire NDEF message for AARs. If it finds an AAR, it starts the application based
+on the package name inside the AAR. If the application is not present on the device,
+Android Market is launched to download the application.</p>
+
+<p>AARs are useful if you want to prevent other applications from filtering for the same intent and
+potentially handling specific tags that you have deployed. AARs are only supported at the
+application level, because of the package name constraint, and not at the Activity level as with
+intent filtering. If you want to handle an intent at the Activity level, <a
+href="filtering-intents">use intent filters</a>.
+</p>
+
+
+
+<p>If a tag contains an AAR, the tag dispatch system dispatches in the following manner:</p>
+<ol>
+  <li>Try to start an Activity using an intent filter as normal. If the Activity that matches
+the intent also matches the AAR, start the Activity.</li>
+  <li>If the Activity that filters for the intent does not match the
+AAR, if multiple Activities can handle the intent, or if no Activity handles the intent, start the
+application specified by the AAR.</li>
+  <li>If no application can start with the AAR, go to the Android Market to download the
+application based on the AAR.</li>
+</ol>
+
+</p>
+
+<p class="note"><strong>Note:</strong> You can override AARs and the intent dispatch system with the <a
+href="{@docRoot}guide/topics/nfc/advanced-nfc.html#foreground-dispatch">foreground dispatch
+system</a>, which allows a foreground activity to have priority when an NFC tag is discovered.
+With this method, the activity must be in the foreground to
+override AARs and the intent dispatch system.</p>
+
+<p>If you still want to filter for scanned tags that do not contain an AAR, you can declare
+intent filters as normal. This is useful if your application is interested in other tags
+that do not contain an AAR. For example, maybe you want to guarantee that your application handles
+proprietary tags that you deploy as well as general tags deployed by third parties. Keep in mind
+that AARs are specific to Android 4.0 devices or later, so when deploying tags, you most likely want
+to use a combination of AARs and MIME types/URIs to support the widest range of devices. In
+addition, when you deploy NFC tags, think about how you want to write your NFC tags to enable
+support for the most devices (Android-powered and other devices). You can do this by
+defining a relatively unique MIME type or URI to make it easier for applications to distinguish.
+</p>
+
+<p>Android provides a simple API to create an AAR,
+{@link android.nfc.NdefRecord#createApplicationRecord createApplicationRecord()}. All you need to
+do is embed the AAR anywhere in your {@link android.nfc.NdefMessage}. You do not want
+to use the first record of your {@link android.nfc.NdefMessage}, unless the AAR is the only
+record in the {@link android.nfc.NdefMessage}. This is because the Android
+system checks the first record of an {@link android.nfc.NdefMessage} to determine the MIME type or
+URI of the tag, which is used to create an intent for applications to filter. The following code
+shows you how to create an AAR:</p>
+
+<pre>
+NdefMessage msg = new NdefMessage(
+        new NdefRecord[] {
+            ...,
+            NdefRecord.createApplicationRecord("com.example.android.beam")}
+</pre>
+
+
+<h2 id="p2p">Beaming NDEF Messages to Other Devices</h2>
+
+<p>Android Beam allows simple peer-to-peer data exchange between two Android-powered devices. The
+application that wants to beam data to another device must be in the foreground and the device
+receiving the data must not be locked. When the beaming device comes in close enough contact with a
+receiving device, the beaming device displays the "Touch to Beam" UI. The user can then choose
+whether or not to beam the message to the receiving device.</p>
+
+<p class="note"><strong>Note:</strong> Foreground NDEF pushing was available at API level 10,
+which provides similar functionality to Android Beam. These APIs have since been deprecated, but
+are available to support older devices. See {@link android.nfc.NfcAdapter#enableForegroundNdefPush
+enableForegroundNdefPush()} for more information.</p>
+
+<p>You can enable Android Beam for your application by calling one of the two methods:</p>
+  <ul>
+    <li>{@link android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()}: Accepts an
+{@link android.nfc.NdefMessage} to set as the message to beam. Automatically beams the message
+when two devices are in close enough proximity.</li>
+    <li>{@link android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()}:
+Accepts a callback that contains a
+{@link android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()}
+which is called when a device is in range to beam data to. The callback lets you create
+the NDEF message only when necessary.</li>
+  </ul>
+
+<p>An activity can only push one NDEF message at a time, so {@link
+android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()} takes precedence
+over {@link android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} if both are set. To use
+Android Beam, the following general guidelines must be met:
+</p>
+
+  <ul>
+    <li>The activity that is beaming the data must be in the foreground. Both devices must have
+their screens unlocked.</li>
+
+    <li>You must encapsulate the data that you are beaming in an {@link android.nfc.NdefMessage}
+    object.</li>
+
+    <li>The NFC device that is receiving the beamed data must support the
+    <code>com.android.npp</code> NDEF push protocol or NFC Forum's SNEP (Simple NDEF Exchange
+Protocol). The <code>com.android.npp</code> protocol is required for devices on API level 9 (Android
+2.3) to API level 13 (Android 3.2). <code>com.android.npp</code> and SNEP are both required on
+API level 14 (Android 4.0) and later.</li>
+</li>
+  </ul>
+
+  <p class="note"><strong>Note:</strong> If your activity enables Android Beam and is
+in the foreground, the standard intent dispatch system is disabled. However, if your activity also
+enables <a href="{@docRoot}guide/topics/nfc/advanced-nfc.html#foreground-dispatch">foreground
+dispatching</a>, then it can still scan tags that match the intent filters set in the foreground
+dispatching.</p>
+
+  <p>To enable Android Beam:</p>
+
+  <ol>
+    <li>Create an {@link android.nfc.NdefMessage} that contains the {@link android.nfc.NdefRecord}s
+that you want to push onto the other device.</li>
+
+    <li>Call {@link
+android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} with a {@link
+android.nfc.NdefMessage} or call {@link
+android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback} passing in a {@link
+android.nfc.NfcAdapter.CreateNdefMessageCallback} object in the <code>onCreate()</code> method of
+your activity. These methods require at least one activity that you want to enable with Android
+Beam, along with an optional list of other activities to activate.
+
+<p>In general, you normally use {@link
+android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} if your Activity only needs to
+push the same NDEF message at all times, when two devices are in range to communicate. You use
+{@link android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback} when your
+application cares about the current context of the application and wants to push an NDEF message
+depending on what the user is doing in your application.</p>
+    </li>
+  </ol>
+
+<p>The following sample shows how a simple activity calls {@link
+android.nfc.NfcAdapter.CreateNdefMessageCallback} in the <code>onCreate()</code> method of an
+activity (see <a href="{@docRoot}resources/samples/AndroidBeam/index.html"></a> for the
+complete sample). This example also has methods to help you create a MIME record:</p>
+
+<pre id="code-example">
+package com.example.android.beam;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.nfc.NdefMessage;
+import android.nfc.NdefRecord;
+import android.nfc.NfcAdapter;
+import android.nfc.NfcAdapter.CreateNdefMessageCallback;
+import android.nfc.NfcEvent;
+import android.os.Bundle;
+import android.os.Parcelable;
+import android.widget.TextView;
+import android.widget.Toast;
+import java.nio.charset.Charset;
+
+
+public class Beam extends Activity implements CreateNdefMessageCallback {
+    NfcAdapter mNfcAdapter;
+    TextView textView;
+
+    &#064;Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.main);
+        TextView textView = (TextView) findViewById(R.id.textView);
+        // Check for available NFC Adapter
+        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
+        if (mNfcAdapter == null) {
+            Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
+            finish();
+            return;
+        }
+        // Register callback
+        mNfcAdapter.setNdefPushMessageCallback(this, this);
+    }
+
+    &#064;Override
+    public NdefMessage createNdefMessage(NfcEvent event) {
+        String text = ("Beam me up, Android!\n\n" +
+                "Beam Time: " + System.currentTimeMillis());
+        NdefMessage msg = new NdefMessage(
+                new NdefRecord[] { createMimeRecord(
+                        "application/com.example.android.beam", text.getBytes())
+         /**
+          * The Android Application Record (AAR) is commented out. When a device
+          * receives a push with an AAR in it, the application specified in the AAR
+          * is guaranteed to run. The AAR overrides the tag dispatch system.
+          * You can add it back in to guarantee that this
+          * activity starts when receiving a beamed message. For now, this code
+          * uses the tag dispatch system.
+          */
+          //,NdefRecord.createApplicationRecord("com.example.android.beam")
+        });
+        return msg;
+    }
+
+    &#064;Override
+    public void onResume() {
+        super.onResume();
+        // Check to see that the Activity started due to an Android Beam
+        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
+            processIntent(getIntent());
+        }
+    }
+
+    &#064;Override
+    public void onNewIntent(Intent intent) {
+        // onResume gets called after this to handle the intent
+        setIntent(intent);
+    }
+
+    /**
+     * Parses the NDEF Message from the intent and prints to the TextView
+     */
+    void processIntent(Intent intent) {
+        textView = (TextView) findViewById(R.id.textView);
+        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
+                NfcAdapter.EXTRA_NDEF_MESSAGES);
+        // only one message sent during the beam
+        NdefMessage msg = (NdefMessage) rawMsgs[0];
+        // record 0 contains the MIME type, record 1 is the AAR, if present
+        textView.setText(new String(msg.getRecords()[0].getPayload()));
+    }
+
+    /**
+     * Creates a custom MIME type encapsulated in an NDEF record
+     */
+    public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
+        byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
+        NdefRecord mimeRecord = new NdefRecord(
+                NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
+        return mimeRecord;
+    }
+}
+</pre>
+
+<p>Note that this code comments out an AAR, which you can remove. If you enable the AAR, the
+application specified in the AAR always receives the Android Beam message. If the application is not
+present, the Android Market is started to download the application. Therefore, the following intent
+filter is not technically necessary for Android 4.0 devices or later if the AAR is used:
+</p>
+
+<pre>
+&lt;intent-filter&gt;
+  &lt;action android:name="android.nfc.action.NDEF_DISCOVERED"/&gt;
+  &lt;category android:name="android.intent.category.DEFAULT"/&gt;
+  &lt;data android:mimeType="application/com.example.android.beam"/&gt;
+&lt;/intent-filter&gt;
+</pre>
+<p>With this intent filter, the <code>com.example.android.beam</code> application now can be started
+when it scans an NFC tag or receives an Android Beam with an AAR of
+type <code>com.example.android.beam</code>, or when an NDEF formatted message contains a MIME record
+of type <code>application/com.example.android.beam</code>.</p>
+
+<p>Even though AARs guarantee an application is started or downloaded, intent filters are
+recommended, because they let you start an Activity of your choice in your
+application instead of always starting the main Activity within the package specified by an AAR.
+AARs do not have Activity level granularity. Also, because some Android-powered devices do not
+support AARs, you should also embed identifying information in the first NDEF record of your NDEF
+messages and filter for that as well, just in case. See <a href="#creating-records">Creating Common
+Types of NDEF records</a> for more information on how to create records.
+</p>
diff --git a/docs/html/guide/topics/resources/runtime-changes.jd b/docs/html/guide/topics/resources/runtime-changes.jd
index 74a9073..871b063 100644
--- a/docs/html/guide/topics/resources/runtime-changes.jd
+++ b/docs/html/guide/topics/resources/runtime-changes.jd
@@ -25,80 +25,78 @@
 <p>Some device configurations can change during runtime
 (such as screen orientation, keyboard availability, and language). When such a change occurs,
 Android restarts the running
-Activity ({@link android.app.Activity#onDestroy()} is called, followed by {@link
+{@link android.app.Activity} ({@link android.app.Activity#onDestroy()} is called, followed by {@link
 android.app.Activity#onCreate(Bundle) onCreate()}). The restart behavior is designed to help your
 application adapt to new configurations by automatically reloading your application with
-alternative resources.</p>
+alternative resources that match the new device configuration.</p>
 
-<p>To properly handle a restart, it is important that your Activity restores its previous
+<p>To properly handle a restart, it is important that your activity restores its previous
 state through the normal <a
 href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activity
 lifecycle</a>, in which Android calls
 {@link android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()} before it destroys
-your Activity so that you can save data about the application state. You can then restore the state
+your activity so that you can save data about the application state. You can then restore the state
 during {@link android.app.Activity#onCreate(Bundle) onCreate()} or {@link
-android.app.Activity#onRestoreInstanceState(Bundle) onRestoreInstanceState()}. To test
-that your application restarts itself with the application state intact, you should
-invoke configuration changes (such as changing the screen orientation) while performing various
-tasks in your application.</p>
+android.app.Activity#onRestoreInstanceState(Bundle) onRestoreInstanceState()}.</p>
 
-<p>Your application should be able to restart at any time without loss of user data or
-state in order to handle events such as when the user receives an incoming phone call and then
-returns to your application (read about the
-<a href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activity lifecycle</a>).</p>
+<p>To test that your application restarts itself with the application state intact, you should
+invoke configuration changes (such as changing the screen orientation) while performing various
+tasks in your application. Your application should be able to restart at any time without loss of
+user data or state in order to handle events such as configuration changes or when the user receives
+an incoming phone call and then returns to your application much later after your application
+process may have been destroyed. To learn how you can restore your activity state, read about the <a
+href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activity lifecycle</a>.</p>
 
 <p>However, you might encounter a situation in which restarting your application and
 restoring significant amounts of data can be costly and create a poor user experience. In such a
-situation, you have two options:</p>
+situation, you have two other options:</p>
 
 <ol type="a">
   <li><a href="#RetainingAnObject">Retain an object during a configuration change</a>
-  <p>Allow your Activity to restart when a configuration changes, but carry a stateful
-{@link java.lang.Object} to the new instance of your Activity.</p>
+  <p>Allow your activity to restart when a configuration changes, but carry a stateful
+{@link java.lang.Object} to the new instance of your activity.</p>
 
   </li>
   <li><a href="#HandlingTheChange">Handle the configuration change yourself</a>
-  <p>Prevent the system from restarting your Activity during certain configuration
-changes and receive a callback when the configurations do change, so that you can manually update
-your Activity as necessary.</p>
+  <p>Prevent the system from restarting your activity during certain configuration
+changes, but receive a callback when the configurations do change, so that you can manually update
+your activity as necessary.</p>
   </li>
 </ol>
 
 
 <h2 id="RetainingAnObject">Retaining an Object During a Configuration Change</h2>
 
-<p>If restarting your Activity requires that you recover large sets of data, re-establish a
-network connection, or perform other intensive operations, then a full restart due to a
-configuration change might
-be an unpleasant user experience. Also, it may not be possible for you to completely
-maintain your Activity state with the {@link android.os.Bundle} that the system saves for you during
-the Activity lifecycle&mdash;it is not designed to carry large objects (such as bitmaps) and the
-data within it must be serialized then deserialized, which can consume a lot of memory and make the
-configuration change slow. In such a situation, you can alleviate the burden of reinitializing
-your Activity by retaining a stateful Object when your Activity is restarted due to a configuration
-change.</p>
+<p>If restarting your activity requires that you recover large sets of data, re-establish a network
+connection, or perform other intensive operations, then a full restart due to a configuration change
+might be a slow user experience. Also, it might not be possible for you to completely restore your
+activity state with the {@link android.os.Bundle} that the system saves for you with the {@link
+android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()} callback&mdash;it is not
+designed to carry large objects (such as bitmaps) and the data within it must be serialized then
+deserialized, which can consume a lot of memory and make the configuration change slow. In such a
+situation, you can alleviate the burden of reinitializing your activity by retaining a stateful
+{@link java.lang.Object} when your activity is restarted due to a configuration change.</p>
 
-<p>To retain an Object during a runtime configuration change:</p>
+<p>To retain an object during a runtime configuration change:</p>
 <ol>
   <li>Override the {@link android.app.Activity#onRetainNonConfigurationInstance()} method to return
-the Object you would like to retain.</li>
-  <li>When your Activity is created again, call {@link
-android.app.Activity#getLastNonConfigurationInstance()} to recover your Object.</li>
+the object you would like to retain.</li>
+  <li>When your activity is created again, call {@link
+android.app.Activity#getLastNonConfigurationInstance()} to recover your object.</li>
 </ol>
 
-<p>Android calls {@link android.app.Activity#onRetainNonConfigurationInstance()} between {@link
-android.app.Activity#onStop()} and {@link
-android.app.Activity#onDestroy()} when it shuts down your Activity due to a configuration
-change. In your implementation of {@link
-android.app.Activity#onRetainNonConfigurationInstance()}, you can return any {@link
-java.lang.Object} that you need in order to efficiently restore your state after the configuration
-change.</p>
+<p>When the Android system shuts down your activity due to a configuration change, it calls {@link
+android.app.Activity#onRetainNonConfigurationInstance()} between the {@link
+android.app.Activity#onStop()} and {@link android.app.Activity#onDestroy()} callbacks. In your
+implementation of {@link android.app.Activity#onRetainNonConfigurationInstance()}, you can return
+any {@link java.lang.Object} that you need in order to efficiently restore your state after the
+configuration change.</p>
 
 <p>A scenario in which this can be valuable is if your application loads a lot of data from the
-web. If the user changes the orientation of the device and the Activity restarts, your application
+web. If the user changes the orientation of the device and the activity restarts, your application
 must re-fetch the data, which could be slow. What you can do instead is implement
 {@link android.app.Activity#onRetainNonConfigurationInstance()} to return an object carrying your
-data and then retrieve the data when your Activity starts again with {@link
+data and then retrieve the data when your activity starts again with {@link
 android.app.Activity#getLastNonConfigurationInstance()}. For example:</p>
 
 <pre>
@@ -113,11 +111,11 @@
 should never pass an object that is tied to the {@link android.app.Activity}, such as a {@link
 android.graphics.drawable.Drawable}, an {@link android.widget.Adapter}, a {@link android.view.View}
 or any other object that's associated with a {@link android.content.Context}. If you do, it will
-leak all the Views and resources of the original Activity instance. (To leak the resources
+leak all the views and resources of the original activity instance. (Leaking resources
 means that your application maintains a hold on them and they cannot be garbage-collected, so
 lots of memory can be lost.)</p>
 
-<p>Then retrieve the {@code data} when your Activity starts again:</p>
+<p>Then retrieve the data when your activity starts again:</p>
 
 <pre>
 &#64;Override
@@ -133,11 +131,10 @@
 }
 </pre>
 
-<p>In this case, {@link android.app.Activity#getLastNonConfigurationInstance()} retrieves
-the data saved by {@link android.app.Activity#onRetainNonConfigurationInstance()}. If {@code data}
-is null (which happens when the
-Activity starts due to any reason other than a configuration change) then the data object is loaded
-from the original source.</p>
+<p>In this case, {@link android.app.Activity#getLastNonConfigurationInstance()} returns the data
+saved by {@link android.app.Activity#onRetainNonConfigurationInstance()}. If {@code data} is null
+(which happens when the activity starts due to any reason other than a configuration change) then
+this code loads the data object from the original source.</p>
 
 
 
@@ -147,27 +144,27 @@
 
 <p>If your application doesn't need to update resources during a specific configuration
 change <em>and</em> you have a performance limitation that requires you to
-avoid the Activity restart, then you can declare that your Activity handles the configuration change
-itself, which prevents the system from restarting your Activity.</p>
+avoid the activity restart, then you can declare that your activity handles the configuration change
+itself, which prevents the system from restarting your activity.</p>
 
 <p class="note"><strong>Note:</strong> Handling the configuration change yourself can make it much
 more difficult to use alternative resources, because the system does not automatically apply them
-for you. This technique should be considered a last resort and is not recommended for most
-applications.</p>
+for you. This technique should be considered a last resort when you must avoid restarts due to a
+configuration change and is not recommended for most applications.</p>
 
-<p>To declare that your Activity handles a configuration change, edit the appropriate <a
-href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity&gt;}</a> element
-in your manifest file to include the <a
+<p>To declare that your activity handles a configuration change, edit the appropriate <a
+href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity&gt;}</a> element in
+your manifest file to include the <a
 href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
-android:configChanges}</a> attribute with a string value that represents the configuration that you
-want to handle. Possible values are listed in the documentation for
-the <a href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
-android:configChanges}</a> attribute (the most commonly used values are {@code orientation} to
-handle when the screen orientation changes and {@code keyboardHidden} to handle when the
-keyboard availability changes).  You can declare multiple configuration values in the attribute
-by separating them with a pipe character ("|").</p>
+android:configChanges}</a> attribute with a value that represents the configuration you want to
+handle. Possible values are listed in the documentation for the <a
+href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
+android:configChanges}</a> attribute (the most commonly used values are {@code "orientation"} to
+prevent restarts when the screen orientation changes and {@code "keyboardHidden"} to prevent
+restarts when the keyboard availability changes).  You can declare multiple configuration values in
+the attribute by separating them with a pipe {@code |} character.</p>
 
-<p>For example, the following manifest snippet declares an Activity that handles both the
+<p>For example, the following manifest code declares an activity that handles both the
 screen orientation change and keyboard availability change:</p>
 
 <pre>
@@ -176,20 +173,32 @@
           android:label="@string/app_name">
 </pre>
 
-<p>Now when one of these configurations change, {@code MyActivity} is not restarted.
-Instead, the Activity receives a call to {@link
+<p>Now, when one of these configurations change, {@code MyActivity} does not restart.
+Instead, the {@code MyActivity} receives a call to {@link
 android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}. This method
 is passed a {@link android.content.res.Configuration} object that specifies
 the new device configuration. By reading fields in the {@link android.content.res.Configuration},
 you can determine the new configuration and make appropriate changes by updating
 the resources used in your interface. At the
-time this method is called, your Activity's {@link android.content.res.Resources} object is updated
+time this method is called, your activity's {@link android.content.res.Resources} object is updated
 to return resources based on the new configuration, so you can easily
-reset elements of your UI without the system restarting your Activity.</p>
+reset elements of your UI without the system restarting your activity.</p>
+
+<p class="caution"><strong>Caution:</strong> Beginning with Android 3.2 (API level 13), <strong>the
+"screen size" also changes</strong> when the device switches between portrait and landscape
+orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing
+for API level 13 or higher (as declared by the <a
+href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> and <a
+href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a>
+attributes), you must include the {@code "screenSize"} value in addition to the {@code
+"orientation"} value. That is, you must decalare {@code
+android:configChanges="orientation|screenSize"}. However, if your application targets API level
+12 or lower, then your activity always handles this configuration change itself (this configuration
+change does not restart your activity, even when running on an Android 3.2 or higher device).</p>
 
 <p>For example, the following {@link
 android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()} implementation
-checks the availability of a hardware keyboard and the current device orientation:</p>
+checks the current device orientation:</p>
 
 <pre>
 &#64;Override
@@ -202,12 +211,6 @@
     } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
         Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
     }
-    // Checks whether a hardware keyboard is available
-    if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
-        Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
-    } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
-        Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
-    }
 }
 </pre>
 
@@ -216,7 +219,8 @@
 the configuration has changed and can simply re-assign all your resources that provide alternatives
 to the configuration that you're handling. For example, because the {@link
 android.content.res.Resources} object is now updated, you can reset
-any {@link android.widget.ImageView}s with {@link android.widget.ImageView#setImageResource(int)}
+any {@link android.widget.ImageView}s with {@link android.widget.ImageView#setImageResource(int)
+setImageResource()}
 and the appropriate resource for the new configuration is used (as described in <a
 href="providing-resources.html#AlternateResources">Providing Resources</a>).</p>
 
@@ -226,9 +230,9 @@
 to use with each field, refer to the appropriate field in the {@link
 android.content.res.Configuration} reference.</p>
 
-<p class="note"><strong>Remember:</strong> When you declare your Activity to handle a configuration
+<p class="note"><strong>Remember:</strong> When you declare your activity to handle a configuration
 change, you are responsible for resetting any elements for which you provide alternatives. If you
-declare your Activity to handle the orientation change and have images that should change
+declare your activity to handle the orientation change and have images that should change
 between landscape and portrait, you must re-assign each resource to each element during {@link
 android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}.</p>
 
@@ -236,13 +240,14 @@
 changes, you can instead <em>not</em> implement {@link
 android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}. In
 which case, all of the resources used before the configuration change are still used
-and you've only avoided the restart of your Activity. However, your application should always be
-able to shutdown and restart with its previous state intact. Not only because
-there are other configuration changes that you cannot prevent from restarting your application but
-also in order to handle events such as when the user receives an incoming phone call and then
-returns to your application.</p>
+and you've only avoided the restart of your activity. However, your application should always be
+able to shutdown and restart with its previous state intact, so you should not consider this
+technique an escape from retaining your state during normal activity lifecycle. Not only because
+there are other configuration changes that you cannot prevent from restarting your application, but
+also because you should handle events such as when the user leaves your application and it gets
+destroyed before the user returns to it.</p>
 
-<p>For more about which configuration changes you can handle in your Activity, see the <a
+<p>For more about which configuration changes you can handle in your activity, see the <a
 href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
 android:configChanges}</a> documentation and the {@link android.content.res.Configuration}
 class.</p>
diff --git a/docs/html/images/nfc_tag_dispatch.png b/docs/html/images/nfc_tag_dispatch.png
new file mode 100644
index 0000000..70ed711
--- /dev/null
+++ b/docs/html/images/nfc_tag_dispatch.png
Binary files differ
diff --git a/docs/html/index.jd b/docs/html/index.jd
index a8b61bf..d412993 100644
--- a/docs/html/index.jd
+++ b/docs/html/index.jd
@@ -129,15 +129,14 @@
     'sdk': {
       'layout':"imgLeft",
       'icon':"sdk-small.png",
-      'name':"Android 3.2",
-      'img':"honeycomb-android.png",
-      'title':"Android 3.2 is here!",
-      'desc': "<p>Android 3.2 is a minor feature update that includes new APIs that allow you to "
-+ "better target your layouts for specific screen sizes and other miscellaneous new APIs.</p>"
+      'name':"Android 4.0",
+      'img':"ics-android.png",
+      'title':"Ice Cream Sandwich!",
+      'desc': "<br/><br/><br/><p>Oh my goodness, that looks tasty!</p>"
+/*
 + "<p>For more information about all the changes in Android 3.2, read the "
 + "<a href='{@docRoot}sdk/android-3.2.html'>version notes</a> and <a "
 + "href='{@docRoot}sdk/api_diff/13/changes.html'>diff report</a>.</p>"
-/*
 + "<p>If you have an existing SDK, add Android 3.0 as an "
 + "<a href='{@docRoot}sdk/adding-components.html'>SDK "
 + "component</a>. If you're new to Android, install the "
diff --git a/docs/html/offline.jd b/docs/html/offline.jd
index 1064a99..5f8e37ce 100644
--- a/docs/html/offline.jd
+++ b/docs/html/offline.jd
@@ -29,7 +29,7 @@
 especially <a href="{@docRoot}resources/samples/ApiDemos/index.html">API Demos</a></li>
     <li>Read the <a href="{@docRoot}guide/topics/fundamentals/index.html">Application
 Fundamentals</a></li>
-    <li>Read the <a href="{@docRoot}guide/developing/index.html">Overview</a> for using the SDK
+    <li>Read the <a href="{@docRoot}guide/developing/index.html">Introduction</a> for using the SDK
 tools</li>
   </ul>
 </div>
@@ -44,9 +44,6 @@
 
 <p>There's no additional setup.</p>
 
-<p>New Android platforms are saved in the <code>&lt;sdk>/platforms/</code> directory of
-your existing SDK and new add-ons are saved in the <code>&lt;sdk>/add-ons/</code> directory.</p>
-
 
 <div class="note">
 <p><strong>Note:</strong> You are currently viewing the offline version of the Android developer
diff --git a/docs/html/resources/resources-data.js b/docs/html/resources/resources-data.js
index 3e673a5..310310e 100644
--- a/docs/html/resources/resources-data.js
+++ b/docs/html/resources/resources-data.js
@@ -419,16 +419,16 @@
   },
   {
     tags: ['sample', 'new'],
-    path: 'samples/AndroidBeam/index.html',
+    path: 'samples/AndroidBeamDemo/index.html',
     title: {
-      en: 'Android Beam'
+      en: 'Android Beam Demo'
     },
     description: {
       en: 'An example of how to use the Android Beam feature to send messages between two Android-powered devices (API level 14 or later) that support NFC.'
     }
   },
   {
-    tags: ['sample', 'layout', 'ui'],
+    tags: ['sample', 'layout', 'ui', 'updated'],
     path: 'samples/ApiDemos/index.html',
     title: {
       en: 'API Demos'
@@ -608,7 +608,7 @@
     }
   },
   {
-    tags: ['sample', 'accountsync'],
+    tags: ['sample', 'accountsync', 'updated'],
     path: 'samples/SampleSyncAdapter/index.html',
     title: {
       en: 'SampleSyncAdapter'
diff --git a/docs/html/resources/samples/images/hcgallery-phone1.png b/docs/html/resources/samples/images/hcgallery-phone1.png
new file mode 100644
index 0000000..9f0c280
--- /dev/null
+++ b/docs/html/resources/samples/images/hcgallery-phone1.png
Binary files differ
diff --git a/docs/html/resources/samples/images/hcgallery-phone2.png b/docs/html/resources/samples/images/hcgallery-phone2.png
new file mode 100644
index 0000000..b049a65
--- /dev/null
+++ b/docs/html/resources/samples/images/hcgallery-phone2.png
Binary files differ
diff --git a/docs/html/sdk/android-4.0.jd b/docs/html/sdk/android-4.0.jd
index 8f7ac55..9a9f02a 100644
--- a/docs/html/sdk/android-4.0.jd
+++ b/docs/html/sdk/android-4.0.jd
@@ -10,6 +10,7 @@
 <ol>
   <li><a href="#relnotes">Revisions</a></li>
   <li><a href="#api">API Overview</a></li>
+  <li><a href="#Honeycomb">Previous APIs</a></li>
   <li><a href="#api-diff">API Differences Report</a></li>
   <li><a href="#api-level">API Level</a></li>
   <li><a href="#apps">Built-in Applications</a></li>
@@ -45,14 +46,14 @@
 Components</a>. If you are new to Android, <a
 href="{@docRoot}sdk/index.html">download the SDK Starter Package</a> first.</p>
 
-<p>For a high-level introduction to the new user and developer features in Android 4.0, see the
-<a href="http://developer.android.com/sdk/android-4.0-highlights.html">Platform Highlights</a>.</p>
-
 <p class="note"><strong>Reminder:</strong> If you've already published an
 Android application, please test your application on Android {@sdkPlatformVersion} as
 soon as possible to be sure your application provides the best
 experience possible on the latest Android-powered devices.</p>
 
+<p>For a high-level introduction to the new user and developer features in Android 4.0, see the
+<a href="http://developer.android.com/sdk/android-4.0-highlights.html">Platform Highlights</a>.</p>
+
 
 <h2 id="relnotes">Revisions</h2>
 
@@ -92,21 +93,21 @@
 
   <div class="toggle-content-toggleme" style="padding-left:2em;">
     <ol class="toc" style="margin-left:-1em">
-      <li><a href="#Contacts">Contacts</a></li>
-      <li><a href="#Calendar">Calendar</a></li>
+      <li><a href="#Contacts">Contact Provider</a></li>
+      <li><a href="#Calendar">Calendar Provider</a></li>
+      <li><a href="#Voicemail">Voicemail Provider</a></li>
       <li><a href="#Camera">Camera</a></li>
       <li><a href="#Multimedia">Multimedia</a></li>
       <li><a href="#Bluetooth">Bluetooth</a></li>
       <li><a href="#AndroidBeam">Android Beam (NDEF Push with NFC)</a></li>
-      <li><a href="#P2pWiFi">Peer-to-peer Wi-Fi</a></li>
-      <li><a href="#NetworkData">Network Data</a></li>
-      <li><a href="#Sensors">Device Sensors</a></li>
-      <li><a href="#Renderscript">Renderscript</a></li>
+      <li><a href="#WiFiDirect">Wi-Fi Direct</a></li>
+      <li><a href="#NetworkUsage">Network Usage</a></li>
+      <li><a href="#RenderScript">RenderScript</a></li>
       <li><a href="#A11y">Accessibility</a></li>
       <li><a href="#Enterprise">Enterprise</a></li>
-      <li><a href="#Voicemail">Voicemail</a></li>
-      <li><a href="#SpellChecker">Spell Checker Services</a></li>
+      <li><a href="#Sensors">Device Sensors</a></li>
       <li><a href="#TTS">Text-to-speech Engines</a></li>
+      <li><a href="#SpellChecker">Spell Checker Services</a></li>
       <li><a href="#ActionBar">Action Bar</a></li>
       <li><a href="#UI">User Interface and Views</a></li>
       <li><a href="#Properties">Properties</a></li>
@@ -123,86 +124,95 @@
 
 
 
-<h3 id="Contacts">Contacts</h3>
+<h3 id="Contacts">Contact Provider</h3>
 
-<p>The Contact APIs that are defined by the {@link android.provider.ContactsContract} provider have
-been extended to support new features such as a personal profile for the device owner, large contact
-photos, and the ability for users to invite individual contacts to social networks that are
-installed on the device.</p>
+<p>The contact APIs that are defined by the {@link android.provider.ContactsContract} provider have
+been extended to support new features such as a personal profile for the device owner, high
+resolution contact photos, and the ability for users to invite individual contacts to social
+networks that are installed on the device.</p>
 
 
 <h4>User Profile</h4>
 
 <p>Android now includes a personal profile that represents the device owner, as defined by the
-{@link
-android.provider.ContactsContract.Profile} table.  Social apps that maintain a user identity     can
-contribute to the user's profile data by creating a new {@link
+{@link android.provider.ContactsContract.Profile} table.  Social apps that maintain a user identity 
+can contribute to the user's profile data by creating a new {@link
 android.provider.ContactsContract.RawContacts} entry within the {@link
 android.provider.ContactsContract.Profile}. That is, raw contacts that represent the device user do
 not belong in the traditional raw contacts table defined by the {@link
 android.provider.ContactsContract.RawContacts} Uri; instead, you must add a profile raw contact in
 the table at {@link android.provider.ContactsContract.Profile#CONTENT_RAW_CONTACTS_URI}. Raw
-contacts in this table are then aggregated into the single user-visible profile information.</p>
+contacts in this table are then aggregated into the single user-visible profile labeled "Me".</p>
 
 <p>Adding a new raw contact for the profile requires the {@link
 android.Manifest.permission#WRITE_PROFILE} permission. Likewise, in order to read from the profile
 table, you must request the {@link android.Manifest.permission#READ_PROFILE} permission. However,
-reading the user profile should not be required by most apps, even when contributing data to the
-profile. Reading the user profile is a sensitive permission and users will be very skeptical of apps
-that request reading their profile information.</p>
+most apps should need to read the user profile, even when contributing data to the
+profile. Reading the user profile is a sensitive permission and you should expect users to be
+skeptical of apps that request it.</p>
+
 
 <h4>Large photos</h4>
 
 <p>Android now supports high resolution photos for contacts. Now, when you push a photo into a
-contact
-record, the system processes it into both a 96x96 thumbnail (as it has previously) and a 256x256
-"display photo" stored in a new file-based photo store (the exact dimensions that the system chooses
-may vary in the future). You can add a large photo to a contact by putting a large photo in the
-usual {@link android.provider.ContactsContract.CommonDataKinds.Photo#PHOTO} column of a data row,
-which the system will then process into the appropriate thumbnail and display photo records.</p>
+contact record, the system processes it into both a 96x96 thumbnail (as it has previously) and a
+256x256 "display photo" that's stored in a new file-based photo store (the exact dimensions that the
+system chooses may vary in the future). You can add a large photo to a contact by putting a large
+photo in the usual {@link android.provider.ContactsContract.CommonDataKinds.Photo#PHOTO} column of a
+data row, which the system will then process into the appropriate thumbnail and display photo
+records.</p>
+
 
 <h4>Invite Intent</h4>
 
-<p>The {@link android.provider.ContactsContract.Intents#INVITE_CONTACT} intent action allows you to
-invoke an action that indicates the user wants to add a contact to a social network that understand
-this intent and use it to invite the contact specified in the contact to that social network.</p> 
+<p>The {@link android.provider.ContactsContract.Intents#INVITE_CONTACT} intent action allows an app
+to invoke an action that indicates the user wants to add a contact to a social network. The app
+receiving the app uses it to invite the specified contact to that
+social network. Most apps will be on the receiving-end of this operation. For example, the
+built-in People app invokes the invite intent when the user selects "Add connection" for a specific
+social app that's listed in a person's contact details.</p> 
 
-<p>Apps that use a sync adapter to provide information about contacts can register with the system
-to
-receive the invite intent when there’s an opportunity for the user to “invite” a contact to the
-app’s social network (such as from a contact card in the People app). To receive the invite intent,
-you simply need to add the {@code inviteContactActivity} attribute to your app’s XML sync
-configuration file, providing a fully-qualified name of the activity that the system should start
-when the user wants to “invite” a contact in your social network. The activity that starts can then
-retrieve the URI for the contact in question from the intent’s data and perform the necessary work
-to
-invite that contact to the network or add the person to the user’s connections.</p>
+<p>To make your app visible as in the "Add connection" list, your app must provide a sync adapter to
+sync contact information from your social network. You must then indicate to the system that your
+app responds to the {@link android.provider.ContactsContract.Intents#INVITE_CONTACT} intent by
+adding the {@code inviteContactActivity} attribute to your app’s sync configuration file, with a
+fully-qualified name of the activity that the system should start when sending the invite intent.
+The activity that starts can then retrieve the URI for the contact in question from the intent’s
+data and perform the necessary work to invite that contact to the network or add the person to the
+user’s connections.</p>
+
+<p>See the <a href="{@docRoot}resources/samples/SampleSyncAdapter/index.html">Sample Sync
+Adapter</a> app for an example (specifically, see the <a
+href="{@docRoot}resources/samples/SampleSyncAdapter/res/xml-v14/contacts.html">contacts.xml</a>
+file).</p>
+
 
 <h4>Contact Usage Feedback</h4>
 
 <p>The new {@link android.provider.ContactsContract.DataUsageFeedback} APIs allow you to  help track
 how often the user uses particular methods of contacting people, such as how often the user uses
 each phone number or e-mail address. This information helps improve the ranking for each contact
-method associated with each person and provide such contact methods as suggestions.</p>
+method associated with each person and provide better suggestions for contacting each person.</p>
 
 
 
 
 
-<h3 id="Calendar">Calendar</h3>
+<h3 id="Calendar">Calendar Provider</h3>
 
-<p>The new calendar API allows you to access and modify the user’s calendars and events. The
-calendar
-APIs are provided with the {@link android.provider.CalendarContract} provider. Using the calendar
-provider, you can:</p>
-<ul>
-<li>Read, write, and modify calendars.</li>
-<li>Add and modify events, attendees, reminders, and alarms.</li>
-</ul>
+<p>The new calendar APIs allow you to read, add, modify and delete calendars, events, attendees,
+reminders and alerts, which are stored in the Calendar Provider.</p>
 
-<p>{@link android.provider.CalendarContract} defines the data model of calendar and event-related
-information. All of the user’s calendar data is stored in a number of tables defined by subclasses
-of {@link android.provider.CalendarContract}:</p>
+<p>A variety of apps and widgets can use these APIs to read and modify calendar events. However,
+some of the most compelling use cases are sync adapters that synchronize the user's calendar from
+other calendar services with the Calendar Provider, in order to offer a unified location for all the
+user's events. Google Calendar events, for example, are synchronized with the Calendar Provider by
+the Google Calendar Sync Adapter, allowing these events to be viewed with Android's built-in
+Calendar app.</p>
+
+<p>The data model for calendars and event-related information in the Calendar Provider is
+defined by {@link android.provider.CalendarContract}. All the user’s calendar data is stored in a
+number of tables defined by various subclasses of {@link android.provider.CalendarContract}:</p>
 
 <ul>
 <li>The {@link android.provider.CalendarContract.Calendars} table holds the calendar-specific
@@ -210,11 +220,10 @@
 color, sync information, and so on.</li>
 
 <li>The {@link android.provider.CalendarContract.Events} table holds event-specific information.
-Each
-row in this table has the information for a single event. It contains information such as event
-title, location, start time, end time, and so on. The event can occur one-time or can recur multiple
-times. Attendees, reminders, and extended properties are stored in separate tables and reference the
-event’s _ID to link them with the event.</li>
+Each row in this table contains the information for a single event, such as the
+event title, location, start time, end time, and so on. The event can occur one time or recur
+multiple times. Attendees, reminders, and extended properties are stored in separate tables and
+use the event’s {@code _ID} to link them with the event.</li>
 
 <li>The {@link android.provider.CalendarContract.Instances} table holds the start and end time for
 occurrences of an event. Each row in this table represents a single occurrence. For one-time events
@@ -223,47 +232,93 @@
 
 <li>The {@link android.provider.CalendarContract.Attendees} table holds the event attendee or guest
 information. Each row represents a single guest of an event. It specifies the type of guest the
-person is and the person’s attendance response for the event.</li>
+person is and the person’s response for the event.</li>
 
 <li>The {@link android.provider.CalendarContract.Reminders} table holds the alert/notification data.
 Each row represents a single alert for an event. An event can have multiple reminders. The number of
-reminders per event is specified in MAX_REMINDERS, which is set by the Sync Adapter that owns the
-given calendar. Reminders are specified in minutes before the event and have a type.</li>
+reminders per event is specified in {@code MAX_REMINDERS}, which is set by the sync adapter that
+owns the given calendar. Reminders are specified in number-of-minutes before the event is
+scheduled and specify an alarm method such as to use an alert, email, or SMS to remind
+the user.</li>
 
 <li>The {@link android.provider.CalendarContract.ExtendedProperties} table hold opaque data fields
-used
-by the sync adapter. The provider takes no action with items in this table except to delete them
-when their related events are deleted.</li>
+used by the sync adapter. The provider takes no action with items in this table except to delete
+them when their related events are deleted.</li>
 </ul>
 
-<p>To access a user’s calendar data with the calendar provider, your application must request
-permission from the user by declaring <uses-permission
-android:name="android.permission.READ_CALENDAR" /> (for read access) and <uses-permission
-android:name="android.permission.WRITE_CALENDAR" /> (for write access) in their manifest files.</p>
+<p>To access a user’s calendar data with the Calendar Provider, your application must request 
+the {@link android.Manifest.permission#READ_CALENDAR} permission (for read access) and
+{@link android.Manifest.permission#WRITE_CALENDAR} (for write access).</p>
 
-<p>However, if all you want to do is add an event to the user’s calendar, you can instead use an
-INSERT
-{@link android.content.Intent} to start an activity in the Calendar app that creates new events.
-Using the intent does not require the WRITE_CALENDAR permission and you can specify the {@link
-android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME} and {@link
-android.provider.CalendarContract#EXTRA_EVENT_END_TIME} extra fields to pre-populate the form with
-the time of the event. The values for these times must be in milliseconds from the epoch. You must
-also specify {@code “vnd.android.cursor.item/event”} as the intent type.</p>
 
+<h4>Event intent</h4>
+
+<p>If all you want to do is add an event to the user’s calendar, you can use an
+{@link android.content.Intent#ACTION_INSERT} intent with a {@code "vnd.android.cursor.item/event"}
+MIME type to start an activity in the Calendar app that creates new events. Using the intent does
+not require any permission and you can specify event details with the following extras:</p>
+
+<ul>
+  <li>{@link android.provider.CalendarContract.EventsColumns#TITLE Events.TITLE}: Name for the
+event</li>
+  <li>{@link
+android.provider.CalendarContract#EXTRA_EVENT_BEGIN_TIME CalendarContract.EXTRA_EVENT_BEGIN_TIME}:
+Event begin time in milliseconds from the
+epoch</li>
+  <li>{@link
+android.provider.CalendarContract#EXTRA_EVENT_END_TIME CalendarContract.EXTRA_EVENT_END_TIME}: Event
+end time in milliseconds from the epoch</li>
+  <li>{@link android.provider.CalendarContract.EventsColumns#EVENT_LOCATION Events.EVENT_LOCATION}:
+Location of the event</li>
+  <li>{@link android.provider.CalendarContract.EventsColumns#DESCRIPTION Events.DESCRIPTION}: Event
+description</li>
+  <li>{@link android.content.Intent#EXTRA_EMAIL Intent.EXTRA_EMAIL}: Email addresses of those to
+invite</li>
+  <li>{@link android.provider.CalendarContract.EventsColumns#RRULE Events.RRULE}: The recurrence
+rule for the event</li>
+  <li>{@link android.provider.CalendarContract.EventsColumns#ACCESS_LEVEL Events.ACCESS_LEVEL}:
+Whether the event is private or public</li>
+  <li>{@link android.provider.CalendarContract.EventsColumns#AVAILABILITY Events.AVAILABILITY}:
+Whether the time period of this event allows for other events to be scheduled at the same time</li>
+</ul>
+
+
+
+
+<h3 id="Voicemail">Voicemail Provider</h3>
+
+<p>The new voicemail APIs allows applications to add voicemails to a content provider on the device.
+Because the APIs currently do not allow third party apps to read all the voicemails from the system,
+the only third-party apps that should use the voicemail APIs are those that have voicemail to
+deliver to the user. For instance, it’s possible that a user has multiple voicemail sources, such as
+one provided by the phone’s service provider and others from VoIP or other alternative voice
+services. These apps can use the APIs to add their voicemails to the system for quick playback. The
+built-in Phone application presents all voicemails from the Voicemail Provider with a single list.
+Although the system’s Phone application is the only application that can read all the voicemails,
+each application that provides voicemails can read those that it has added to the system (but cannot
+read voicemails from other services).</p>
+
+<p>The {@link android.provider.VoicemailContract} class defines the content provider for the
+voicemail APIs. The subclasses {@link android.provider.VoicemailContract.Voicemails} and {@link
+android.provider.VoicemailContract.Status} provide tables in which the Voicemail Providers can
+insert voicemail data for storage on the device. For an example of a voicemail provider app, see the
+<a href="{@docRoot}resources/samples/VoicemailProviderDemo/index.html">Voicemail Provider
+Demo</a>.</p>
 
 
 
 
 <h3 id="Camera">Camera</h3>
 
-<p>The {@link android.hardware.Camera} APIs now support face detection and control for metering and
-focus areas.</p>
+<p>The {@link android.hardware.Camera} class now includes APIs for detecting faces and controlling
+focus and metering areas.</p>
 
-<h4>Face Detection</h4>
 
-<p>Camera apps can now enhance their abilities with Android’s face detection software, which not
-only
-detects the face of a subject, but also specific facial features, such as the eyes and mouth. </p>
+<h4>Face detection</h4>
+
+<p>Camera apps can now enhance their abilities with Android’s face detection APIs, which not
+only detect the face of a subject, but also specific facial features, such as the eyes and mouth.
+</p>
 
 <p>To detect faces in your camera application, you must register a {@link
 android.hardware.Camera.FaceDetectionListener} by calling {@link
@@ -271,41 +326,44 @@
 your camera surface and start  detecting faces by calling {@link
 android.hardware.Camera#startFaceDetection}.</p>
 
-<p>When the system detects a face, it calls the {@link
+<p>When the system detects one or more faces in the camera scene, it calls the {@link
 android.hardware.Camera.FaceDetectionListener#onFaceDetection onFaceDetection()} callback in your
 implementation of {@link android.hardware.Camera.FaceDetectionListener}, including an array of
 {@link android.hardware.Camera.Face} objects.</p>
 
 <p>An instance of the {@link android.hardware.Camera.Face} class provides various information about
-the
-face detected by the camera, including:</p>
+the face detected, including:</p>
 <ul>
 <li>A {@link android.graphics.Rect} that specifies the bounds of the face, relative to the camera's
 current field of view</li>
-<li>An integer betwen 0 and 100 that indicates how confident the system is that the object is a
-human
-face</li>
+<li>An integer betwen 1 and 100 that indicates how confident the system is that the object is a
+human face</li>
 <li>A unique ID so you can track multiple faces</li>
 <li>Several {@link android.graphics.Point} objects that indicate where the eyes and mouth are
 located</li>
 </ul>
 
-  
-<h4>Focus and Metering Areas</h4>
+<p class="note"><strong>Note:</strong> Face detection may not be supported on some
+devices, so you should check by calling {@link
+android.hardware.Camera.Parameters#getMaxNumDetectedFaces()} and ensure the return
+value is greater than zero. Also, some devices may not support identification of eyes and mouth,
+in which case, those fields in the {@link android.hardware.Camera.Face} object will be null.</p>
 
-<p>Camera apps can now control the areas that the camera uses for focus and when metering white
+  
+<h4>Focus and metering areas</h4>
+
+<p>Camera apps can now control the areas that the camera uses for focus and for metering white
 balance
-and auto-exposure (when supported by the hardware). Both features use the new {@link
-android.hardware.Camera.Area} class to specify the region of the camera’s current view that should
-be focused or metered. An instance of the {@link android.hardware.Camera.Area} class defines the
-bounds of the area with a {@link android.graphics.Rect} and the weight of the
-area&mdash;representing the level of importance of that area, relative to other areas in
-consideration&mdash;with an integer.</p>
+and auto-exposure. Both features use the new {@link android.hardware.Camera.Area} class to specify
+the region of the camera’s current view that should be focused or metered. An instance of the {@link
+android.hardware.Camera.Area} class defines the bounds of the area with a {@link
+android.graphics.Rect} and the area's weight&mdash;representing the level of importance of that
+area, relative to other areas in consideration&mdash;with an integer.</p>
 
 <p>Before setting either a focus area or metering area, you should first call {@link
 android.hardware.Camera.Parameters#getMaxNumFocusAreas} or {@link
 android.hardware.Camera.Parameters#getMaxNumMeteringAreas}, respectively. If these return zero, then
-the device does not support the respective feature. </p>
+the device does not support the corresponding feature.</p>
 
 <p>To specify the focus or metering areas to use, simply call {@link
 android.hardware.Camera.Parameters#setFocusAreas setFocusAreas()} or {@link
@@ -313,63 +371,87 @@
 java.util.List} of {@link android.hardware.Camera.Area} objects that indicate the areas to consider
 for focus or metering. For example, you might implement a feature that allows the user to set the
 focus area by touching an area of the preview, which you then translate to an {@link
-android.hardware.Camera.Area} object and set the focus to that spot. The focus or exposure in that
-area will continually update as the scene in the area changes.</p>
+android.hardware.Camera.Area} object and request that the camera focus on that area of the scene.
+The focus or exposure in that area will continually update as the scene in the area changes.</p>
 
 
-<h4>Other Camera Features</h4>
-<ul>
-<li>Capture photos during video recording
-While recording video, you can now call {@link android.hardware.Camera#takePicture takePicture()} to
-save a photo without interrupting the video session. Before doing so, you should call {@link
-android.hardware.Camera.Parameters#isVideoSnapshotSupported} to be sure the hardware supports
-it.</li>
+<h4>Continuous auto focus for photos</h4>
 
-<li>Lock auto exposure and white balance with {@link
+<p>You can now enable continuous auto focusing (CAF) when taking photos. To enable CAF in your
+camera app, pass {@link android.hardware.Camera.Parameters#FOCUS_MODE_CONTINUOUS_PICTURE}
+to {@link android.hardware.Camera.Parameters#setFocusMode setFocusMode()}. When ready to capture
+a photo, call {@link android.hardware.Camera#autoFocus autoFocus()}. Your {@link
+android.hardware.Camera.AutoFocusCallback} immediately receives a callback to indicate whether
+focus was acheived. To resume CAF after receiving the callback, you must call {@link
+android.hardware.Camera#cancelAutoFocus()}.</p>
+
+<p class="note"><strong>Note:</strong> Continuous auto focus is also supported when capturing
+video, using {@link android.hardware.Camera.Parameters#FOCUS_MODE_CONTINUOUS_VIDEO}, which was
+added in API level 9.</p>
+
+
+<h4>Other camera features</h4>
+
+<ul>  
+<li>While recording video, you can now call {@link android.hardware.Camera#takePicture
+takePicture()} to save a photo without interrupting the video session. Before doing so, you should
+call {@link android.hardware.Camera.Parameters#isVideoSnapshotSupported} to be sure the hardware
+supports it.</li>
+
+<li>You can now lock auto exposure and white balance with {@link
 android.hardware.Camera.Parameters#setAutoExposureLock setAutoExposureLock()} and {@link
-android.hardware.Camera.Parameters#setAutoWhiteBalanceLock setAutoWhiteBalanceLock()}, to prevent
+android.hardware.Camera.Parameters#setAutoWhiteBalanceLock setAutoWhiteBalanceLock()} to prevent
 these properties from changing.</li>
+
+<li>You can now call {@link android.hardware.Camera#setDisplayOrientation
+setDisplayOrientation()} while the camera preview is running. Previously, you could call this
+only before beginning the preview, but you can now change the orientation at any time.</li>
 </ul>
 
-<h4>Camera Broadcast Intents</h4>
+
+<h4>Camera broadcast intents</h4>
 
 <ul>
-<li>{@link android.hardware.Camera#ACTION_NEW_PICTURE Camera.ACTION_NEW_PICTURE} 
-This indicates that the user has captured a new photo. The built-in camera app invokes this
+<li>{@link android.hardware.Camera#ACTION_NEW_PICTURE Camera.ACTION_NEW_PICTURE}:
+This indicates that the user has captured a new photo. The built-in Camera app invokes this
 broadcast after a photo is captured and third-party camera apps should also broadcast this intent
 after capturing a photo.</li>
-<li>{@link android.hardware.Camera#ACTION_NEW_VIDEO Camera.ACTION_NEW_VIDEO}
-This indicates that the user has captured a new video. The built-in camera app invokes this
+<li>{@link android.hardware.Camera#ACTION_NEW_VIDEO Camera.ACTION_NEW_VIDEO}:
+This indicates that the user has captured a new video. The built-in Camera app invokes this
 broadcast after a video is recorded and third-party camera apps should also broadcast this intent
 after capturing a video.</li>
 </ul>
 
-  
-  
 
-  
+
+
+
 <h3 id="Multimedia">Multimedia</h3>
 
 <p>Android 4.0 adds several new APIs for applications that interact with media such as photos,
-videos,
-and music.</p>
+videos, and music.</p>
 
 
-<h4>Media Player</h4>
+<h4>Media player</h4>
 
 <ul>
-<li>Streaming online media from {@link android.media.MediaPlayer} now requires {@link
+<li>Streaming online media from {@link android.media.MediaPlayer} now requires the {@link
 android.Manifest.permission#INTERNET} permission. If you use {@link android.media.MediaPlayer} to
-play content from the internet, be sure to add the {@link android.Manifest.permission#INTERNET}
-permission or else your media playback will not work beginning with Android 4.0.</li>
+play content from the Internet, be sure to add the {@link android.Manifest.permission#INTERNET}
+permission to your manifest or else your media playback will not work beginning with Android
+4.0.</li>
+
 <li>{@link android.media.MediaPlayer#setSurface(Surface) setSurface()} allows you define a {@link
 android.view.Surface} to behave as the video sink.</li>
+
 <li>{@link android.media.MediaPlayer#setDataSource(Context,Uri,Map) setDataSource()} allows you to
 send additional HTTP headers with your request, which can be useful for HTTP(S) live streaming</li>
+
 <li>HTTP(S) live streaming now respects HTTP cookies across requests</li>
 </ul>
 
-<h4>Media Type Support</h4>
+
+<h4>Media types</h4>
 
 <p>Android 4.0 adds support for:</p>
 <ul>
@@ -378,20 +460,21 @@
 <li>WEBP images</li>
 <li>Matroska video</li>
 </ul>
-<p>For more info, see <a href=”{@docRoot}guide/appendix/media-formats.html”>Supported Media
+<p>For more info, see <a href="{@docRoot}guide/appendix/media-formats.html">Supported Media
 Formats</a>.</p>
 
 
-<h4>Remote Control Client</h4>
+
+<h4>Remote control client</h4>
 
 <p>The new {@link android.media.RemoteControlClient} allows media players to enable playback
-controls
-from remote control clients such as the device lock screen. Media players can also expose
+controls from remote control clients such as the device lock screen. Media players can also expose
 information about the media currently playing for display on the remote control, such as track
 information and album art.</p>
 
 <p>To enable remote control clients for your media player, instantiate a {@link
-android.media.RemoteControlClient} with a {@link android.app.PendingIntent} that broadcasts {@link
+android.media.RemoteControlClient} with its constructor, passing it a {@link
+android.app.PendingIntent} that broadcasts {@link
 android.content.Intent#ACTION_MEDIA_BUTTON}. The intent must also declare the explicit {@link
 android.content.BroadcastReceiver} component in your app that handles the {@link
 android.content.Intent#ACTION_MEDIA_BUTTON} event.</p>
@@ -418,22 +501,20 @@
 android.media.MediaMetadataRetriever}.</p>
 
 <p>For a sample implementation, see the <a
-href=”{@docRoot}resources/samples/RandomMusicPlayer/index.html”>Random Music Player</a>, which
-provides compatibility logic such that it enables the remote control client while continuing to
-support Android 2.1 devices.</p>
+href="{@docRoot}resources/samples/RandomMusicPlayer/index.html">Random Music Player</a>, which
+provides compatibility logic such that it enables the remote control client on Android 4.0
+devices while continuing to support devices back to Android 2.1.</p>
 
 
 <h4>Media Effects</h4>
 
 <p>A new media effects framework allows you to apply a variety of visual effects to images and
-videos.
-The system performs all effects processing on the GPU to obtain maximum performance. Applications in
-Android 4.0 such as Google Talk or the Gallery editor make use of the effects API to apply real-time
-effects to video and photos.</p>
+videos. For example, image effects allow you to easily fix red-eye, convert an image to grayscale,
+adjust brightness, adjust saturation, rotate an image, apply a fisheye effect, and much more. The
+system performs all effects processing on the GPU to obtain maximum performance.</p>
 
 <p>For maximum performance, effects are applied directly to OpenGL textures, so your application
-must
-have a valid OpenGL context before it can use the effects APIs. The textures to which you apply
+must have a valid OpenGL context before it can use the effects APIs. The textures to which you apply
 effects may be from bitmaps, videos or even the camera. However, there are certain restrictions that
 textures must meet:</p>
 <ol>
@@ -442,8 +523,7 @@
 </ol>
 
 <p>An {@link android.media.effect.Effect} object defines a single media effect that you can apply to
-an
-image frame. The basic workflow to create an {@link android.media.effect.Effect} is:</p>
+an image frame. The basic workflow to create an {@link android.media.effect.Effect} is:</p>
 
 <ol>
 <li>Call {@link android.media.effect.EffectContext#createWithCurrentGlContext
@@ -452,17 +532,15 @@
 android.media.effect.EffectContext#getFactory EffectContext.getFactory()}, which returns an instance
 of {@link android.media.effect.EffectFactory}.</li>
 <li>Call {@link android.media.effect.EffectFactory#createEffect createEffect()}, passing it an
-effect
-name from @link android.media.effect.EffectFactory}, such as {@link
+effect name from @link android.media.effect.EffectFactory}, such as {@link
 android.media.effect.EffectFactory#EFFECT_FISHEYE} or {@link
 android.media.effect.EffectFactory#EFFECT_VIGNETTE}.</li>
 </ol>
 
 <p>Not all devices support all effects, so you must first check if the desired effect is supported
-by
-calling {@link android.media.effect.EffectFactory#isEffectSupported isEffectSupported()}.</p>
+by calling {@link android.media.effect.EffectFactory#isEffectSupported isEffectSupported()}.</p>
 
-<p>You can adjust the effect’s parameters by calling {@link android.media.effect.Effect#setParameter
+<p>You can adjust an effect’s parameters by calling {@link android.media.effect.Effect#setParameter
 setParameter()} and passing a parameter name and parameter value. Each type of effect accepts
 different parameters, which are documented with the effect name. For example, {@link
 android.media.effect.EffectFactory#EFFECT_FISHEYE} has one parameter for the {@code scale} of the
@@ -475,7 +553,7 @@
 image (usually done by calling the {@link android.opengl.GLES20#glTexImage2D glTexImage2D()}
 function). You may provide multiple mipmap levels. If the output texture has not been bound to a
 texture image, it will be automatically bound by the effect as a {@link
-android.opengl.GLES20#GL_TEXTURE_2D}. It will contain one mipmap level (0), which will have the same
+android.opengl.GLES20#GL_TEXTURE_2D} and with one mipmap level (0), which will have the same
 size as the input.</p> 
 
 
@@ -496,7 +574,7 @@
 android.bluetooth.BluetoothProfile#HEALTH} profile type to establish a connection with the profile
 proxy object.</p>
 
-<p>Once you’ve acquired the Health profile proxy (the {@link android.bluetooth.BluetoothHealth}
+<p>Once you’ve acquired the Health Profile proxy (the {@link android.bluetooth.BluetoothHealth}
 object), connecting to and communicating with paired health devices involves the following new
 Bluetooth classes:</p>
 <ul>
@@ -510,15 +588,15 @@
 android.bluetooth.BluetoothHealth} APIs.</li>
 </ul>
 
-<p>For more information about using the Bluetooth Health profile, see the documentation for {@link
+<p>For more information about using the Bluetooth Health Profile, see the documentation for {@link
 android.bluetooth.BluetoothHealth}.</p>
 
 
+
 <h3 id="AndroidBeam">Android Beam (NDEF Push with NFC)</h3>
 
-<p>Android Beam allows you to send NDEF messages (an NFC standard for data stored on NFC tags) from
-one
-device to another (a process also known as “NDEF Push”). The data transfer is initiated when two
+<p>Android Beam is a new NFC feature that allows you to send NDEF messages from one device to
+another (a process also known as “NDEF Push"). The data transfer is initiated when two
 Android-powered devices that support Android Beam are in close proximity (about 4 cm), usually with
 their backs touching. The data inside the NDEF message can contain any data that you wish to share
 between devices. For example, the People app shares contacts, YouTube shares videos, and Browser
@@ -526,29 +604,30 @@
 
 <p>To transmit data between devices using Android Beam, you need to create an {@link
 android.nfc.NdefMessage} that contains the information you want to share while your activity is in
-the foreground. You must then pass the
-{@link android.nfc.NdefMessage} to the system in one of two ways:</p>
+the foreground. You must then pass the {@link android.nfc.NdefMessage} to the system in one of two
+ways:</p>
 
 <ul>
-<li>Define a single {@link android.nfc.NdefMessage} to use from the activity:
+<li>Define a single {@link android.nfc.NdefMessage} to push while in the activity:
 <p>Call {@link android.nfc.NfcAdapter#setNdefPushMessage setNdefPushMessage()} at any time to set
-the
-message you want to send. For instance, you might call this method and pass it your {@link
+the message you want to send. For instance, you might call this method and pass it your {@link
 android.nfc.NdefMessage} during your activity’s {@link android.app.Activity#onCreate onCreate()}
-method. Then, whenever Android Beam is activated with another device while your activity is in the
-foreground, the system sends that {@link android.nfc.NdefMessage} to the other device.</p></li>
+method. Then, whenever Android Beam is activated with another device while the activity is in the
+foreground, the system sends the {@link android.nfc.NdefMessage} to the other device.</p></li>
 
-<li>Define the {@link android.nfc.NdefMessage} depending on the current context:
-<p>Implement {@link android.nfc.NfcAdapter.CreateNdefMessageCallback}, in which the {@link
-android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()} callback
+<li>Define the {@link android.nfc.NdefMessage} to push at the time that Android Beam is initiated:
+<p>Implement {@link android.nfc.NfcAdapter.CreateNdefMessageCallback}, in which your
+implementation of the {@link
+android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()}
 method returns the {@link android.nfc.NdefMessage} you want to send. Then pass the {@link
-android.nfc.NfcAdapter.CreateNdefMessageCallback} to {@link
-android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()}. In this case, when
-Android Beam is activated with another device while your activity is in the foreground, the system
-calls {@link android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()}
-to retrieve the {@link android.nfc.NdefMessage} you want to send. This allows you to create a
-different {@link android.nfc.NdefMessage} for each occurrence, depending on the user context (such
-as which contact in the People app is currently visible).</p></li>
+android.nfc.NfcAdapter.CreateNdefMessageCallback} implementation to {@link
+android.nfc.NfcAdapter#setNdefPushMessageCallback setNdefPushMessageCallback()}.</p>
+<p>In this case, when Android Beam is activated with another device while your activity is in the
+foreground, the system calls {@link
+android.nfc.NfcAdapter.CreateNdefMessageCallback#createNdefMessage createNdefMessage()} to retrieve
+the {@link android.nfc.NdefMessage} you want to send. This allows you to define the {@link
+android.nfc.NdefMessage} to deliver only once Android Beam is initiated, in case the contents
+of the message might vary throughout the life of the activity.</p></li>
 </ul>
 
 <p>In case you want to run some specific code once the system has successfully delivered your NDEF
@@ -562,9 +641,9 @@
 tags. The system invokes an intent with the {@link android.nfc.NfcAdapter#ACTION_NDEF_DISCOVERED}
 action to start an activity, with either a URL or a MIME type set according to the first {@link
 android.nfc.NdefRecord} in the {@link android.nfc.NdefMessage}. For the activity you want to
-respond, you can set intent filters for the URLs or MIME types your app cares about. For more
+respond, you can declare intent filters for the URLs or MIME types your app cares about. For more
 information about Tag Dispatch see the <a
-href=”{@docRoot}guide/topics/nfc/index.html#dispatch”>NFC</a> developer guide.</p>
+href="{@docRoot}guide/topics/nfc/index.html#dispatch">NFC</a> developer guide.</p>
 
 <p>If you want your {@link android.nfc.NdefMessage} to carry a URI, you can now use the convenience
 method {@link android.nfc.NdefRecord#createUri createUri} to construct a new {@link
@@ -573,46 +652,51 @@
 should create an intent filter for your activity using the same URI scheme in order to receive the
 incoming NDEF message.</p>
 
-<p>You may also want to pass an “Android application record” with your {@link
-android.nfc.NdefMessage}
-in order to guarantee a specific application handles an NDEF message, regardless of whether other
-applications filter for the same intent. You can create an Android application record by calling
-{@link android.nfc.NdefRecord#createApplicationRecord createApplicationRecord()}, passing it the
-application’s package name. When the other device receives the NDEF message with this record, the
-system automatically starts the application matching the package name. If the target device does not
-currently have the application installed, the system uses the Android application record to launch
-Android Market and take the user to the application to install it.</p>
+<p>You should also pass an “Android application record" with your {@link android.nfc.NdefMessage} in
+order to guarantee that your application handles the incoming NDEF message, even if other
+applications filter for the same intent action. You can create an Android application record by
+calling {@link android.nfc.NdefRecord#createApplicationRecord createApplicationRecord()}, passing it
+your application’s package name. When the other device receives the NDEF message with the
+application record and multiple applications contain activities that handle the specified intent,
+the system always delivers the message to the activity in your application (based on the matching
+application record). If the target device does not currently have your application installed, the
+system uses the Android application record to launch Android Market and take the user to the
+application in order to install it.</p>
 
 <p>If your application doesn’t use NFC APIs to perform NDEF Push messaging, then Android provides a
 default behavior: When your application is in the foreground on one device and Android Beam is
 invoked with another Android-powered device, then the other device receives an NDEF message with an
 Android application record that identifies your application. If the receiving device has the
 application installed, the system launches it; if it’s not installed, Android Market opens and takes
-the user to your application so they can install it.</p>
+the user to your application in order to install it.</p>
+
+<p>For some example code, see the <a
+href="{@docRoot}resources/samples/AndroidBeamDemo/src/com/example/android/beam/Beam.html">Android
+Beam Demo</a> sample app.</p>
 
 
 
 
+<h3 id="WiFiDirect">Wi-Fi Direct</h3>
 
-<h3 id="P2pWiFi">Peer-to-peer Wi-Fi</h3>
-
-<p>Android now supports Wi-Fi Direct&trade; for peer-to-peer (P2P) connections between
-Android-powered
+<p>Android now supports Wi-Fi Direct for peer-to-peer (P2P) connections between Android-powered
 devices and other device types without a hotspot or Internet connection. The Android framework
 provides a set of Wi-Fi P2P APIs that allow you to discover and connect to other devices when each
-device supports Wi-Fi Direct&trade;, then communicate over a speedy connection across distances much
-longer than a Bluetooth connection.</p>
+device supports Wi-Fi Direct, then communicate over a speedy connection across distances much longer
+than a Bluetooth connection.</p>
 
 <p>A new package, {@link android.net.wifi.p2p}, contains all the APIs for performing peer-to-peer
 connections with Wi-Fi. The primary class you need to work with is {@link
-android.net.wifi.p2p.WifiP2pManager}, for which you can get an instance by calling {@link
+android.net.wifi.p2p.WifiP2pManager}, which you can acquire by calling {@link
 android.app.Activity#getSystemService getSystemService(WIFI_P2P_SERVICE)}. The {@link
-android.net.wifi.p2p.WifiP2pManager} provides methods that allow you to:</p>
+android.net.wifi.p2p.WifiP2pManager} includes APIs that allow you to:</p>
 <ul>
 <li>Initialize your application for P2P connections by calling {@link
 android.net.wifi.p2p.WifiP2pManager#initialize initialize()}</li>
+
 <li>Discover nearby devices by calling {@link android.net.wifi.p2p.WifiP2pManager#discoverPeers
 discoverPeers()}</li>
+
 <li>Start a P2P connection by calling {@link android.net.wifi.p2p.WifiP2pManager#connect
 connect()}</li>
 <li>And more</li>
@@ -622,18 +706,20 @@
 <ul>
 <li>The {@link android.net.wifi.p2p.WifiP2pManager.ActionListener} interface allows you to receive
 callbacks when an operation such as discovering peers or connecting to them succeeds or fails.</li>
+
 <li>{@link android.net.wifi.p2p.WifiP2pManager.PeerListListener} interface allows you to receive
 information about discovered peers. The callback provides a {@link
 android.net.wifi.p2p.WifiP2pDeviceList}, from which you can retrieve a {@link
 android.net.wifi.p2p.WifiP2pDevice} object for each device within range and get information such as
 the device name, address, device type, the WPS configurations the device supports, and more.</li>
+
 <li>The {@link android.net.wifi.p2p.WifiP2pManager.GroupInfoListener} interface allows you to
-receive
-information about a P2P group. The callback provides a {@link android.net.wifi.p2p.WifiP2pGroup}
-object, which provides group information such as the owner, the network name, and passphrase.</li>
+receive information about a P2P group. The callback provides a {@link
+android.net.wifi.p2p.WifiP2pGroup} object, which provides group information such as the owner, the
+network name, and passphrase.</li>
+
 <li>{@link android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener} interface allows you to
-receive
-information about the current connection. The callback provides a {@link
+receive information about the current connection. The callback provides a {@link
 android.net.wifi.p2p.WifiP2pInfo} object, which has information such as whether a group has been
 formed and who is the group owner.</li>
 </ul>
@@ -642,58 +728,57 @@
 <ul>
 <li>{@link android.Manifest.permission#ACCESS_WIFI_STATE}</li>
 <li>{@link android.Manifest.permission#CHANGE_WIFI_STATE}</li>
-<li>{@link android.Manifest.permission#INTERNET} (even though your app doesn’t technically connect
-to
-the Internet, the WiFi Direct implementation uses traditional sockets that do require Internet
-permission to work).</li>
+<li>{@link android.Manifest.permission#INTERNET} (although your app doesn’t technically connect
+to the Internet, communicating to Wi-Fi Direct peers with standard java sockets requires Internet
+permission).</li>
 </ul>
 
 <p>The Android system also broadcasts several different actions during certain Wi-Fi P2P events:</p>
 <ul>
 <li>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_CONNECTION_CHANGED_ACTION}: The P2P
-connection
-state has changed. This carries {@link android.net.wifi.p2p.WifiP2pManager#EXTRA_WIFI_P2P_INFO} with
-a {@link android.net.wifi.p2p.WifiP2pInfo} object and {@link
+connection state has changed. This carries {@link
+android.net.wifi.p2p.WifiP2pManager#EXTRA_WIFI_P2P_INFO} with a {@link
+android.net.wifi.p2p.WifiP2pInfo} object and {@link
 android.net.wifi.p2p.WifiP2pManager#EXTRA_NETWORK_INFO} with a {@link android.net.NetworkInfo}
 object.</li>
+
 <li>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_CHANGED_ACTION}: The P2P state has
-changed
-between enabled and disabled. It carries {@link
+changed between enabled and disabled. It carries {@link
 android.net.wifi.p2p.WifiP2pManager#EXTRA_WIFI_STATE} with either {@link
 android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_DISABLED} or {@link
 android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_ENABLED}</li>
+
 <li>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION}: The list of peer
-devices
-has changed.</li>
+devices has changed.</li>
+
 <li>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_THIS_DEVICE_CHANGED_ACTION}: The details for
 this device have changed.</li>
 </ul>
 
 <p>See the  {@link android.net.wifi.p2p.WifiP2pManager} documentation for more information. Also
-look
-at the <a href=”{@docRoot}resources/samples/WiFiDirectDemo/index.html”>Wi-Fi Direct</a> sample
-application for example code.</p>
+look at the <a href="{@docRoot}resources/samples/WiFiDirectDemo/index.html">Wi-Fi Direct Demo</a>
+sample application.</p>
 
 
 
 
 
-<h3 id="NetworkData">Network Data</h3>
+<h3 id="NetworkUsage">Network Usage</h3>
 
-<p>Android 4.0 gives users precise visibility of how much network data applications are using. The
-Settings app provides controls that allow users to manage set limits for network data usage and even
-disable the use of background data for individual apps. In order to avoid users disabling your app’s
-access to data from the background, you should develop strategies to use use the data connection
-efficiently and vary your usage depending on the type of connection available.</p>
+<p>Android 4.0 gives users precise visibility of how much network data their applications are using.
+The Settings app provides controls that allow users to manage set limits for network data usage and
+even disable the use of background data for individual apps. In order to avoid users disabling your
+app’s access to data from the background, you should develop strategies to use use the data
+connection efficiently and adjust your usage depending on the type of connection available.</p>
 
 <p>If your application performs a lot of network transactions, you should provide user settings that
 allow users to control your app’s data habits, such as how often your app syncs data, whether to
 perform uploads/downloads only when on Wi-Fi, whether to use data while roaming, etc. With these
 controls available to them, users are much less likely to disable your app’s access to data when
 they approach their limits, because they can instead precisely control how much data your app uses.
-When you provide an activity with these settings, you should include in its manifest declaration an
-intent filter for the {@link android.content.Intent#ACTION_MANAGE_NETWORK_USAGE} action. For
-example:</p>
+If you provide a preference activity with these settings, you should include in its manifest
+declaration an intent filter for the {@link android.content.Intent#ACTION_MANAGE_NETWORK_USAGE}
+action. For example:</p>
 
 <pre>
 &lt;activity android:name="DataPreferences" android:label="@string/title_preferences">
@@ -704,10 +789,10 @@
 &lt;/activity>
 </pre>
 
-<p>This intent filter indicates to the system that this is the application that controls your
+<p>This intent filter indicates to the system that this is the activity that controls your
 application’s data usage. Thus, when the user inspects how much data your app is using from the
-Settings app, a “View application settings” button is available that launches your activity so the
-user can refine how much data your app uses.</p>
+Settings app, a “View application settings" button is available that launches your
+preference activity so the user can refine how much data your app uses.</p>
 
 <p>Also beware that {@link android.net.ConnectivityManager#getBackgroundDataSetting()} is now
 deprecated and always returns true&mdash;use  {@link
@@ -715,7 +800,7 @@
 transactions, you should always call {@link android.net.ConnectivityManager#getActiveNetworkInfo()}
 to get the {@link android.net.NetworkInfo} that represents the current network and query {@link
 android.net.NetworkInfo#isConnected()} to check whether the device has a
-connection. You can then check various other connection properties, such as whether the device is
+connection. You can then check other connection properties, such as whether the device is
 roaming or connected to Wi-Fi.</p>
 
 
@@ -724,43 +809,10 @@
 
 
 
-<h3 id="Sensors">Device Sensors</h3>
 
-<p>Two new sensor types have been added in Android 4.0: {@link
-android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} and {@link
-android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY}. </p>
+<h3 id="RenderScript">RenderScript</h3>
 
-<p>{@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} is a temperature sensor that provides
-the ambient (room) temperature near a device. This sensor reports data in degrees Celsius. {@link
-android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY} is a humidity sensor that provides the relative
-ambient (room) humidity. The sensor reports data as a percentage. If a device has both {@link
-android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} and  {@link
-android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY} sensors, you can use them to calculate the dew point
-and the absolute humidity.</p>
-
-<p>The existing temperature sensor ({@link android.hardware.Sensor#TYPE_TEMPERATURE}) has been
-deprecated. You should use the {@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} sensor
-instead.</p>
-
-<p>Additionally, Android’s three synthetic sensors have been improved so they now have lower latency
-and smoother output. These sensors include the gravity sensor ({@link
-android.hardware.Sensor#TYPE_GRAVITY}), rotation vector sensor ({@link
-android.hardware.Sensor#TYPE_ROTATION_VECTOR}), and linear acceleration sensor ({@link
-android.hardware.Sensor#TYPE_LINEAR_ACCELERATION}). The improved sensors rely on the gyroscope
-sensor to improve their output so the sensors appear only on devices that have a gyroscope. If a
-device already provides one of the sensors, then that sensor appears as a second sensor on the
-device. The three improved sensors have a version number of 2.</p>
-
-
-
-
-
-
-
-
-<h3 id="Renderscript">Renderscript</h3>
-
-<p>Three major features have been added to Renderscript:</p>
+<p>Three major features have been added to RenderScript:</p>
 
 <ul>
   <li>Off-screen rendering to a framebuffer object</li>
@@ -771,24 +823,24 @@
 <p>The {@link android.renderscript.Allocation} class now supports a {@link
 android.renderscript.Allocation#USAGE_GRAPHICS_RENDER_TARGET} memory space, which allows you to
 render things directly into the {@link android.renderscript.Allocation} and use it as a framebuffer
-object.  </p>
+object.</p>
 
-<p>{@link android.renderscript.RSTextureView} provides a means to display Renderscript graphics
-inside
-of a normal View,  unlike {@link android.renderscript.RSSurfaceView}, which creates a separate
-window. This key difference allows you to do things such as move, transform, or animate an {@link
-android.renderscript.RSTextureView} as well as draw Renderscript graphics inside the View alongside
-other traditional View widgets.</p>
+<p>{@link android.renderscript.RSTextureView} provides a means to display RenderScript graphics
+inside of a {@link android.view.View},  unlike {@link android.renderscript.RSSurfaceView}, which
+creates a separate window. This key difference allows you to do things such as move, transform, or
+animate an {@link android.renderscript.RSTextureView} as well as draw RenderScript graphics inside
+a view that lies within an activity layout.</p>
 
-<p>The {@link android.renderscript.Script#forEach forEach()} method allows you to call Renderscript
-compute scripts from the VM level and have them automatically delegated to available cores on the
-device. You do not use this method directly, but any compute Renderscript that you write will have a
-{@link android.renderscript.Script#forEach forEach()}  method that you can call in the reflected
-Renderscript class. You can call the reflected {@link android.renderscript.Script#forEach forEach()}
-method by passing in an input {@link android.renderscript.Allocation} to process, an output {@link
-android.renderscript.Allocation} to write the result to, and a data structure if the Renderscript
-needs more information in addition to the {@link android.renderscript.Allocation}s to. Only one of
-the {@link android.renderscript.Allocation}s is necessary and the data structure is optional.</p>
+<p>The {@link android.renderscript.Script#forEach Script.forEach()} method allows you to call
+RenderScript compute scripts from the VM level and have them automatically delegated to available
+cores on the device. You do not use this method directly, but any compute RenderScript that you
+write will have a {@link android.renderscript.Script#forEach forEach()}  method that you can call in
+the reflected RenderScript class. You can call the reflected {@link
+android.renderscript.Script#forEach forEach()} method by passing in an input {@link
+android.renderscript.Allocation} to process, an output {@link android.renderscript.Allocation} to
+write the result to, and a {@link android.renderscript.FieldPacker} data structure in case the
+RenderScript needs more information. Only one of the {@link android.renderscript.Allocation}s is
+necessary and the data structure is optional.</p>
 
 
 
@@ -797,118 +849,154 @@
 
 <h3 id="A11y">Accessibility</h3>
 
-<p>Android 4.0 improves accessibility for users with disabilities with the Touch Exploration service
-and provides extended APIs for developers of new accessibility services.</p>
-
-<h4>Touch Exploration</h4>
-
-<p>Users with vision loss can now explore applications by touching areas of the screen and hearing
-voice descriptions of the content. The “Explore by Touch” feature works like a virtual cursor as the
-user drags a finger across the screen.</p>
-
-<p>You don’t have to use any new APIs to enhance touch exploration in your application, because the
-existing {@link android.R.attr#contentDescription android:contentDescription}
-attribute and {@link android.view.View#setContentDescription setContentDescription()} method is all
-you need. Because touch exploration works like a virtual cursor, it allows screen readers to
-identify the descriptive the same way that screen readers can when navigating with a d-pad or
-trackball. So this is a reminder to provide descriptive text for the views in your application,
-especially for {@link android.widget.ImageButton}, {@link android.widget.EditText}, {@link
-android.widget.CheckBox} and other interactive widgets that might not contain text information by
-default.</p>
-
-<h4>Accessibility for Custom Views</h4>
-
-<p>Developers of custom Views, ViewGroups and widgets can make their components compatible with
-accessibility services like Touch Exploration. For custom views and widgets targeted for Android 4.0
-and later, developers should implement the following accessibility API methods in their classes:</p>
-<ul>
-<li>These two methods initiate the accessibility event generation process and must be implemented by
-your custom view class.
-  <ul>
-  <li>{@link android.view.View#sendAccessibilityEvent(int) sendAccessibilityEvent()} If
-accessibility
-  is
-  not enabled, this call has no effect.</li>
-  <li>{@link
-  android.view.View#sendAccessibilityEventUnchecked(android.view.accessibility.AccessibilityEvent)
-  sendAccessibilityEventUnchecked()} - This method executes regardless of whether accessibility is
-  enabled or not.</li>
-  </ul>
-</li>
-
-<li>These methods are called in order by the sendAccessibilityEvent methods listed above to collect
-accessibility information about the view, and its child views.
-  <ul>
-  <li>{@link
-  android.view.View#onInitializeAccessibilityEvent(android.view.accessibility.AccessibilityEvent)
-  onInitializeAccessibilityEvent()} - This method collects information about the view. If your
-  application has specific requirements for accessibility, you should extend this method to add that
-  information to the {@link android.view.accessibility.AccessibilityEvent}.</li>
-  
-  <li>{@link
- 
-android.view.View#dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent)
-  dispatchPopulateAccessibilityEvent()} is called by the framework to request text information for
-  this view and its children. This method calls {@link
-  android.view.View#onPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent)
-  onPopulateAccessibilityEvent()} first on the current view and then on its children.</li>
-  </ul>
-</li>
-
-<li>The {@link
-android.view.View#onInitializeAccessibilityNodeInfo onInitializeAccessibilityNodeInfo()} method
-provides additional context information for
-accessibility services. You should implement or override this method to provide improved information
-for accessibility services investigating your custom view.</li>
-
-<li>Custom {@link android.view.ViewGroup} classes should also implement {@link
-android.view.ViewGroup#onRequestSendAccessibilityEvent(android.view.View,
-android.view.accessibility.AccessibilityEvent) onRequestSendAccessibilityEvent()}  </li>
-</ul>
-
-<p>Developers who want to maintain compatibility with Android versions prior to 4.0, while still
-providing support for new the accessibility APIs, can use the {@link
-android.view.View#setAccessibilityDelegate(android.view.View.AccessibilityDelegate)
-setAccessibilityDelegate()} method to provide an {@link android.view.View.AccessibilityDelegate}
-containing implementations of the new accessibility API methods while maintaining compatibility with
-prior releases.</p>
+<p>Android 4.0 improves accessibility for sight-impaired users with new explore-by-touch mode
+and extended APIs that allow you to provide more information about view content or
+develop advanced accessibility services.</p>
 
 
+<h4>Explore-by-touch mode</h4>
 
-<h4>Accessibility Service APIs</h4>
+<p>Users with vision loss can now explore the screen by touching and dragging a finger across the
+screen to hear voice descriptions of the content. Because the explore-by-touch mode works like a
+virtual cursor, it allows screen readers to identify the descriptive text the same way that screen
+readers can when the user navigates with a d-pad or trackball&mdash;by reading information provided
+by {@link android.R.attr#contentDescription android:contentDescription} and {@link
+android.view.View#setContentDescription setContentDescription()} upon a simulated "hover" event. So,
+consider this is a reminder that you should provide descriptive text for the views in your
+application, especially for {@link android.widget.ImageButton}, {@link android.widget.EditText},
+{@link android.widget.ImageView} and other widgets that might not naturally contain descriptive
+text.</p>
 
-<p>Accessibility events have been significantly improved to provide better information for
-accessibility services. In particular, events are generated based on view composition, providing
-better context information and allowing accessibility service developers to traverse view
-hierarchies to get additional view information and deal with special cases.</p>
 
-<p>To access additional content information and traverse view hierarchies, accessibility service
-application developers should use the following procedure.</p>
+<h4>Accessibility for views</h4>
+
+<p>To enhance the information available to accessibility services such as screen readers, you can
+implement new callback methods for accessibility events in your custom {@link
+android.view.View} components.</p>
+
+<p>It's important to first note that the behavior of the {@link
+android.view.View#sendAccessibilityEvent sendAccessibilityEvent()} method has changed in Android
+4.0. As with previous version of Android, when the user enables accessibility services on the device
+and an input event such as a click or hover occurs, the respective view is notified with a call to
+{@link android.view.View#sendAccessibilityEvent sendAccessibilityEvent()}. Previously, the
+implementation of {@link android.view.View#sendAccessibilityEvent sendAccessibilityEvent()} would
+initialize an {@link android.view.accessibility.AccessibilityEvent} and send it to {@link
+android.view.accessibility.AccessibilityManager}. The new behavior involves some additional callback
+methods that allow the view and its parents to add more contextual information to the event:
 <ol>
-<li>Upon receiving an {@link android.view.accessibility.AccessibilityEvent} from an application,
-call
-the {@link android.view.accessibility.AccessibilityEvent#getRecord(int)
-AccessibilityEvent.getRecord()} to retrieve new accessibility information about the state of the
-view.</li>
-<li>From the {@link android.view.accessibility.AccessibilityRecord}, call {@link 
-android.view.accessibility.AccessibilityRecord#getSource() getSource()} to retrieve a {@link
-android.view.accessibility.AccessibilityNodeInfo} object.</li>
-<li>With the {@link android.view.accessibility.AccessibilityNodeInfo}, call {@link
-android.view.accessibility.AccessibilityNodeInfo#getParent getParent()} or {@link
-android.view.accessibility.AccessibilityNodeInfo#getChild getChild()} to traverse the view
-hierarchy and get additional context information.</li>
+  <li>When invoked, the {@link
+android.view.View#sendAccessibilityEvent sendAccessibilityEvent()} and {@link
+android.view.View#sendAccessibilityEventUnchecked sendAccessibilityEventUnchecked()} methods defer
+to {@link android.view.View#onInitializeAccessibilityEvent onInitializeAccessibilityEvent()}. 
+  <p>Custom implementations of {@link android.view.View} might want to implement {@link
+android.view.View#onInitializeAccessibilityEvent onInitializeAccessibilityEvent()} to
+attach additional accessibility information to the {@link
+android.view.accessibility.AccessibilityEvent}, but should also call the super implementation to
+provide default information such as the standard content description, item index, and more.
+However, you should not add additional text content in this callback&mdash;that happens
+next.</p></li>
+  <li>Once initialized, if the event is one of several types that should be populated with text
+information, the view then receives a call to {@link
+android.view.View#dispatchPopulateAccessibilityEvent dispatchPopulateAccessibilityEvent()}, which
+defers to the {@link android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()}
+callback.
+  <p>Custom implementations of {@link android.view.View} should usually implement {@link
+android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()} to add additional
+text content to the {@link android.view.accessibility.AccessibilityEvent} if the {@link
+android.R.attr#contentDescription android:contentDescription} text is missing or
+insufficient. To add more text description to the
+{@link android.view.accessibility.AccessibilityEvent}, call {@link
+android.view.accessibility.AccessibilityEvent#getText()}.{@link java.util.List#add add()}.</p>
+</li>
+  <li>At this point, the {@link android.view.View} passes the event up the view hierarchy by calling
+{@link android.view.ViewGroup#requestSendAccessibilityEvent requestSendAccessibilityEvent()} on the
+parent view. Each parent view then has the chance to augment the accessibility information by
+adding an {@link android.view.accessibility.AccessibilityRecord}, until it
+ultimately reaches the root view, which sends the event to the {@link
+android.view.accessibility.AccessibilityManager} with {@link
+android.view.accessibility.AccessibilityManager#sendAccessibilityEvent
+sendAccessibilityEvent()}.</li>
 </ol>
 
-<p>In order to retrieve {@link android.view.accessibility.AccessibilityNodeInfo} information, your
-application must request permission to retrieve application window content through a manifest
-declaration that includes a new, separate xml configuration file, which supercedes {@link
-android.accessibilityservice.AccessibilityServiceInfo}. For more information, see {@link
+<p>In addition to the new methods above, which are useful when extending the {@link
+android.view.View} class, you can also intercept these event callbacks on any {@link
+android.view.View} by extending {@link
+android.view.View.AccessibilityDelegate AccessibilityDelegate} and setting it on the view with
+{@link android.view.View#setAccessibilityDelegate setAccessibilityDelegate()}.
+When you do, each accessibility method in the view defers the call to the corresponding method in
+the delegate. For example, when the view receives a call to {@link
+android.view.View#onPopulateAccessibilityEvent onPopulateAccessibilityEvent()}, it passes it to the
+same method in the {@link android.view.View.AccessibilityDelegate}. Any methods not handled by
+the delegate are given right back to the view for default behavior. This allows you to override only
+the methods necessary for any given view without extending the {@link android.view.View} class.</p>
+
+
+<p>If you want to maintain compatibility with Android versions prior to 4.0, while also supporting
+the new the accessibility APIs, you can do so with the latest version of the <em>v4 support
+library</em> (in <a href="{@docRoot}sdk/compatibility-library.html">Compatibility Package, r4</a>)
+using a set of utility classes that provide the new accessibility APIs in a backward-compatible
+design.</p>
+
+
+
+<h4>Accessibility services</h4>
+
+<p>If you're developing an accessibility service, the information about various accessibility events
+has been significantly expanded to enable more advanced accessibility feedback for users. In
+particular, events are generated based on view composition, providing better context information and
+allowing accessibility services to traverse view hierarchies to get additional view information and
+deal with special cases.</p>
+
+<p>If you're developing an accessibility service (such as a screen reader), you can access
+additional content information and traverse view hierarchies with the following procedure:</p>
+<ol>
+<li>Upon receiving an {@link android.view.accessibility.AccessibilityEvent} from an application,
+call the {@link android.view.accessibility.AccessibilityEvent#getRecord(int)
+AccessibilityEvent.getRecord()} to retrieve a specific {@link
+android.view.accessibility.AccessibilityRecord} (there may be several records attached to the
+event).</li>
+
+<li>From either {@link android.view.accessibility.AccessibilityEvent} or an individual {@link
+android.view.accessibility.AccessibilityRecord}, you can call {@link 
+android.view.accessibility.AccessibilityRecord#getSource() getSource()} to retrieve a {@link
+android.view.accessibility.AccessibilityNodeInfo} object.
+  <p>An {@link android.view.accessibility.AccessibilityNodeInfo} represents a single node
+of the window content in a format that allows you to query accessibility information about that
+node. The {@link android.view.accessibility.AccessibilityNodeInfo} object returned from {@link
+android.view.accessibility.AccessibilityEvent} describes the event source, whereas the source from
+an {@link android.view.accessibility.AccessibilityRecord} describes the predecessor of the event
+source.</p></li>
+
+<li>With the {@link android.view.accessibility.AccessibilityNodeInfo}, you can query information
+about it, call {@link
+android.view.accessibility.AccessibilityNodeInfo#getParent getParent()} or {@link
+android.view.accessibility.AccessibilityNodeInfo#getChild getChild()} to traverse the view
+hierarchy, and even add child views to the node.</li>
+</ol>
+
+<p>In order for your application to publish itself to the system as an accessibility service, it
+must declare an XML configuration file that corresponds to {@link
+android.accessibilityservice.AccessibilityServiceInfo}. For more information about creating an
+accessibility service, see {@link
 android.accessibilityservice.AccessibilityService} and {@link
 android.accessibilityservice.AccessibilityService#SERVICE_META_DATA
-AccessibilityService.SERVICE_META_DATA}.</p>
+SERVICE_META_DATA} for information about the XML configuration.</p>
 
 
+<h4>Other accessibility APIs</h4>
 
+<p>If you're interested in the device's accessibility state, the {@link
+android.view.accessibility.AccessibilityManager} has some new APIs such as:</p>
+<ul>
+  <li>{@link android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener}
+is an interface that allows you to receive a callback whenever accessibility is enabled or
+disabled.</li>
+  <li>{@link android.view.accessibility.AccessibilityManager#getEnabledAccessibilityServiceList
+    getEnabledAccessibilityServiceList()} provides information about which accessibility services
+    are currently enabled.</li>
+  <li>{@link android.view.accessibility.AccessibilityManager#isTouchExplorationEnabled()} tells
+  you whether the explore-by-touch mode is enabled.</li>
+</ul>
 
 
 
@@ -916,13 +1004,12 @@
 
 <p>Android 4.0 expands the capabilities for enterprise application with the following features.</p>
 
-<h4>VPN Services</h4>
+<h4>VPN services</h4>
 
 <p>The new {@link android.net.VpnService} allows applications to build their own VPN (Virtual
-Private
-Network), running as a {@link android.app.Service}. A VPN service creates an interface for a virtual
-network with its own address and routing rules and performs all reading and writing with a file
-descriptor.</p>
+Private Network), running as a {@link android.app.Service}. A VPN service creates an interface for a
+virtual network with its own address and routing rules and performs all reading and writing with a
+file descriptor.</p>
 
 <p>To create a VPN service, use {@link android.net.VpnService.Builder}, which allows you to specify
 the network address, DNS server, network route, and more. When complete, you can establish the
@@ -936,7 +1023,7 @@
 users must manually enable it in the system settings.</p>
 
 
-<h4>Device Restrictions</h4>
+<h4>Device restrictions</h4>
 
 <p>Applications that manage the device restrictions can now disable the camera using {@link
 android.app.admin.DevicePolicyManager#setCameraDisabled setCameraDisabled()} and the {@link
@@ -944,54 +1031,46 @@
 &lt;disable-camera /&gt;} element in the policy configuration file).</p>
 
 
-<h4>Certificate Management</h4>
+<h4>Certificate management</h4>
 
 <p>The new {@link android.security.KeyChain} class provides APIs that allow you to import and access
-certificates and key stores in credential storage.  See the {@link android.security.KeyChain}
+certificates in the system key store. Certificates streamline the installation of both client
+certificates (to validate the identity of the user) and certificate authority certificates (to
+verify server identity). Applications such as web browsers or email clients can access the installed
+certificates to authenticate users to servers. See the {@link android.security.KeyChain}
 documentation for more information.</p>
 
 
 
 
-<h3 id="Voicemail">Voicemail</h3>
-
-<p>A new voicemail APIs allows applications to add voicemails to the system. Because the APIs
-currently
-do not allow third party apps to read all the voicemails from the system, the only third-party apps
-that should use the voicemail APIs are those that have voicemail to deliver to the user. For
-instance, it’s possible that a users have multiple voicemail sources, such as one provided by their
-phone’s service provider and others from VoIP or other alternative services. These kinds of apps can
-use the APIs to add voicemail to the system. The built-in Phone application can then present all
-voicemails to the user with a single list. Although the system’s Phone application is the only
-application that can read all the voicemails, each application that provides voicemails can read
-those that it has added to the system.</p>
-
-<p>The {@link android.provider.VoicemailContract} class defines the content provider for the
-voicemail
-APIs. The subclasses {@link android.provider.VoicemailContract.Voicemails} and {@link
-android.provider.VoicemailContract.Status} provide tables in which the voicemail providers can
-insert voicemail data for storage on the device. For an example of a voicemail provider app, see the
-<a href=”{@docRoot}resources/samples/VoicemailProviderDemo/index.html”>Voicemail Provider
-Demo</a>.</p>
 
 
 
+<h3 id="Sensors">Device Sensors</h3>
 
-<h3 id="SpellChecker">Spell Checker Services</h3>
+<p>Two new sensor types have been added in Android 4.0:</p>
 
-<p>The new spell checker framework allows apps to create spell checkers in a manner similar to the
-input method framework. To create a new spell checker, you must override the {@link
-android.service.textservice.SpellCheckerService.Session} class to provide spelling suggestions based
-on text provided by the interface callback methods, returning suggestions as a {@link
-android.view.textservice.SuggestionsInfo} object. </p>
+<ul>
+  <li>{@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE}: A temperature sensor that provides
+the ambient (room) temperature in degrees Celsius.</li>
+  <li>{@link android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY}: A humidity sensor that provides the
+relative ambient (room) humidity as a percentage.</li>
+</ul>
 
-<p>Applications with a spell checker service must declare the {@link
-android.Manifest.permission#BIND_TEXT_SERVICE} permission as required by the service, such that
-other services must have this permission in order for them to bind with the spell checker service.
-The service must also declare an intent filter with <action
-android:name="android.service.textservice.SpellCheckerService" /> as the intent’s action and should
-include a {@code &lt;meta-data&gt;} element that declares configuration information for the spell
-checker. </p>
+<p>If a device has both {@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} and  {@link
+android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY} sensors, you can use them to calculate the dew point
+and the absolute humidity.</p>
+
+<p>The previous temperature sensor, {@link android.hardware.Sensor#TYPE_TEMPERATURE}, has been
+deprecated. You should use the {@link android.hardware.Sensor#TYPE_AMBIENT_TEMPERATURE} sensor
+instead.</p>
+
+<p>Additionally, Android’s three synthetic sensors have been improved so they now have lower latency
+and smoother output. These sensors include the gravity sensor ({@link
+android.hardware.Sensor#TYPE_GRAVITY}), rotation vector sensor ({@link
+android.hardware.Sensor#TYPE_ROTATION_VECTOR}), and linear acceleration sensor ({@link
+android.hardware.Sensor#TYPE_LINEAR_ACCELERATION}). The improved sensors rely on the gyroscope
+sensor to improve their output, so the sensors appear only on devices that have a gyroscope.</p>
 
 
 
@@ -999,22 +1078,20 @@
 
 <h3 id="TTS">Text-to-speech Engines</h3>
 
-<p>Android’s text-to-speech (TTS) APIs have been greatly extended to allow applications to more
-easily
-implement custom TTS engines, while applications that want to use a TTS engine have a couple new
-APIs for selecting the engine.</p>
+<p>Android’s text-to-speech (TTS) APIs have been significantly extended to allow applications to
+more easily implement custom TTS engines, while applications that want to use a TTS engine have a
+couple new APIs for selecting an engine.</p>
 
 
 <h4>Using text-to-speech engines</h4>
 
 <p>In previous versions of Android, you could use the {@link android.speech.tts.TextToSpeech} class
-to
-perform text-to-speech (TTS) operations using the TTS engine provided by the system or set a custom
-engine using {@link android.speech.tts.TextToSpeech#setEngineByPackageName
-setEngineByPackageName()}.
-In Android 4.0, the {@link android.speech.tts.TextToSpeech#setEngineByPackageName
-setEngineByPackageName()} method has been deprecated and you can now specify the engine to use with
-a new {@link android.speech.tts.TextToSpeech} that accepts the package name of a TTS engine.</p>
+to perform text-to-speech (TTS) operations using the TTS engine provided by the system or set a
+custom engine using {@link android.speech.tts.TextToSpeech#setEngineByPackageName
+setEngineByPackageName()}. In Android 4.0, the {@link
+android.speech.tts.TextToSpeech#setEngineByPackageName setEngineByPackageName()} method has been
+deprecated and you can now specify the engine to use with a new {@link
+android.speech.tts.TextToSpeech} constructor that accepts the package name of a TTS engine.</p>
 
 <p>You can also query the available TTS engines with {@link
 android.speech.tts.TextToSpeech#getEngines()}. This method returns a list of {@link
@@ -1024,39 +1101,59 @@
 
 <h4>Building text-to-speech engines</h4>
 
-<p>Previously, custom engines required that the engine be built using native code, based on a TTS
-engine header file. In Android 4.0, there is a framework API for building TTS engines. </p>
+<p>Previously, custom engines required that the engine be built using an undocumented native header
+file. In Android 4.0, there is a complete set of framework APIs for building TTS engines. </p>
 
 <p>The basic setup requires an implementation of {@link android.speech.tts.TextToSpeechService} that
 responds to the {@link android.speech.tts.TextToSpeech.Engine#INTENT_ACTION_TTS_SERVICE} intent. The
 primary work for a TTS engine happens during the {@link
-android.speech.tts.TextToSpeechService#onSynthesizeText onSynthesizeText()} callback in the {@link
-android.speech.tts.TextToSpeechService}. The system delivers this method two objects:</p>
+android.speech.tts.TextToSpeechService#onSynthesizeText onSynthesizeText()} callback in a service
+that extends {@link android.speech.tts.TextToSpeechService}. The system delivers this method two
+objects:</p>
 <ul>
 <li>{@link android.speech.tts.SynthesisRequest}: This contains various data including the text to
 synthesize, the locale, the speech rate, and voice pitch.</li>
 <li>{@link android.speech.tts.SynthesisCallback}: This is the interface by which your TTS engine
-delivers the resulting speech data as streaming audio, by calling {@link
+delivers the resulting speech data as streaming audio. First the engine must call {@link
 android.speech.tts.SynthesisCallback#start start()} to indicate that the engine is ready to deliver
-the
-audio, then call {@link android.speech.tts.SynthesisCallback#audioAvailable audioAvailable()},
-passing it the audio
-data in a byte buffer. Once your engine has passed all audio through the buffer, call {@link
-android.speech.tts.SynthesisCallback#done()}.</li>
+the audio, then call {@link android.speech.tts.SynthesisCallback#audioAvailable audioAvailable()},
+passing it the audio data in a byte buffer. Once your engine has passed all audio through the
+buffer, call {@link android.speech.tts.SynthesisCallback#done()}.</li>
 </ul>
 
-<p>Now that the framework supports a true API for creating TTS engines, support for the previous
-technique using native code has been removed. Watch for a blog post about the compatibility layer
-that you can use to convert TTS engines built using the previous technique to the new framework.</p>
+<p>Now that the framework supports a true API for creating TTS engines, support for the native code
+implementation has been removed. Look for a blog post about a compatibility layer
+that you can use to convert your old TTS engines to the new framework.</p>
 
 <p>For an example TTS engine using the new APIs, see the <a
-href=”{@docRoot}resources/samples/TtsEngine/index.html”>Text To Speech Engine</a> sample app.</p>
+href="{@docRoot}resources/samples/TtsEngine/index.html">Text To Speech Engine</a> sample app.</p>
 
 
 
 
 
 
+<h3 id="SpellChecker">Spell Checker Services</h3>
+
+<p>A new spell checker framework allows apps to create spell checkers in a manner similar to the
+input method framework. To create a new spell checker, you must implement a service that extends
+{@link android.service.textservice.SpellCheckerService} and extend the {@link
+android.service.textservice.SpellCheckerService.Session} class to provide spelling suggestions based
+on text provided by interface callback methods. In the {@link
+android.service.textservice.SpellCheckerService.Session} callback methods, you must return the
+spelling suggestions as {@link android.view.textservice.SuggestionsInfo} objects. </p>
+
+<p>Applications with a spell checker service must declare the {@link
+android.Manifest.permission#BIND_TEXT_SERVICE} permission as required by the service, such that
+other services must have this permission in order for them to bind with the spell checker service.
+The service must also declare an intent filter with {@code &lt;action
+android:name="android.service.textservice.SpellCheckerService" />} as the intent’s action and should
+include a {@code &lt;meta-data&gt;} element that declares configuration information for the spell
+checker. </p>
+
+
+
+
 
 
 
@@ -1066,34 +1163,36 @@
 
 <p>The {@link android.app.ActionBar} has been updated to support several new behaviors. Most
 importantly, the system gracefully manages the action bar’s size and configuration when running on
-smaller screens in order to provide an optimal user experience. For example, when the screen is
-narrow (such as when a handset is in portrait orientation), the action bar’s navigation tabs appear
-in a “stacked bar,” which appears directly below the main action bar. You can also opt-in to a
-“split action bar,” which will place all action items in a separate bar at the bottom of the screen
-when the screen is narrow.</p>
+smaller screens in order to provide an optimal user experience on all screen sizes. For example,
+when the screen is narrow (such as when a handset is in portrait orientation), the action bar’s
+navigation tabs appear in a “stacked bar," which appears directly below the main action bar. You can
+also opt-in to a “split action bar," which places all action items in a separate bar at the bottom
+of the screen when the screen is narrow.</p>
 
 
-<h4>Split Action Bar</h4>
+<h4>Split action bar</h4>
 
-<p>If your action bar includes several action items, not all of them will fit into the action bar
-when on a narrow screen, so the system will place them into the overflow menu. However, Android 4.0
-allows you to enable “split action bar” so that more action items can appear on the screen in a
+<p>If your action bar includes several action items, not all of them will fit into the action bar on
+a narrow screen, so the system will place more of them into the overflow menu. However, Android 4.0
+allows you to enable “split action bar" so that more action items can appear on the screen in a
 separate bar at the bottom of the screen. To enable split action bar, add {@link
-android.R.attr#uiOptions android:uiOptions} with {@code ”splitActionBarWhenNarrow”} to either your
-{@code &lt;application&gt;} tag or individual {@code &lt;activity&gt;} tags in your manifest file.
-When enabled, the system will enable the additional bar for action items when the screen is narrow
-and add all action items to the new bar (no action items will appear in the primary action bar).</p>
+android.R.attr#uiOptions android:uiOptions} with {@code "splitActionBarWhenNarrow"} to either your
+<a href="guide/topics/manifest/application-element.html">{@code &lt;application&gt;}</a> tag or
+individual <a href="guide/topics/manifest/activity-element.html">{@code &lt;activity&gt;}</a> tags
+in your manifest file. When enabled, the system will add an additional bar at the bottom of the
+screen for all action items when the screen is narrow (no action items will appear in the primary
+action bar).</p>
 
 <p>If you want to use the navigation tabs provided by the {@link android.app.ActionBar.Tab} APIs,
-but
-don’t want the stacked bar&mdash;you want only the tabs to appear, then enable the split action bar
-as described above and also call {@link android.app.ActionBar#setDisplayShowHomeEnabled
-setDisplayShowHomeEnabled(false)} to disable the application icon in the action bar. With nothing
-left in the main action bar, it disappears&mdash;all that’s left are the navigation tabs at the top
-and the action items at the bottom of the screen.</p>
+but don’t need the main action bar on top (you want only the tabs to appear at the top), then enable
+the split action bar as described above and also call {@link
+android.app.ActionBar#setDisplayShowHomeEnabled setDisplayShowHomeEnabled(false)} to disable the
+application icon in the action bar. With nothing left in the main action bar, it
+disappears&mdash;all that’s left are the navigation tabs at the top and the action items at the
+bottom of the screen.</p>
 
 
-<h4>Action Bar Styles</h4>
+<h4>Action bar styles</h4>
 
 <p>If you want to apply custom styling to the action bar, you can use new style properties {@link
 android.R.attr#backgroundStacked} and {@link android.R.attr#backgroundSplit} to apply a background
@@ -1103,31 +1202,38 @@
 setSplitBackgroundDrawable()}.</p>
 
 
-<h4>Action Provider</h4>
+<h4>Action provider</h4>
 
-<p>The new {@link android.view.ActionProvider} class facilitates user actions to which several
-different applications may respond. For example, a “share” action in your application might invoke
-several different apps that can handle the {@link android.content.Intent#ACTION_SEND} intent and the
-associated data. In this case, you can use the {@link android.widget.ShareActionProvider} (an
-extension of {@link android.view.ActionProvider}) in your action bar, instead of a traditional menu
-item that invokes the intent. The {@link android.widget.ShareActionProvider} populates a drop-down
-menu with all the available apps that can handle the intent.</p>
+<p>The new {@link android.view.ActionProvider} class allows you to create a specialized handler for
+action items. An action provider can define an action view, a default action behavior, and a submenu
+for each action item to which it is associated. When you want to create an action item that has
+dynamic behaviors (such as a variable action view, default action, or submenu), extending {@link
+android.view.ActionProvider} is a good solution in order to create a reusable component, rather than
+handling the various action item transformations in your fragment or activity.</p>
+
+<p>For example, the {@link android.widget.ShareActionProvider} is an extension of {@link
+android.view.ActionProvider} that facilitates a “share" action from the action bar. Instead of using
+traditional action item that invokes the {@link android.content.Intent#ACTION_SEND} intent, you can
+use this action provider to present an action view with a drop-down list of applications that handle
+the {@link android.content.Intent#ACTION_SEND} intent. When the user selects an application to use
+for the action, {@link android.widget.ShareActionProvider} remembers that selection and provides it
+in the action view for faster access to sharing with that app.</p>
 
 <p>To declare an action provider for an action item, include the {@code android:actionProviderClass}
-attribute in the {@code &lt;item&gt;} element for your activity’s options menu, with the class name
-of the action provider as the attribute value. For example:</p>
+attribute in the <a href="{@docRoot}guide/topics/resources/menu-resource.html#item-element">{@code
+&lt;item&gt;}</a> element for your activity’s options menu, with the class name of the action
+provider as the value. For example:</p>
 
 <pre>
 &lt;item android:id="@+id/menu_share"
       android:title="Share"
-      android:icon="@drawable/ic_share"
       android:showAsAction="ifRoom"
       android:actionProviderClass="android.widget.ShareActionProvider" /&gt;
 </pre>
 
 <p>In your activity’s {@link android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()}
-callback
-method, retrieve an instance of the action provider from the menu item and set the intent:</p>
+callback method, retrieve an instance of the action provider from the menu item and set the
+intent:</p>
 
 <pre>
 public boolean onCreateOptionsMenu(Menu menu) {
@@ -1142,21 +1248,23 @@
 </pre>
 
 <p>For an example using the {@link android.widget.ShareActionProvider}, see the <a
-href=”{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/ActionBarActionProviderActivity.html”>ActionBarActionProviderActivity</a>
+href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/
+ActionBarActionProviderActivity.html">ActionBarActionProviderActivity</a>
 class in ApiDemos.</p>
 
 
-<h4>Collapsible Action Views</h4>
+<h4>Collapsible action views</h4>
 
-<p>Menu items that appear as action items can now toggle between their action view state and
+<p>Action items that provide an action view can now toggle between their action view state and
 traditional action item state. Previously only the {@link android.widget.SearchView} supported
 collapsing when used as an action view, but now you can add an action view for any action item and
 switch between the expanded state (action view is visible) and collapsed state (action item is
 visible).</p>
 
 <p>To declare that an action item that contains an action view be collapsible, include the {@code
-“collapseActionView”} flag in the {@code android:showAsAction} attribute for the {@code
-&lt;item&gt;} element in the menu’s XML file.</p>
+“collapseActionView"} flag in the {@code android:showAsAction} attribute for the <a
+href="{@docRoot}guide/topics/resources/menu-resource.html#item-element">{@code
+&lt;item&gt;}</a> element in the menu’s XML file.</p>
 
 <p>To receive callbacks when an action view switches between expanded and collapsed, register an
 instance of {@link android.view.MenuItem.OnActionExpandListener} with the respective {@link
@@ -1173,20 +1281,20 @@
 collapsed.</p>
 
 
-<h4>Other APIs for Action Bar</h4>
+<h4>Other APIs for action bar</h4>
 <ul>
-<li>{@link android.app.ActionBar#setHomeButtonEnabled setHomeButtonEnabled()} allows you to disable
-the
-default behavior in which the application icon/logo behaves as a button (pass “false” to disable it
-as a button).</li>
+<li>{@link android.app.ActionBar#setHomeButtonEnabled setHomeButtonEnabled()} allows you to specify
+whether the icon/logo behaves as a button to navigate home or “up" (pass “true" to make it behave as
+a button).</li>
+
 <li>{@link android.app.ActionBar#setIcon setIcon()} and {@link android.app.ActionBar#setLogo
-setLogo()}
-to define the action bar icon or logo at runtime.</li>
+setLogo()} allow you to define the action bar icon or logo at runtime.</li>
+
 <li>{@link android.app.Fragment#setMenuVisibility Fragment.setMenuVisibility()} allows you to enable
-or
-disable the visibility of the options menu items declared by the fragment. This is useful if the
+or disable the visibility of the options menu items declared by the fragment. This is useful if the
 fragment has been added to the activity, but is not visible, so the menu items should be
 hidden.</li>
+
 <li>{@link android.app.FragmentManager#invalidateOptionsMenu
 FragmentManager.invalidateOptionsMenu()}
 allows you to invalidate the activity options menu during various states of the fragment lifecycle
@@ -1204,6 +1312,7 @@
 
 <p>Android 4.0 introduces a variety of new views and other UI components.</p>
 
+
 <h4>System UI</h4>
 
 <p>Since the early days of Android, the system has managed a UI component known as the <em>status
@@ -1214,8 +1323,8 @@
 Android 4.0, the system provides a new type of system UI called the <em>navigation bar</em>. The
 navigation bar shares some qualities with the system bar, because it provides navigation controls
 for devices that don’t have hardware counterparts for navigating the system, but the navigation
-controls is all that it provides (a device with the navigation bar, thus, also includes the status
-bar at the top of the screen).</p>
+controls is all that the navigation bar offers (a device with the navigation bar, thus, also
+includes the status bar at the top of the screen).</p>
 
 <p>To this day, you can hide the status bar on handsets using the {@link
 android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN} flag. In Android 4.0, the APIs that control
@@ -1223,43 +1332,41 @@
 and navigation bar:</p>
 <ul>
 <li>The {@link android.view.View#SYSTEM_UI_FLAG_LOW_PROFILE} flag replaces View.STATUS_BAR_HIDDEN
-flag
-(now deprecated). When set, this flag enables “low profile” mode for the system bar or navigation
-bar. Navigation buttons dim and other elements in the system bar also hide.</li>
+flag. When set, this flag enables “low profile" mode for the system bar or
+navigation bar. Navigation buttons dim and other elements in the system bar also hide.</li>
+
 <li>The {@link android.view.View#SYSTEM_UI_FLAG_VISIBLE} flag replaces the {@code
-STATUS_BAR_VISIBLE}
-flag to request the system bar or navigation bar be visible.</li>
+STATUS_BAR_VISIBLE} flag to request the system bar or navigation bar be visible.</li>
+
 <li>The {@link android.view.View#SYSTEM_UI_FLAG_HIDE_NAVIGATION} is a new flag that requests that
-the
-navigation bar hide completely. Take note that this works only for the <em>navigation bar</em> used
-by some handsets (it does <strong>not</strong> hide the system bar on tablets). The navigation bar
-returns as soon as the system receives user input. As such, this mode is generally used for video
-playback or other cases in which user input is not required.</li>
+the navigation bar hide completely. Take note that this works only for the <em>navigation bar</em>
+used by some handsets (it does <strong>not</strong> hide the system bar on tablets). The navigation
+bar returns as soon as the system receives user input. As such, this mode is generally used for
+video playback or other cases in which the whole screen is needed but user input is not
+required.</li>
 </ul>
 
-<p>You can set each of these flags for the system bar by calling {@link
-android.view.View#setSystemUiVisibility setSystemUiVisibility()} on any view in your activity
-window. The window manager will combine (OR-together) all flags from all views in your window and
+<p>You can set each of these flags for the system bar and navigation bar by calling {@link
+android.view.View#setSystemUiVisibility setSystemUiVisibility()} on any view in your activity. The
+window manager will combine (OR-together) all flags from all views in your window and
 apply them to the system UI as long as your window has input focus. When your window loses input
 focus (the user navigates away from your app, or a dialog appears), your flags cease to have effect.
 Similarly, if you remove those views from the view hierarchy their flags no longer apply.</p>
 
 <p>To synchronize other events in your activity with visibility changes to the system UI (for
-example,
-hide the action bar or other UI controls when the system UI hides), you can register a {@link
-android.view.View.OnSystemUiVisibilityChangeListener} to get a callback when the visibility
-changes.</p>
+example, hide the action bar or other UI controls when the system UI hides), you should register a
+{@link android.view.View.OnSystemUiVisibilityChangeListener} to be notified when the visibility
+of the system bar or navigation bar changes.</p>
 
 <p>See the <a
-href=”{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/OverscanActivity.html”>
+href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/OverscanActivity.html">
 OverscanActivity</a> class for a demonstration of different system UI options.</p>
 
 
 <h4>GridLayout</h4>
 
 <p>{@link android.widget.GridLayout} is a new view group that places child views in a rectangular
-grid.
-Unlike {@link android.widget.TableLayout}, {@link android.widget.GridLayout} relies on a flat
+grid. Unlike {@link android.widget.TableLayout}, {@link android.widget.GridLayout} relies on a flat
 hierarchy and does not make use of intermediate views such as table rows for providing structure.
 Instead, children specify which row(s) and column(s) they should occupy (cells can span multiple
 rows and/or columns), and by default are laid out sequentially across the grid’s rows and columns.
@@ -1269,7 +1376,8 @@
 on children.</p>
 
 <p>See <a
-href=”{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/index.html”>ApiDemos</a>
+href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/index.html">ApiDemos</a
+>
 for samples using {@link android.widget.GridLayout}.</p>
 
 
@@ -1277,11 +1385,10 @@
 <h4>TextureView</h4>
 
 <p>{@link android.view.TextureView} is a new view that allows you to display a content stream, such
-as
-a video or an OpenGL scene. Although similar to {@link android.view.SurfaceView}, {@link
+as a video or an OpenGL scene. Although similar to {@link android.view.SurfaceView}, {@link
 android.view.TextureView} is unique in that it behaves like a regular view, rather than creating a
 separate window, so you can treat it like any other {@link android.view.View} object. For example,
-you can apply transforms, animate it using {@link android.view.ViewPropertyAnimator}, or easily
+you can apply transforms, animate it using {@link android.view.ViewPropertyAnimator}, or
 adjust its opacity with {@link android.view.View#setAlpha setAlpha()}.</p>
 
 <p>Beware that {@link android.view.TextureView} works only within a hardware accelerated window.</p>
@@ -1289,38 +1396,36 @@
 <p>For more information, see the {@link android.view.TextureView} documentation.</p>
 
 
-<h4>Switch Widget</h4>
+<h4>Switch widget</h4>
 
 <p>The new {@link android.widget.Switch} widget is a two-state toggle that users can drag to one
-side
-or the other (or simply tap) to toggle an option between two states.</p>
+side or the other (or simply tap) to toggle an option between two states.</p>
 
-<p>You can declare a switch in your layout with the {@code &lt;Switch&gt;} element. You can use the
-{@code android:textOn} and {@code android:textOff} attributes to specify the text to appear on the
-switch when in the on and off setting. The {@code android:text} attribute also allows you to place a
-label alongside the switch.</p>
+<p>You can use the {@code android:textOn} and {@code android:textOff} attributes to specify the text
+to appear on the switch when in the on and off setting. The {@code android:text} attribute also
+allows you to place a label alongside the switch.</p>
 
 <p>For a sample using switches, see the <a
-href=”{@docRoot}resources/samples/ApiDemos/res/layout/switches.html”>switches.xml</a> layout file
+href="{@docRoot}resources/samples/ApiDemos/res/layout/switches.html">switches.xml</a> layout file
 and respective <a
-href=”{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/Switches.html”>Switches
+href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/Switches.html">Switches
 </a> activity.</p>
 
 
-<h4>Popup Menus</h4>
+<h4>Popup menus</h4>
 
 <p>Android 3.0 introduced {@link android.widget.PopupMenu} to create short contextual menus that pop
-up
-at an anchor point you specify (usually at the point of the item selected). Android 4.0 extends the
-{@link android.widget.PopupMenu} with a couple useful features:</p>
+up at an anchor point you specify (usually at the point of the item selected). Android 4.0 extends
+the {@link android.widget.PopupMenu} with a couple useful features:</p>
 <ul>
 <li>You can now easily inflate the contents of a popup menu from an XML <a
-href=”{@docRoot}guide/topics/resources/menu-resource.html”>menu resource</a> with {@link
+href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a> with {@link
 android.widget.PopupMenu#inflate inflate()}, passing it the menu resource ID.</li>
 <li>You can also now create a {@link android.widget.PopupMenu.OnDismissListener} that receives a
 callback when the menu is dismissed.</li>
 </ul>
 
+
 <h4>Preferences</h4>
 
 <p>A new {@link android.preference.TwoStatePreference} abstract class serves as the basis for
@@ -1332,10 +1437,10 @@
 android.preference.SwitchPreference} for the Wi-Fi and Bluetooth settings.</p>
 
 
-<h4>Hover Events</h4>
+<h4>Hover events</h4>
 
-<p>The {@link android.view.View} class now supports “hover” events to enable richer interactions
-through the use of pointer devices (such as a mouse or other device that drives an on-screen
+<p>The {@link android.view.View} class now supports “hover" events to enable richer interactions
+through the use of pointer devices (such as a mouse or other devices that drive an on-screen
 cursor).</p>
 
 <p>To receive hover events on a view, implement the {@link android.view.View.OnHoverListener} and
@@ -1355,21 +1460,19 @@
 listener returns false, then the hover event will be dispatched to the parent view as usual.</p>
 
 <p>If your application uses buttons or other widgets that change their appearance based on the
-current
-state, you can now use the {@code android:state_hovered} attribute in a <a
-href=”{@docRoot}guide/topics/resources/drawable-resource.html#StateList”>state list drawable</a> to
+current state, you can now use the {@code android:state_hovered} attribute in a <a
+href="{@docRoot}guide/topics/resources/drawable-resource.html#StateList">state list drawable</a> to
 provide a different background drawable when a cursor hovers over the view.</p>
 
 <p>For a demonstration of the new hover events, see the <a
-href=”{@docRoot}samples/ApiDemos/src/com/example/android/apis/view/Hover.html”>Hover</a> class in
+href="{@docRoot}samples/ApiDemos/src/com/example/android/apis/view/Hover.html">Hover</a> class in
 ApiDemos.</p>
 
 
-<h4>Stylus and Mouse Button Input Events</h4>
+<h4>Stylus and mouse button events</h4>
 
 <p>Android now provides APIs for receiving input from a stylus input device such as a digitizer
-tablet
-peripheral or a stylus-enabled touch screen.</p>
+tablet peripheral or a stylus-enabled touch screen.</p>
 
 <p>Stylus input operates in a similar manner to touch or mouse input.  When the stylus is in contact
 with the digitizer, applications receive touch events just like they would when a finger is used to
@@ -1378,7 +1481,7 @@
 are pressed.</p>
 
 <p>Your application can distinguish between finger, mouse, stylus and eraser input by querying the
-“tool type” associated with each pointer in a {@link android.view.MotionEvent} using {@link
+“tool type" associated with each pointer in a {@link android.view.MotionEvent} using {@link
 android.view.MotionEvent#getToolType getToolType()}.  The currently defined tool types are: {@link
 android.view.MotionEvent#TOOL_TYPE_UNKNOWN}, {@link android.view.MotionEvent#TOOL_TYPE_FINGER},
 {@link android.view.MotionEvent#TOOL_TYPE_MOUSE}, {@link android.view.MotionEvent#TOOL_TYPE_STYLUS},
@@ -1386,26 +1489,24 @@
 can choose to handle stylus input in different ways from finger or mouse input.</p>
 
 <p>Your application can also query which mouse or stylus buttons are pressed by querying the “button
-state” of a {@link android.view.MotionEvent} using {@link android.view.MotionEvent#getButtonState
+state" of a {@link android.view.MotionEvent} using {@link android.view.MotionEvent#getButtonState
 getButtonState()}.  The currently defined button states are: {@link
-android.view.MotionEvent#BUTTON_PRIMARY}, {@link
-android.view.MotionEvent#BUTTON_SECONDARY}, {@link
-android.view.MotionEvent#BUTTON_TERTIARY}, {@link android.view.MotionEvent#BUTTON_BACK},
-and {@link android.view.MotionEvent#BUTTON_FORWARD}.
-For convenience, the back and forward mouse buttons are automatically mapped to the {@link
-android.view.KeyEvent#KEYCODE_BACK} and {@link android.view.KeyEvent#KEYCODE_FORWARD} keys.  Your
-application can handle these keys to support mouse button based back and forward navigation.</p>
+android.view.MotionEvent#BUTTON_PRIMARY}, {@link android.view.MotionEvent#BUTTON_SECONDARY}, {@link
+android.view.MotionEvent#BUTTON_TERTIARY}, {@link android.view.MotionEvent#BUTTON_BACK}, and {@link
+android.view.MotionEvent#BUTTON_FORWARD}. For convenience, the back and forward mouse buttons are
+automatically mapped to the {@link android.view.KeyEvent#KEYCODE_BACK} and {@link
+android.view.KeyEvent#KEYCODE_FORWARD} keys.  Your application can handle these keys to support
+mouse button based back and forward navigation.</p>
 
 <p>In addition to precisely measuring the position and pressure of a contact, some stylus input
-devices
-also report the distance between the stylus tip and the digitizer, the stylus tilt angle, and the
-stylus orientation angle.  Your application can query this information using {@link
+devices also report the distance between the stylus tip and the digitizer, the stylus tilt angle,
+and the stylus orientation angle.  Your application can query this information using {@link
 android.view.MotionEvent#getAxisValue getAxisValue()} with the axis codes {@link
 android.view.MotionEvent#AXIS_DISTANCE}, {@link android.view.MotionEvent#AXIS_TILT}, and {@link
 android.view.MotionEvent#AXIS_ORIENTATION}.</p>
 
 <p>For a demonstration of tool types, button states and the new axis codes, see the <a
-href=”{@docRoot}samples/ApiDemos/src/com/example/android/apis/graphics/TouchPaint.html”>TouchPaint
+href="{@docRoot}samples/ApiDemos/src/com/example/android/apis/graphics/TouchPaint.html">TouchPaint
 </a> class in ApiDemos.</p>
 
 
@@ -1463,40 +1564,42 @@
 application has set either <a
 href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a> or
 <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> to
-{@code “14”} or higher. Hardware acceleration generally results in smoother animations, smoother
+{@code “14"} or higher. Hardware acceleration generally results in smoother animations, smoother
 scrolling, and overall better performance and response to user interaction.</p>
 
 <p>If necessary, you can manually disable hardware acceleration with the <a
-href=”{@docRoot}guide/topics/manifest/activity-element.html#hwaccel”>{@code hardwareAccelerated}</a>
+href="{@docRoot}guide/topics/manifest/activity-element.html#hwaccel">{@code hardwareAccelerated}</a>
 attribute for individual <a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code
 &lt;activity&gt;}</a> elements or the <a
 href="{@docRoot}guide/topics/manifest/application-element.html">{@code &lt;application&gt;}</a>
 element. You can alternatively disable hardware acceleration for individual views by calling {@link
 android.view.View#setLayerType setLayerType(LAYER_TYPE_SOFTWARE)}.</p>
 
+<p>For more information about hardware acceleration, including a list of unsupported drawing
+operations, see the <a href="{@docRoot}guide/topics/graphics/hardware-accel.html">Hardware
+Acceleration</a> document.</p>
+
+
 
 <h3 id="Jni">JNI Changes</h3>
 
-<p>In previous versions of Android, JNI local references weren’t indirect handles; we used direct
-pointers. This didn’t seem like a problem as long as we didn’t have a garbage collector that moves
-objects, but it was because it meant that it was possible to write buggy code that still seemed to
-work. In Android 4.0, we’ve moved to using indirect references so we can detect these bugs before we
-need third-party native code to be correct.</p>
+<p>In previous versions of Android, JNI local references weren’t indirect handles; Android used
+direct pointers. This wasn't a problem as long as the garbage collector didn't move objects, but it
+seemed to work because it made it possible to write buggy code. In Android 4.0, the system now uses
+indirect references in order to detect these bugs.</p>
 
-<p>The ins and outs of JNI local references are described in “Local and Global References” in
-<a href="{@docRoot}guide/practices/design/jni.html">JNI Tips</a>. In Android 4.0, <a
-href="http://android-developers.blogspot.com/2011/07/debugging-android-jni-with-checkjni.html">CheckJNI</a>
-has been
-enhanced to detect these errors. Watch the <a href=”http://android-developers.blogspot.com/”>Android
-Developers Blog</a> for an upcoming post about common errors with JNI references and how you can fix
-them.</p>
+<p>The ins and outs of JNI local references are described in “Local and Global References" in <a
+href="{@docRoot}guide/practices/design/jni.html">JNI Tips</a>. In Android 4.0, <a
+href="http://android-developers.blogspot.com/2011/07/debugging-android-jni-with-checkjni.html">
+CheckJNI</a> has been enhanced to detect these errors. Watch the <a
+href="http://android-developers.blogspot.com/">Android Developers Blog</a> for an upcoming post
+about common errors with JNI references and how you can fix them.</p>
 
 <p>This change in the JNI implementation only affects apps that target Android 4.0 by setting either
-the <a
-href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a> or
-<a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> to
-{@code “14”} or higher. If you’ve set these attributes to any lower
-value, then JNI local references will behave the same as in previous versions.</p>
+the <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code
+targetSdkVersion}</a> or <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code
+minSdkVersion}</a> to {@code “14"} or higher. If you’ve set these attributes to any lower value,
+then JNI local references behave the same as in previous versions.</p>
 
 
 
@@ -1521,7 +1624,7 @@
 <ul>
 <li>Updated V8 JavaScript compiler for faster performance</li>
 <li>Plus other notable enhancements carried over from <a
-href=”{@docRoot}sdk/android-3.0.html”>Android
+href="{@docRoot}sdk/android-3.0.html">Android
 3.0</a> are now available for handsets:
 <ul>
 <li>Support for fixed position elements on all pages</li>
@@ -1564,8 +1667,115 @@
 
 
 
+<h2 id="Honeycomb">Previous APIs</h2>
 
+<p>In addition to everything above, Android 4.0 naturally supports all APIs from previous releases.
+Because the Android 3.x (Honeycomb) platform is available only for large-screen devices, if you've
+been developing primarily for handsets, then you might not be aware of all the APIs added to Android
+in these recent releases.</p>
 
+<p>Here's a look at some of the most notable APIs you might have missed that are now available
+on handsets as well:</p>
+
+<dl>
+  <dt><a href="android-3.0.html">Android 3.0</a></dt>
+  <dd>
+    <ul>
+      <li>{@link android.app.Fragment}: A framework component that allows you to separate distinct
+elements of an activity into self-contained modules that define their own UI and lifecycle. See the
+<a href="{@docRoot}guide/topics/fundamentals/fragments.html">Fragments</a> developer guide.</li>
+      <li>{@link android.app.ActionBar}: A replacement for the traditional title bar at the top of
+the activity window. It includes the application logo in the left corner and provides a new
+interface for menu items. See the
+<a href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> developer guide.</li>
+      <li>{@link android.content.Loader}: A framework component that facilitates asynchronour
+loading of data in combination with UI components to dynamically load data without blocking the
+main thread. See the
+<a href="{@docRoot}guide/topics/fundamentals/loaders.html">Loaders</a> developer guide.</li>
+      <li>System clipboard: Applications can copy and paste data (beyond mere text) to and from
+the system-wide clipboard. Clipped data can be plain text, a URI, or an intent. See the
+<a href="{@docRoot}guide/topics/clipboard/copy-paste.html">Copy and Paste</a> developer guide.</li>
+      <li>Drag and drop: A set of APIs built into the view framework that facilitates drag and drop
+operations. See the
+<a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</li>
+      <li>An all new flexible animation framework allows you to animate arbitrary properties of any
+object (View, Drawable, Fragment, Object, or anything else) and define animation aspects such
+as duration, interpolation, repeat and more. The new framework makes Animations in Android
+simpler than ever. See the
+<a href="{@docRoot}guide/topics/graphics/property-animation.html">Property Animation</a> developer
+guide.</li>
+      <li>RenderScript graphics and compute engine: RenderScript offers a high performance 3D
+graphics rendering and compute API at the native level, which you write in the C (C99 standard),
+providing the type of performance you expect from a native environment while remaining portable
+across various CPUs and GPUs. See the
+<a href="{@docRoot}guide/topics/renderscript/index.html">RenderScript</a> developer
+guide.</li>
+      <li>Hardware accelerated 2D graphics: You can now enable the OpenGL renderer for your
+application by setting {android:hardwareAccelerated="true"} in your manifest element's <a
+href="{@docRoot}guide/topics/manifest/application-element.html"><code>&lt;application&gt;</code></a>
+element or for individual <a
+href="{@docRoot}guide/topics/manifest/activity-element.html"><code>&lt;activity&gt;</code></a>
+elements. This results
+in smoother animations, smoother scrolling, and overall better performance and response to user
+interaction.
+      <p class="note"><strong>Note:</strong> If you set your application's <a
+href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> or <a
+href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a> to
+{@code "14"} or higher, hardware acceleration is enabled by default.</p></li>
+      <li>And much, much more. See the <a href="android-3.0.html">Android 3.0 Platform</a>
+notes for more information.</li>
+    </ul>
+  </dd>
+  
+  <dt><a href="android-3.1.html">Android 3.1</a></dt>
+  <dd>
+    <ul>
+      <li>USB APIs: Powerful new APIs for integrating connected peripherals with
+Android applications. The APIs are based on a USB stack and services that are
+built into the platform, including support for both USB host and device interactions. See the <a
+href="{@docRoot}guide/topics/usb/index.html">USB Host and Accessory</a> developer guide.</li>
+      <li>MTP/PTP APIs: Applications can interact directly with connected cameras and other PTP
+devices to receive notifications when devices are attached and removed, manage files and storage on
+those devices, and transfer files and metadata to and from them. The MTP API implements the PTP
+(Picture Transfer Protocol) subset of the MTP (Media Transfer Protocol) specification. See the
+{@link android.mtp} documentation.</li>
+      <li>RTP APIs: Android exposes an API to its built-in RTP (Real-time Transport Protocol) stack,
+which applications can use to manage on-demand or interactive data streaming. In particular, apps
+that provide VOIP, push-to-talk, conferencing, and audio streaming can use the API to initiate
+sessions and transmit or receive data streams over any available network. See the {@link
+android.net.rtp} documentation.</li>
+      <li>Support for joysticks and other generic motion inputs.</li>
+      <li>See the <a href="android-3.1.html">Android 3.1 Platform</a>
+notes for many more new APIs.</li>
+    </ul>
+  </dd>
+  
+  <dt><a href="android-3.2.html">Android 3.2</a></dt>
+  <dd>
+    <ul>
+      <li>New screens support APIs that give you more control over how your applications are
+displayed across different screen sizes. The API extends the existing screen support model with the
+ability to precisely target specific screen size ranges by dimensions, measured in
+density-independent pixel units (such as 600dp or 720dp wide), rather than by their generalized
+screen sizes (such as large or xlarge). For example, this is important in order to help you
+distinguish between a 5" device and a 7" device, which would both traditionally be bucketed as
+"large" screens. See the blog post, <a
+href="http://android-developers.blogspot.com/2011/07/new-tools-for-managing-screen-sizes.html">
+New Tools for Managing Screen Sizes</a>.</li>
+      <li>New constants for <a
+href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code &lt;uses-feature&gt;}</a> to
+declare landscape or portrait screen orientation requirements.</li>
+      <li>The device "screen size" configuration now changes during a screen orientation
+change. If your app targets API level 13 or higher, you must handle the {@code "screenSize"}
+configuration change if you also want to handle the {@code "orientation"} configuration change. See
+<a href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
+android:configChanges}</a> for more information.</li>
+      <li>See the <a href="android-3.2.html">Android 3.2 Platform</a>
+notes for other new APIs.</li>
+    </ul>
+  </dd>
+
+</dl>
 
 
 
@@ -1574,32 +1784,28 @@
 
 <h2 id="api-diff">API Differences Report</h2>
 
-<p>For a detailed view of all API changes in Android {@sdkPlatformVersion} (API
-Level
+<p>For a detailed view of all API changes in Android {@sdkPlatformVersion} (API Level
 {@sdkPlatformApiLevel}), see the <a
-href="{@docRoot}sdk/api_diff/{@sdkPlatformApiLevel}/changes.html">API
-Differences Report</a>.</p>
-
-
+href="{@docRoot}sdk/api_diff/{@sdkPlatformApiLevel}/changes.html">API Differences Report</a>.</p>
 
 
 
 <h2 id="api-level">API Level</h2>
 
-<p>The Android {@sdkPlatformVersion} platform delivers an updated version of the framework API. The
-Android {@sdkPlatformVersion} API is assigned an integer identifier &mdash;
-<strong>{@sdkPlatformApiLevel}</strong> &mdash; that is stored in the system itself. This
-identifier, called the "API Level", allows the system to correctly determine whether an application
-is compatible with the system, prior to installing the application. </p>
+<p>The Android {@sdkPlatformVersion} API is assigned an integer
+identifier&mdash;<strong>{@sdkPlatformApiLevel}</strong>&mdash;that is stored in the system itself.
+This identifier, called the "API level", allows the system to correctly determine whether an
+application is compatible with the system, prior to installing the application. </p>
 
 <p>To use APIs introduced in Android {@sdkPlatformVersion} in your application, you need compile the
-application against the Android library that is provided in the Android {@sdkPlatformVersion} SDK
-platform. Depending on your needs, you might also need to add an
+application against an Android platform that supports API level {@sdkPlatformApiLevel} or
+higher. Depending on your needs, you might also need to add an
 <code>android:minSdkVersion="{@sdkPlatformApiLevel}"</code> attribute to the
-<code>&lt;uses-sdk&gt;</code> element in the application's manifest.</p>
+<a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">{@code &lt;uses-sdk&gt;}</a>
+element.</p>
 
-<p>For more information about how to use API Level, see the <a
-href="{@docRoot}guide/appendix/api-levels.html">API Levels</a> document. </p>
+<p>For more information, see the <a href="{@docRoot}guide/appendix/api-levels.html">API Levels</a>
+document. </p>
 
 
 <h2 id="apps">Built-in Applications</h2>
@@ -1614,6 +1820,7 @@
 <li>API Demos</li>
 <li>Browser</li>
 <li>Calculator</li>
+<li>Calendar</li>
 <li>Camera</li>
 <li>Clock</li>
 <li>Custom Locale</li>
@@ -1632,7 +1839,7 @@
 <li>Phone</li>
 <li>Search</li>
 <li>Settings</li>
-<li>Spare Parts</li>
+<li>Speech Recorder</li>
 <li>Speech Recorder</li>
 <li>Widget Preview</li>
 </ul>
@@ -1643,13 +1850,10 @@
 
 <h2 id="locs" style="margin-top:.75em;">Locales</h2>
 
-<p>The system image included in the downloadable SDK platform provides a variety
-of
-built-in locales. In some cases, region-specific strings are available for the
-locales. In other cases, a default version of the language is used. The
-languages that are available in the Android 3.0 system
-image are listed below (with <em>language</em>_<em>country/region</em> locale
-descriptor).</p>
+<p>The system image included in the downloadable SDK platform provides a variety of built-in
+locales. In some cases, region-specific strings are available for the locales. In other cases, a
+default version of the language is used. The languages that are available in the Android 3.0 system
+image are listed below (with <em>language</em>_<em>country/region</em> locale descriptor).</p>
 
 <table style="border:0;padding-bottom:0;margin-bottom:0;">
 <tr>
@@ -1726,15 +1930,45 @@
 
 <h2 id="skins">Emulator Skins</h2>
 
-<p>The downloadable platform includes the following emulator skin:</p>
+<p>The downloadable platform includes the following emulator skins:</p>
 
 <ul>
   <li>
-    WVGA800 (1280x800, extra high density, normal screen)
+    QVGA (240x320, low density, small screen)
+  </li>
+  <li>
+    WQVGA400 (240x400, low density, normal screen)
+  </li>
+  <li>
+    WQVGA432 (240x432, low density, normal screen)
+  </li>
+  <li>
+    HVGA (320x480, medium density, normal screen)
+  </li>
+  <li>
+    WVGA800 (480x800, high density, normal screen)
+  </li>
+  <li>
+    WVGA854 (480x854 high density, normal screen)
+  </li>
+  <li>
+    WXGA720 (1280x720, extra-high density, normal screen) <span class="new">new</span>
+  </li>
+  <li>
+    WSVGA (1024x600, medium density, large screen) <span class="new">new</span>
+  </li>
+  <li>
+    WXGA (1280x800, medium density, xlarge screen)
   </li>
 </ul>
 
-<p>For more information about how to develop an application that displays
-and functions properly on all Android-powered devices, see <a
-href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
-Screens</a>.</p>
+<p>To test your application on an emulator that represents the latest Android device, you can create
+an AVD with the new WXGA720 skin (it's an xhdpi, normal screen device). Note that the emulator
+currently doesn't support the new on-screen navigation bar for devices without hardware navigation
+buttons, so when using this skin, you must use keyboard keys <em>Home</em> for the Home button,
+<em>ESC</em> for the Back button, and <em>F2</em> or <em>Page-up</em> for the Menu button.</p>
+
+<p>However, due to performance issues in the emulator when running high-resolution screens such as
+the one for the WXGA720 skin, we recommend that you primarily use the traditional WVGA800 skin
+(hdpi, normal screen) to test your application.</p>
+
diff --git a/docs/html/sdk/eclipse-adt.jd b/docs/html/sdk/eclipse-adt.jd
index 333efa2..59675a8 100644
--- a/docs/html/sdk/eclipse-adt.jd
+++ b/docs/html/sdk/eclipse-adt.jd
@@ -1,8 +1,8 @@
 page.title=ADT Plugin for Eclipse
 adt.zip.version=14.0.0
 adt.zip.download=ADT-14.0.0.zip
-adt.zip.bytes=6745584
-adt.zip.checksum=a645330d90fd9dae6187662bb1c3c644
+adt.zip.bytes=6747816
+adt.zip.checksum=3883973cd229dc4336911117af949509
 
 @jd:body
 
@@ -66,6 +66,9 @@
 <p>The sections below provide notes about successive releases of
 the ADT Plugin, as denoted by revision number. </p>
 
+<p>For a summary of all known issues in ADT, see <a
+href="http://tools.android.com/release/knownissues">http://tools.android.com/release/knownissues</a>.</p>
+
 <script type="text/javascript">
 function toggleDiv(link) {
   var toggleable = $(link).parent();
diff --git a/docs/html/sdk/index.jd b/docs/html/sdk/index.jd
index 065f41b..82db803 100644
--- a/docs/html/sdk/index.jd
+++ b/docs/html/sdk/index.jd
@@ -2,20 +2,20 @@
 sdk.redirect=0
 
 sdk.win_installer=installer_r14-windows.exe
-sdk.win_installer_bytes=33860145
-sdk.win_installer_checksum=7a563491bf4671d09b9da0dcde85f212
+sdk.win_installer_bytes=33853391
+sdk.win_installer_checksum=4f1cb329a41328c2cee2908b31ae6f6b
 
 sdk.win_download=android-sdk_r14-windows.zip
-sdk.win_bytes=33852972
-sdk.win_checksum=d1381a0cc8e6f9358174aa6d051ba379
+sdk.win_bytes=33846273
+sdk.win_checksum=48d44ae4cfcadede68621acb53caee80
 
 sdk.mac_download=android-sdk_r14-macosx.zip
-sdk.mac_bytes=30426052
-sdk.mac_checksum=df0a5c5b5327ffcaf256ce735998e12a
+sdk.mac_bytes=30428734
+sdk.mac_checksum=812887018435382de8486f3bb26a5db4
 
 sdk.linux_download=android-sdk_r14-linux.tgz
-sdk.linux_bytes=26083315
-sdk.linux_checksum=2049d5c1a164fcae47a5e93c52200752
+sdk.linux_bytes=26075938
+sdk.linux_checksum=35c989ff67184766dc4960813ede8ab5
 
 @jd:body
 
diff --git a/docs/html/sdk/tools-notes.jd b/docs/html/sdk/tools-notes.jd
index 2d044ed..f5b61ee 100644
--- a/docs/html/sdk/tools-notes.jd
+++ b/docs/html/sdk/tools-notes.jd
@@ -23,6 +23,9 @@
 Tools you are using, refer to the "Installed Packages" listing in the Android SDK
 and AVD Manager. </p>
 
+<p>For a summary of all known issues in SDK Tools, see <a
+href="http://tools.android.com/release/knownissues">http://tools.android.com/release/knownissues</a>.</p>
+
 <script type="text/javascript">
 function toggleDiv(link) {
   var toggleable = $(link).parent();
@@ -66,7 +69,12 @@
   <a href="#" onclick="return toggleDiv(this)">
     <img src="{@docRoot}assets/images/triangle-opened.png" class="toggle-img" height="9px"
     width="9px" />SDK Tools, Revision 14</a> <em>(October 2011)</em>
+
   <div class="toggleme">
+    <p class="note"><strong>Important:</strong> To download the new Android
+    4.0 system components from the Android SDK Manager, you must first update the
+    SDK tools to revision 14 and restart the Android SDK Manager. If you do not,
+    the Android 4.0 system components will not be available for download.</p>
   <dl>
 <dt>Dependencies:</dt>
 <dd>
@@ -81,6 +89,9 @@
 <dt>General notes:</dt>
 <dd>
   <ul>
+    <li>Added webcam support to Android 4.0 or later platforms to emulate rear-facing cameras when one webcam is present,
+    and to emulate both rear-facing and front-facing cameras when two webcams are present. Webcam suport is for Windows and Linux only.
+    Mac support will come in a later release.</li>
      <li>Changed <code>default.properties</code> to <code>project.properties</code> and
     <code>build.properties</code> to <code>ant.properties</code>. Any existing
     projects that you build with Ant must be updated with the <code>android update project</code>
@@ -90,7 +101,6 @@
 commands, see the
 <a href="{@docRoot}guide/developing/building/building-cmdline.html#AntReference">Ant Command
 Reference</a>.</li>
-
     <li>Changed how library projects are built.</a></li>
     <li>Improved incremental builds, so that resource compilation runs less frequently. Builds no
     longer run when you edit strings or layouts (unless you add a new <code>id</code>) and no longer
diff --git a/include/binder/CursorWindow.h b/include/binder/CursorWindow.h
index 5d490ed..f0284de 100644
--- a/include/binder/CursorWindow.h
+++ b/include/binder/CursorWindow.h
@@ -80,8 +80,7 @@
 
     ~CursorWindow();
 
-    static status_t create(const String8& name, size_t size, bool localOnly,
-            CursorWindow** outCursorWindow);
+    static status_t create(const String8& name, size_t size, CursorWindow** outCursorWindow);
     static status_t createFromParcel(Parcel* parcel, CursorWindow** outCursorWindow);
 
     status_t writeToParcel(Parcel* parcel);
diff --git a/include/camera/CameraParameters.h b/include/camera/CameraParameters.h
index cd2c0a3..ef4cf5c 100644
--- a/include/camera/CameraParameters.h
+++ b/include/camera/CameraParameters.h
@@ -283,7 +283,8 @@
     // outside the current field of view, even when using zoom.
     //
     // Focus area only has effect if the current focus mode is FOCUS_MODE_AUTO,
-    // FOCUS_MODE_MACRO, or FOCUS_MODE_CONTINOUS_VIDEO.
+    // FOCUS_MODE_MACRO, FOCUS_MODE_CONTINUOUS_VIDEO, or
+    // FOCUS_MODE_CONTINUOUS_PICTURE.
     // Example value: "(-10,-10,0,0,300),(0,0,10,10,700)". Read/write.
     static const char KEY_FOCUS_AREAS[];
     // Focal length in millimeter.
@@ -629,19 +630,29 @@
     // recording because the focus changes smoothly . Applications still can
     // call CameraHardwareInterface.takePicture in this mode but the subject may
     // not be in focus. Auto focus starts when the parameter is set.
-    // Applications should not call CameraHardwareInterface.autoFocus in this
-    // mode. To stop continuous focus, applications should change the focus mode
-    // to other modes.
+    //
+    // Applications can call CameraHardwareInterface.autoFocus in this mode. The
+    // focus callback will immediately return with a boolean that indicates
+    // whether the focus is sharp or not. The focus position is locked after
+    // autoFocus call. If applications want to resume the continuous focus,
+    // cancelAutoFocus must be called. Restarting the preview will not resume
+    // the continuous autofocus. To stop continuous focus, applications should
+    // change the focus mode to other modes.
     static const char FOCUS_MODE_CONTINUOUS_VIDEO[];
     // Continuous auto focus mode intended for taking pictures. The camera
     // continuously tries to focus. The speed of focus change is more aggressive
     // than FOCUS_MODE_CONTINUOUS_VIDEO. Auto focus starts when the parameter is
-    // set. If applications call autoFocus in this mode, the focus callback will
-    // immediately return with a boolean that indicates the focus is sharp or
-    // not. The apps can then decide if they want to take a picture immediately
-    // or to change the focus mode to auto, and run a full autofocus cycle. To
-    // stop continuous focus, applications should change the focus mode to other
-    // modes.
+    // set.
+    //
+    // If applications call CameraHardwareInterface.autoFocus in this mode, the
+    // focus callback will immediately return with a boolean that indicates
+    // whether the focus is sharp or not. The apps can then decide if they want
+    // to take a picture immediately or to change the focus mode to auto, and
+    // run a full autofocus cycle. The focus position is locked after autoFocus
+    // call. If applications want to resume the continuous focus,
+    // cancelAutoFocus must be called. Restarting the preview will not resume
+    // the continuous autofocus. To stop continuous focus, applications should
+    // change the focus mode to other modes.
     static const char FOCUS_MODE_CONTINUOUS_PICTURE[];
 
 private:
diff --git a/include/gui/SensorManager.h b/include/gui/SensorManager.h
index e1b1a7be..3176462 100644
--- a/include/gui/SensorManager.h
+++ b/include/gui/SensorManager.h
@@ -20,6 +20,8 @@
 #include <stdint.h>
 #include <sys/types.h>
 
+#include <binder/IBinder.h>
+
 #include <utils/Errors.h>
 #include <utils/RefBase.h>
 #include <utils/Singleton.h>
@@ -41,7 +43,9 @@
 
 // ----------------------------------------------------------------------------
 
-class SensorManager : public ASensorManager, public Singleton<SensorManager>
+class SensorManager :
+    public ASensorManager,
+    public Singleton<SensorManager>
 {
 public:
     SensorManager();
@@ -52,9 +56,17 @@
     sp<SensorEventQueue> createEventQueue();
 
 private:
-    sp<ISensorServer> mSensorServer;
-    Sensor const** mSensorList;
-    Vector<Sensor> mSensors;
+    // DeathRecipient interface
+    void sensorManagerDied();
+
+    status_t assertStateLocked() const;
+
+private:
+    mutable Mutex mLock;
+    mutable sp<ISensorServer> mSensorServer;
+    mutable Sensor const** mSensorList;
+    mutable Vector<Sensor> mSensors;
+    mutable sp<IBinder::DeathRecipient> mDeathObserver;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/media/stagefright/MediaDefs.h b/include/media/stagefright/MediaDefs.h
index 3e48459..2eb259e 100644
--- a/include/media/stagefright/MediaDefs.h
+++ b/include/media/stagefright/MediaDefs.h
@@ -31,7 +31,9 @@
 
 extern const char *MEDIA_MIMETYPE_AUDIO_AMR_NB;
 extern const char *MEDIA_MIMETYPE_AUDIO_AMR_WB;
-extern const char *MEDIA_MIMETYPE_AUDIO_MPEG;
+extern const char *MEDIA_MIMETYPE_AUDIO_MPEG;           // layer III
+extern const char *MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I;
+extern const char *MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II;
 extern const char *MEDIA_MIMETYPE_AUDIO_AAC;
 extern const char *MEDIA_MIMETYPE_AUDIO_QCELP;
 extern const char *MEDIA_MIMETYPE_AUDIO_VORBIS;
@@ -47,6 +49,7 @@
 extern const char *MEDIA_MIMETYPE_CONTAINER_MATROSKA;
 extern const char *MEDIA_MIMETYPE_CONTAINER_MPEG2TS;
 extern const char *MEDIA_MIMETYPE_CONTAINER_AVI;
+extern const char *MEDIA_MIMETYPE_CONTAINER_MPEG2PS;
 
 extern const char *MEDIA_MIMETYPE_CONTAINER_WVM;
 
diff --git a/include/surfaceflinger/ISurfaceComposer.h b/include/surfaceflinger/ISurfaceComposer.h
index ea022a6..1242e49 100644
--- a/include/surfaceflinger/ISurfaceComposer.h
+++ b/include/surfaceflinger/ISurfaceComposer.h
@@ -83,7 +83,11 @@
         eOrientationUnchanged   = 4,
         eOrientationSwapMask    = 0x01
     };
-    
+
+    enum {
+        eSynchronous            = 0x01,
+    };
+
     enum {
         eElectronBeamAnimationOn  = 0x01,
         eElectronBeamAnimationOff = 0x10
@@ -103,7 +107,7 @@
 
     /* open/close transactions. requires ACCESS_SURFACE_FLINGER permission */
     virtual void setTransactionState(const Vector<ComposerState>& state,
-            int orientation) = 0;
+            int orientation, uint32_t flags) = 0;
 
     /* signal that we're done booting.
      * Requires ACCESS_SURFACE_FLINGER permission
@@ -142,8 +146,6 @@
         GET_CBLK,
         SET_TRANSACTION_STATE,
         SET_ORIENTATION,
-        FREEZE_DISPLAY,
-        UNFREEZE_DISPLAY,
         CAPTURE_SCREEN,
         TURN_ELECTRON_BEAM_OFF,
         TURN_ELECTRON_BEAM_ON,
diff --git a/include/surfaceflinger/SurfaceComposerClient.h b/include/surfaceflinger/SurfaceComposerClient.h
index 14e5b23..8226abe 100644
--- a/include/surfaceflinger/SurfaceComposerClient.h
+++ b/include/surfaceflinger/SurfaceComposerClient.h
@@ -112,7 +112,7 @@
     static void openGlobalTransaction();
         
     //! Close a composer transaction on all active SurfaceComposerClients.
-    static void closeGlobalTransaction();
+    static void closeGlobalTransaction(bool synchronous = false);
     
     //! Freeze the specified display but not transactions.
     static status_t freezeDisplay(DisplayID dpy, uint32_t flags = 0);
diff --git a/libs/binder/CursorWindow.cpp b/libs/binder/CursorWindow.cpp
index 1b85a71..bf8d7a6 100644
--- a/libs/binder/CursorWindow.cpp
+++ b/libs/binder/CursorWindow.cpp
@@ -40,11 +40,9 @@
     ::close(mAshmemFd);
 }
 
-status_t CursorWindow::create(const String8& name, size_t size, bool localOnly,
-        CursorWindow** outCursorWindow) {
+status_t CursorWindow::create(const String8& name, size_t size, CursorWindow** outCursorWindow) {
     String8 ashmemName("CursorWindow: ");
     ashmemName.append(name);
-    ashmemName.append(localOnly ? " (local)" : " (remote)");
 
     status_t result;
     int ashmemFd = ashmem_create_region(ashmemName.string(), size);
diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp
index eb90147..86bc62a 100644
--- a/libs/gui/ISurfaceComposer.cpp
+++ b/libs/gui/ISurfaceComposer.cpp
@@ -79,7 +79,7 @@
     }
 
     virtual void setTransactionState(const Vector<ComposerState>& state,
-            int orientation)
+            int orientation, uint32_t flags)
     {
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
@@ -90,6 +90,7 @@
             b->write(data);
         }
         data.writeInt32(orientation);
+        data.writeInt32(flags);
         remote()->transact(BnSurfaceComposer::SET_TRANSACTION_STATE, data, &reply);
     }
 
@@ -204,7 +205,8 @@
                 state.add(s);
             }
             int orientation = data.readInt32();
-            setTransactionState(state, orientation);
+            uint32_t flags = data.readInt32();
+            setTransactionState(state, orientation, flags);
         } break;
         case BOOT_FINISHED: {
             CHECK_INTERFACE(ISurfaceComposer, data, reply);
diff --git a/libs/gui/ISurfaceTexture.cpp b/libs/gui/ISurfaceTexture.cpp
index babd2c0..d2e5627 100644
--- a/libs/gui/ISurfaceTexture.cpp
+++ b/libs/gui/ISurfaceTexture.cpp
@@ -58,13 +58,16 @@
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
         data.writeInt32(bufferIdx);
-        remote()->transact(REQUEST_BUFFER, data, &reply);
+        status_t result =remote()->transact(REQUEST_BUFFER, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
         bool nonNull = reply.readInt32();
         if (nonNull) {
             *buf = new GraphicBuffer();
             reply.read(**buf);
         }
-        status_t result = reply.readInt32();
+        result = reply.readInt32();
         return result;
     }
 
@@ -73,9 +76,12 @@
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
         data.writeInt32(bufferCount);
-        remote()->transact(SET_BUFFER_COUNT, data, &reply);
-        status_t err = reply.readInt32();
-        return err;
+        status_t result =remote()->transact(SET_BUFFER_COUNT, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
+        result = reply.readInt32();
+        return result;
     }
 
     virtual status_t dequeueBuffer(int *buf, uint32_t w, uint32_t h,
@@ -86,9 +92,12 @@
         data.writeInt32(h);
         data.writeInt32(format);
         data.writeInt32(usage);
-        remote()->transact(DEQUEUE_BUFFER, data, &reply);
+        status_t result = remote()->transact(DEQUEUE_BUFFER, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
         *buf = reply.readInt32();
-        int result = reply.readInt32();
+        result = reply.readInt32();
         return result;
     }
 
@@ -98,11 +107,14 @@
         data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
         data.writeInt32(buf);
         data.writeInt64(timestamp);
-        remote()->transact(QUEUE_BUFFER, data, &reply);
+        status_t result = remote()->transact(QUEUE_BUFFER, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
         *outWidth = reply.readInt32();
         *outHeight = reply.readInt32();
         *outTransform = reply.readInt32();
-        status_t result = reply.readInt32();
+        result = reply.readInt32();
         return result;
     }
 
@@ -120,8 +132,11 @@
         data.writeFloat(reg.top);
         data.writeFloat(reg.right);
         data.writeFloat(reg.bottom);
-        remote()->transact(SET_CROP, data, &reply);
-        status_t result = reply.readInt32();
+        status_t result = remote()->transact(SET_CROP, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
+        result = reply.readInt32();
         return result;
     }
 
@@ -129,8 +144,11 @@
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
         data.writeInt32(transform);
-        remote()->transact(SET_TRANSFORM, data, &reply);
-        status_t result = reply.readInt32();
+        status_t result = remote()->transact(SET_TRANSFORM, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
+        result = reply.readInt32();
         return result;
     }
 
@@ -138,8 +156,11 @@
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
         data.writeInt32(mode);
-        remote()->transact(SET_SCALING_MODE, data, &reply);
-        status_t result = reply.readInt32();
+        status_t result = remote()->transact(SET_SCALING_MODE, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
+        result = reply.readInt32();
         return result;
     }
 
@@ -147,9 +168,12 @@
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
         data.writeInt32(what);
-        remote()->transact(QUERY, data, &reply);
+        status_t result = remote()->transact(QUERY, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
         value[0] = reply.readInt32();
-        status_t result = reply.readInt32();
+        result = reply.readInt32();
         return result;
     }
 
@@ -157,8 +181,11 @@
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
         data.writeInt32(enabled);
-        remote()->transact(SET_SYNCHRONOUS_MODE, data, &reply);
-        status_t result = reply.readInt32();
+        status_t result = remote()->transact(SET_SYNCHRONOUS_MODE, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
+        result = reply.readInt32();
         return result;
     }
 
@@ -167,11 +194,14 @@
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
         data.writeInt32(api);
-        remote()->transact(CONNECT, data, &reply);
+        status_t result = remote()->transact(CONNECT, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
         *outWidth = reply.readInt32();
         *outHeight = reply.readInt32();
         *outTransform = reply.readInt32();
-        status_t result = reply.readInt32();
+        result = reply.readInt32();
         return result;
     }
 
@@ -179,8 +209,11 @@
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
         data.writeInt32(api);
-        remote()->transact(DISCONNECT, data, &reply);
-        status_t result = reply.readInt32();
+        status_t result =remote()->transact(DISCONNECT, data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
+        result = reply.readInt32();
         return result;
     }
 };
diff --git a/libs/gui/SensorManager.cpp b/libs/gui/SensorManager.cpp
index d719efb..dafcdea 100644
--- a/libs/gui/SensorManager.cpp
+++ b/libs/gui/SensorManager.cpp
@@ -23,6 +23,7 @@
 #include <utils/RefBase.h>
 #include <utils/Singleton.h>
 
+#include <binder/IBinder.h>
 #include <binder/IServiceManager.h>
 
 #include <gui/ISensorServer.h>
@@ -40,17 +41,8 @@
 SensorManager::SensorManager()
     : mSensorList(0)
 {
-    const String16 name("sensorservice");
-    while (getService(name, &mSensorServer) != NO_ERROR) {
-        usleep(250000);
-    }
-
-    mSensors = mSensorServer->getSensorList();
-    size_t count = mSensors.size();
-    mSensorList = (Sensor const**)malloc(count * sizeof(Sensor*));
-    for (size_t i=0 ; i<count ; i++) {
-        mSensorList[i] = mSensors.array() + i;
-    }
+    // okay we're not locked here, but it's not needed during construction
+    assertStateLocked();
 }
 
 SensorManager::~SensorManager()
@@ -58,29 +50,100 @@
     free(mSensorList);
 }
 
+void SensorManager::sensorManagerDied()
+{
+    Mutex::Autolock _l(mLock);
+    mSensorServer.clear();
+    free(mSensorList);
+    mSensorList = NULL;
+    mSensors.clear();
+}
+
+status_t SensorManager::assertStateLocked() const {
+    if (mSensorServer == NULL) {
+        // try for one second
+        const String16 name("sensorservice");
+        for (int i=0 ; i<4 ; i++) {
+            status_t err = getService(name, &mSensorServer);
+            if (err == NAME_NOT_FOUND) {
+                usleep(250000);
+                continue;
+            }
+            if (err != NO_ERROR) {
+                return err;
+            }
+            break;
+        }
+
+        class DeathObserver : public IBinder::DeathRecipient {
+            SensorManager& mSensorManger;
+            virtual void binderDied(const wp<IBinder>& who) {
+                LOGW("sensorservice died [%p]", who.unsafe_get());
+                mSensorManger.sensorManagerDied();
+            }
+        public:
+            DeathObserver(SensorManager& mgr) : mSensorManger(mgr) { }
+        };
+
+        mDeathObserver = new DeathObserver(*const_cast<SensorManager *>(this));
+        mSensorServer->asBinder()->linkToDeath(mDeathObserver);
+
+        mSensors = mSensorServer->getSensorList();
+        size_t count = mSensors.size();
+        mSensorList = (Sensor const**)malloc(count * sizeof(Sensor*));
+        for (size_t i=0 ; i<count ; i++) {
+            mSensorList[i] = mSensors.array() + i;
+        }
+    }
+
+    return NO_ERROR;
+}
+
+
+
 ssize_t SensorManager::getSensorList(Sensor const* const** list) const
 {
+    Mutex::Autolock _l(mLock);
+    status_t err = assertStateLocked();
+    if (err < 0) {
+        return ssize_t(err);
+    }
     *list = mSensorList;
     return mSensors.size();
 }
 
 Sensor const* SensorManager::getDefaultSensor(int type)
 {
-    // For now we just return the first sensor of that type we find.
-    // in the future it will make sense to let the SensorService make
-    // that decision.
-    for (size_t i=0 ; i<mSensors.size() ; i++) {
-        if (mSensorList[i]->getType() == type)
-            return mSensorList[i];
+    Mutex::Autolock _l(mLock);
+    if (assertStateLocked() == NO_ERROR) {
+        // For now we just return the first sensor of that type we find.
+        // in the future it will make sense to let the SensorService make
+        // that decision.
+        for (size_t i=0 ; i<mSensors.size() ; i++) {
+            if (mSensorList[i]->getType() == type)
+                return mSensorList[i];
+        }
     }
     return NULL;
 }
 
 sp<SensorEventQueue> SensorManager::createEventQueue()
 {
-    sp<SensorEventQueue> result = new SensorEventQueue(
-            mSensorServer->createSensorEventConnection());
-    return result;
+    sp<SensorEventQueue> queue;
+
+    Mutex::Autolock _l(mLock);
+    while (assertStateLocked() == NO_ERROR) {
+        sp<ISensorEventConnection> connection =
+                mSensorServer->createSensorEventConnection();
+        if (connection == NULL) {
+            // SensorService just died.
+            LOGE("createEventQueue: connection is NULL. SensorService died.");
+            continue;
+        }
+        queue = new SensorEventQueue(connection);
+        break;
+    }
+    return queue;
 }
 
 // ----------------------------------------------------------------------------
diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp
index 5f3d608..4ad6c22 100644
--- a/libs/gui/SurfaceComposerClient.cpp
+++ b/libs/gui/SurfaceComposerClient.cpp
@@ -92,11 +92,14 @@
     mutable Mutex               mLock;
     SortedVector<ComposerState> mStates;
     int                         mOrientation;
+    uint32_t                    mForceSynchronous;
 
     Composer() : Singleton<Composer>(),
-        mOrientation(ISurfaceComposer::eOrientationUnchanged) { }
+        mOrientation(ISurfaceComposer::eOrientationUnchanged),
+        mForceSynchronous(0)
+    { }
 
-    void closeGlobalTransactionImpl();
+    void closeGlobalTransactionImpl(bool synchronous);
 
     layer_state_t* getLayerStateLocked(
             const sp<SurfaceComposerClient>& client, SurfaceID id);
@@ -123,8 +126,8 @@
             uint32_t tint);
     status_t setOrientation(int orientation);
 
-    static void closeGlobalTransaction() {
-        Composer::getInstance().closeGlobalTransactionImpl();
+    static void closeGlobalTransaction(bool synchronous) {
+        Composer::getInstance().closeGlobalTransactionImpl(synchronous);
     }
 };
 
@@ -132,11 +135,12 @@
 
 // ---------------------------------------------------------------------------
 
-void Composer::closeGlobalTransactionImpl() {
+void Composer::closeGlobalTransactionImpl(bool synchronous) {
     sp<ISurfaceComposer> sm(getComposerService());
 
     Vector<ComposerState> transaction;
     int orientation;
+    uint32_t flags = 0;
 
     { // scope for the lock
         Mutex::Autolock _l(mLock);
@@ -145,9 +149,14 @@
 
         orientation = mOrientation;
         mOrientation = ISurfaceComposer::eOrientationUnchanged;
+
+        if (synchronous || mForceSynchronous) {
+            flags |= ISurfaceComposer::eSynchronous;
+        }
+        mForceSynchronous = false;
     }
 
-   sm->setTransactionState(transaction, orientation);
+   sm->setTransactionState(transaction, orientation, flags);
 }
 
 layer_state_t* Composer::getLayerStateLocked(
@@ -188,6 +197,10 @@
     s->what |= ISurfaceComposer::eSizeChanged;
     s->w = w;
     s->h = h;
+
+    // Resizing a surface makes the transaction synchronous.
+    mForceSynchronous = true;
+
     return NO_ERROR;
 }
 
@@ -270,6 +283,10 @@
 status_t Composer::setOrientation(int orientation) {
     Mutex::Autolock _l(mLock);
     mOrientation = orientation;
+
+    // Changing the orientation makes the transaction synchronous.
+    mForceSynchronous = true;
+
     return NO_ERROR;
 }
 
@@ -375,8 +392,8 @@
     // Currently a no-op
 }
 
-void SurfaceComposerClient::closeGlobalTransaction() {
-    Composer::closeGlobalTransaction();
+void SurfaceComposerClient::closeGlobalTransaction(bool synchronous) {
+    Composer::closeGlobalTransaction(synchronous);
 }
 
 // ----------------------------------------------------------------------------
diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp
index ce587b3..693b7b8 100644
--- a/libs/gui/tests/Surface_test.cpp
+++ b/libs/gui/tests/Surface_test.cpp
@@ -75,7 +75,7 @@
 }
 
 // This test probably doesn't belong here.
-TEST_F(SurfaceTest, ScreenshotsOfProtectedBuffersFail) {
+TEST_F(SurfaceTest, ScreenshotsOfProtectedBuffersSucceed) {
     sp<ANativeWindow> anw(mSurface);
 
     // Verify the screenshot works with no protected buffers.
@@ -114,31 +114,8 @@
     }
     heap = 0;
     w = h = fmt = 0;
-    ASSERT_EQ(INVALID_OPERATION, sf->captureScreen(0, &heap, &w, &h, &fmt,
+    ASSERT_EQ(NO_ERROR, sf->captureScreen(0, &heap, &w, &h, &fmt,
             64, 64, 0, 0x7fffffff));
-    ASSERT_TRUE(heap == NULL);
-
-    // XXX: This should not be needed, but it seems that the new buffers don't
-    // correctly show up after the upcoming dequeue/lock/queue loop without it.
-    // We should look into this at some point.
-    ASSERT_EQ(NO_ERROR, native_window_set_buffer_count(anw.get(), 3));
-
-    // Un-set the PROTECTED usage bit and verify that the screenshot works
-    // again.  Note that we have to change the buffers geometry to ensure that
-    // the buffers get reallocated, as the new usage bits are a subset of the
-    // old.
-    ASSERT_EQ(NO_ERROR, native_window_set_usage(anw.get(), 0));
-    ASSERT_EQ(NO_ERROR, native_window_set_buffers_geometry(anw.get(), 32, 32, 0));
-    for (int i = 0; i < 4; i++) {
-        // Loop to make sure SurfaceFlinger has retired a protected buffer.
-        ASSERT_EQ(NO_ERROR, anw->dequeueBuffer(anw.get(), &buf));
-        ASSERT_EQ(NO_ERROR, anw->lockBuffer(anw.get(), buf));
-        ASSERT_EQ(NO_ERROR, anw->queueBuffer(anw.get(), buf));
-    }
-    heap = 0;
-    w = h = fmt = 0;
-    ASSERT_EQ(NO_ERROR, sf->captureScreen(0, &heap, &w, &h, &fmt, 64, 64, 0,
-            0x7fffffff));
     ASSERT_TRUE(heap != NULL);
 }
 
diff --git a/libs/rs/driver/rsdBcc.cpp b/libs/rs/driver/rsdBcc.cpp
index 269703c..4ecf8e8 100644
--- a/libs/rs/driver/rsdBcc.cpp
+++ b/libs/rs/driver/rsdBcc.cpp
@@ -267,12 +267,12 @@
             return;
         }
 
-        //LOGE("usr idx %i, x %i,%i  y %i,%i", idx, mtls->xStart, mtls->xEnd, yStart, yEnd);
+        //LOGE("usr slice %i idx %i, x %i,%i", slice, idx, xStart, xEnd);
         //LOGE("usr ptr in %p,  out %p", mtls->ptrIn, mtls->ptrOut);
+
         p.out = mtls->ptrOut + (mtls->eStrideOut * xStart);
         p.in = mtls->ptrIn + (mtls->eStrideIn * xStart);
-        fn(&mtls->script->mHal.info.root, &p, mtls->xStart, mtls->xEnd,
-           mtls->eStrideIn, mtls->eStrideOut);
+        fn(&mtls->script->mHal.info.root, &p, xStart, xEnd, mtls->eStrideIn, mtls->eStrideOut);
     }
 }
 
diff --git a/libs/rs/rsContext.cpp b/libs/rs/rsContext.cpp
index 53d4970..2d51208 100644
--- a/libs/rs/rsContext.cpp
+++ b/libs/rs/rsContext.cpp
@@ -319,8 +319,12 @@
 
 void Context::printWatchdogInfo(void *ctx) {
     Context *rsc = (Context *)ctx;
-    LOGE("RS watchdog timeout: %i  %s  line %i %s", rsc->watchdog.inRoot,
-         rsc->watchdog.command, rsc->watchdog.line, rsc->watchdog.file);
+    if (rsc->watchdog.command && rsc->watchdog.file) {
+        LOGE("RS watchdog timeout: %i  %s  line %i %s", rsc->watchdog.inRoot,
+             rsc->watchdog.command, rsc->watchdog.line, rsc->watchdog.file);
+    } else {
+        LOGE("RS watchdog timeout: %i", rsc->watchdog.inRoot);
+    }
 }
 
 
diff --git a/libs/rs/rsProgramRaster.h b/libs/rs/rsProgramRaster.h
index 20af30a..c552ea3 100644
--- a/libs/rs/rsProgramRaster.h
+++ b/libs/rs/rsProgramRaster.h
@@ -24,17 +24,16 @@
 namespace renderscript {
 
 class ProgramRasterState;
-
+/*****************************************************************************
+ * CAUTION
+ *
+ * Any layout changes for this class may require a corresponding change to be
+ * made to frameworks/compile/libbcc/lib/ScriptCRT/rs_core.c, which contains
+ * a partial copy of the information below.
+ *
+ *****************************************************************************/
 class ProgramRaster : public ProgramBase {
 public:
-    virtual void setup(const Context *, ProgramRasterState *);
-    virtual void serialize(OStream *stream) const;
-    virtual RsA3DClassID getClassId() const { return RS_A3D_CLASS_ID_PROGRAM_RASTER; }
-    static ProgramRaster *createFromStream(Context *rsc, IStream *stream);
-
-    static ObjectBaseRef<ProgramRaster> getProgramRaster(Context *rsc,
-                                                         bool pointSprite,
-                                                         RsCullMode cull);
     struct Hal {
         mutable void *drv;
 
@@ -46,6 +45,14 @@
     };
     Hal mHal;
 
+    virtual void setup(const Context *, ProgramRasterState *);
+    virtual void serialize(OStream *stream) const;
+    virtual RsA3DClassID getClassId() const { return RS_A3D_CLASS_ID_PROGRAM_RASTER; }
+    static ProgramRaster *createFromStream(Context *rsc, IStream *stream);
+
+    static ObjectBaseRef<ProgramRaster> getProgramRaster(Context *rsc,
+                                                         bool pointSprite,
+                                                         RsCullMode cull);
 protected:
     virtual void preDestroy() const;
     virtual ~ProgramRaster();
diff --git a/libs/rs/rsProgramStore.h b/libs/rs/rsProgramStore.h
index e21f039..9bb2795 100644
--- a/libs/rs/rsProgramStore.h
+++ b/libs/rs/rsProgramStore.h
@@ -25,23 +25,16 @@
 namespace renderscript {
 
 class ProgramStoreState;
-
+/*****************************************************************************
+ * CAUTION
+ *
+ * Any layout changes for this class may require a corresponding change to be
+ * made to frameworks/compile/libbcc/lib/ScriptCRT/rs_core.c, which contains
+ * a partial copy of the information below.
+ *
+ *****************************************************************************/
 class ProgramStore : public ProgramBase {
 public:
-    virtual void setup(const Context *, ProgramStoreState *);
-
-    virtual void serialize(OStream *stream) const;
-    virtual RsA3DClassID getClassId() const { return RS_A3D_CLASS_ID_PROGRAM_STORE; }
-    static ProgramStore *createFromStream(Context *rsc, IStream *stream);
-    static ObjectBaseRef<ProgramStore> getProgramStore(Context *,
-                                                       bool colorMaskR, bool colorMaskG,
-                                                       bool colorMaskB, bool colorMaskA,
-                                                       bool depthMask, bool ditherEnable,
-                                                       RsBlendSrcFunc srcFunc, RsBlendDstFunc destFunc,
-                                                       RsDepthFunc depthFunc);
-
-    void init();
-
     struct Hal {
         mutable void *drv;
 
@@ -64,6 +57,18 @@
     };
     Hal mHal;
 
+    virtual void setup(const Context *, ProgramStoreState *);
+
+    virtual void serialize(OStream *stream) const;
+    virtual RsA3DClassID getClassId() const { return RS_A3D_CLASS_ID_PROGRAM_STORE; }
+    static ProgramStore *createFromStream(Context *rsc, IStream *stream);
+    static ObjectBaseRef<ProgramStore> getProgramStore(Context *,
+                                                       bool colorMaskR, bool colorMaskG,
+                                                       bool colorMaskB, bool colorMaskA,
+                                                       bool depthMask, bool ditherEnable,
+                                                       RsBlendSrcFunc srcFunc, RsBlendDstFunc destFunc,
+                                                       RsDepthFunc depthFunc);
+    void init();
 protected:
     virtual void preDestroy() const;
     virtual ~ProgramStore();
diff --git a/libs/rs/rsSampler.h b/libs/rs/rsSampler.h
index e698132..654cd9c 100644
--- a/libs/rs/rsSampler.h
+++ b/libs/rs/rsSampler.h
@@ -27,23 +27,16 @@
 const static uint32_t RS_MAX_SAMPLER_SLOT = 16;
 
 class SamplerState;
-
+/*****************************************************************************
+ * CAUTION
+ *
+ * Any layout changes for this class may require a corresponding change to be
+ * made to frameworks/compile/libbcc/lib/ScriptCRT/rs_core.c, which contains
+ * a partial copy of the information below.
+ *
+ *****************************************************************************/
 class Sampler : public ObjectBase {
 public:
-    static ObjectBaseRef<Sampler> getSampler(Context *,
-                                             RsSamplerValue magFilter,
-                                             RsSamplerValue minFilter,
-                                             RsSamplerValue wrapS,
-                                             RsSamplerValue wrapT,
-                                             RsSamplerValue wrapR,
-                                             float aniso = 1.0f);
-    void bindToContext(SamplerState *, uint32_t slot);
-    void unbindFromContext(SamplerState *);
-
-    virtual void serialize(OStream *stream) const;
-    virtual RsA3DClassID getClassId() const { return RS_A3D_CLASS_ID_SAMPLER; }
-    static Sampler *createFromStream(Context *rsc, IStream *stream);
-
     struct Hal {
         mutable void *drv;
 
@@ -59,6 +52,20 @@
     };
     Hal mHal;
 
+    static ObjectBaseRef<Sampler> getSampler(Context *,
+                                             RsSamplerValue magFilter,
+                                             RsSamplerValue minFilter,
+                                             RsSamplerValue wrapS,
+                                             RsSamplerValue wrapT,
+                                             RsSamplerValue wrapR,
+                                             float aniso = 1.0f);
+    void bindToContext(SamplerState *, uint32_t slot);
+    void unbindFromContext(SamplerState *);
+
+    virtual void serialize(OStream *stream) const;
+    virtual RsA3DClassID getClassId() const { return RS_A3D_CLASS_ID_SAMPLER; }
+    static Sampler *createFromStream(Context *rsc, IStream *stream);
+
 protected:
     int32_t mBoundSlot;
 
diff --git a/libs/rs/scriptc/rs_graphics.rsh b/libs/rs/scriptc/rs_graphics.rsh
index 3e9339e..80267c7 100644
--- a/libs/rs/scriptc/rs_graphics.rsh
+++ b/libs/rs/scriptc/rs_graphics.rsh
@@ -23,6 +23,55 @@
 #ifndef __RS_GRAPHICS_RSH__
 #define __RS_GRAPHICS_RSH__
 
+// These are API 15 once it get official
+typedef enum {
+    RS_DEPTH_FUNC_ALWAYS,
+    RS_DEPTH_FUNC_LESS,
+    RS_DEPTH_FUNC_LEQUAL,
+    RS_DEPTH_FUNC_GREATER,
+    RS_DEPTH_FUNC_GEQUAL,
+    RS_DEPTH_FUNC_EQUAL,
+    RS_DEPTH_FUNC_NOTEQUAL
+} rs_depth_func;
+
+typedef enum {
+    RS_BLEND_SRC_ZERO,                  // 0
+    RS_BLEND_SRC_ONE,                   // 1
+    RS_BLEND_SRC_DST_COLOR,             // 2
+    RS_BLEND_SRC_ONE_MINUS_DST_COLOR,   // 3
+    RS_BLEND_SRC_SRC_ALPHA,             // 4
+    RS_BLEND_SRC_ONE_MINUS_SRC_ALPHA,   // 5
+    RS_BLEND_SRC_DST_ALPHA,             // 6
+    RS_BLEND_SRC_ONE_MINUS_DST_ALPHA,   // 7
+    RS_BLEND_SRC_SRC_ALPHA_SATURATE     // 8
+} rs_blend_src_func;
+
+typedef enum {
+    RS_BLEND_DST_ZERO,                  // 0
+    RS_BLEND_DST_ONE,                   // 1
+    RS_BLEND_DST_SRC_COLOR,             // 2
+    RS_BLEND_DST_ONE_MINUS_SRC_COLOR,   // 3
+    RS_BLEND_DST_SRC_ALPHA,             // 4
+    RS_BLEND_DST_ONE_MINUS_SRC_ALPHA,   // 5
+    RS_BLEND_DST_DST_ALPHA,             // 6
+    RS_BLEND_DST_ONE_MINUS_DST_ALPHA    // 7
+} rs_blend_dst_func;
+
+typedef enum {
+    RS_CULL_BACK,
+    RS_CULL_FRONT,
+    RS_CULL_NONE
+} rs_cull_mode;
+
+typedef enum {
+    RS_SAMPLER_NEAREST,
+    RS_SAMPLER_LINEAR,
+    RS_SAMPLER_LINEAR_MIP_LINEAR,
+    RS_SAMPLER_WRAP,
+    RS_SAMPLER_CLAMP,
+    RS_SAMPLER_LINEAR_MIP_NEAREST,
+} rs_sampler_value;
+
 #if (defined(RS_VERSION) && (RS_VERSION >= 14))
 /**
  * Set the color target used for all subsequent rendering calls
@@ -83,6 +132,88 @@
 extern void __attribute__((overloadable))
     rsgBindProgramStore(rs_program_store ps);
 
+
+/**
+ * @hide
+ * Get program store depth function
+ *
+ * @param ps
+ */
+extern rs_depth_func __attribute__((overloadable))
+    rsgProgramStoreGetDepthFunc(rs_program_store ps);
+
+/**
+ * @hide
+ * Get program store depth mask
+ *
+ * @param ps
+ */
+extern bool __attribute__((overloadable))
+    rsgProgramStoreGetDepthMask(rs_program_store ps);
+/**
+ * @hide
+ * Get program store red component color mask
+ *
+ * @param ps
+ */
+extern bool __attribute__((overloadable))
+    rsgProgramStoreGetColorMaskR(rs_program_store ps);
+
+/**
+ * @hide
+ * Get program store green component color mask
+ *
+ * @param ps
+ */
+extern bool __attribute__((overloadable))
+    rsgProgramStoreGetColorMaskG(rs_program_store ps);
+
+/**
+ * @hide
+ * Get program store blur component color mask
+ *
+ * @param ps
+ */
+extern bool __attribute__((overloadable))
+    rsgProgramStoreGetColorMaskB(rs_program_store ps);
+
+/**
+ * @hide
+ * Get program store alpha component color mask
+ *
+ * @param ps
+ */
+extern bool __attribute__((overloadable))
+    rsgProgramStoreGetColorMaskA(rs_program_store ps);
+
+/**
+ * @hide
+ * Get program store blend source function
+ *
+ * @param ps
+ */
+extern rs_blend_src_func __attribute__((overloadable))
+        rsgProgramStoreGetBlendSrcFunc(rs_program_store ps);
+
+/**
+ * @hide
+ * Get program store blend destination function
+ *
+ * @param ps
+ */
+extern rs_blend_dst_func __attribute__((overloadable))
+    rsgProgramStoreGetBlendDstFunc(rs_program_store ps);
+
+/**
+ * @hide
+ * Get program store dither state
+ *
+ * @param ps
+ */
+extern bool __attribute__((overloadable))
+    rsgProgramStoreGetDitherEnabled(rs_program_store ps);
+
+
 /**
  * Bind a new ProgramVertex to the rendering context.
  *
@@ -100,6 +231,24 @@
     rsgBindProgramRaster(rs_program_raster pr);
 
 /**
+ * @hide
+ * Get program raster point sprite state
+ *
+ * @param pr
+ */
+extern bool __attribute__((overloadable))
+    rsgProgramRasterGetPointSpriteEnabled(rs_program_raster pr);
+
+/**
+ * @hide
+ * Get program raster cull mode
+ *
+ * @param pr
+ */
+extern rs_cull_mode __attribute__((overloadable))
+    rsgProgramRasterGetCullMode(rs_program_raster pr);
+
+/**
  * Bind a new Sampler object to a ProgramFragment.  The sampler will
  * operate on the texture bound at the matching slot.
  *
@@ -109,6 +258,51 @@
     rsgBindSampler(rs_program_fragment, uint slot, rs_sampler);
 
 /**
+ * @hide
+ * Get sampler minification value
+ *
+ * @param pr
+ */
+extern rs_sampler_value __attribute__((overloadable))
+    rsgSamplerGetMinification(rs_sampler s);
+
+/**
+ * @hide
+ * Get sampler magnification value
+ *
+ * @param pr
+ */
+extern rs_sampler_value __attribute__((overloadable))
+    rsgSamplerGetMagnification(rs_sampler s);
+
+/**
+ * @hide
+ * Get sampler wrap S value
+ *
+ * @param pr
+ */
+extern rs_sampler_value __attribute__((overloadable))
+    rsgSamplerGetWrapS(rs_sampler s);
+
+/**
+ * @hide
+ * Get sampler wrap T value
+ *
+ * @param pr
+ */
+extern rs_sampler_value __attribute__((overloadable))
+    rsgSamplerGetWrapT(rs_sampler s);
+
+/**
+ * @hide
+ * Get sampler anisotropy
+ *
+ * @param pr
+ */
+extern float __attribute__((overloadable))
+    rsgSamplerGetAnisotropy(rs_sampler s);
+
+/**
  * Bind a new Allocation object to a ProgramFragment.  The
  * Allocation must be a valid texture for the Program.  The sampling
  * of the texture will be controled by the Sampler bound at the
diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java
index 4f4f929..e0c2b3b 100644
--- a/media/java/android/media/AudioService.java
+++ b/media/java/android/media/AudioService.java
@@ -85,8 +85,7 @@
     private static final String TAG = "AudioService";
 
     /** Debug remote control client/display feature */
-    // TODO set to false before release
-    protected static final boolean DEBUG_RC = true;
+    protected static final boolean DEBUG_RC = false;
 
     /** How long to delay before persisting a change in volume/ringer mode. */
     private static final int PERSIST_DELAY = 3000;
@@ -369,6 +368,8 @@
         intentFilter.addAction(Intent.ACTION_USB_DGTL_HEADSET_PLUG);
         intentFilter.addAction(Intent.ACTION_HDMI_AUDIO_PLUG);
         intentFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
+        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
+        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
         context.registerReceiver(mReceiver, intentFilter);
 
         // Register for package removal intent broadcasts for media button receiver persistence
@@ -2566,6 +2567,10 @@
                         removeMediaButtonReceiverForPackage(packageName);
                     }
                 }
+            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
+                AudioSystem.setParameters("screen_state=on");
+            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
+                AudioSystem.setParameters("screen_state=off");
             }
         }
     }
diff --git a/media/java/android/media/MediaFile.java b/media/java/android/media/MediaFile.java
index 8793841..e275aa6 100644
--- a/media/java/android/media/MediaFile.java
+++ b/media/java/android/media/MediaFile.java
@@ -71,6 +71,11 @@
     private static final int FIRST_VIDEO_FILE_TYPE = FILE_TYPE_MP4;
     private static final int LAST_VIDEO_FILE_TYPE = FILE_TYPE_WEBM;
     
+    // More video file types
+    public static final int FILE_TYPE_MP2PS   = 200;
+    private static final int FIRST_VIDEO_FILE_TYPE2 = FILE_TYPE_MP2PS;
+    private static final int LAST_VIDEO_FILE_TYPE2 = FILE_TYPE_MP2PS;
+
     // Image file types
     public static final int FILE_TYPE_JPEG    = 31;
     public static final int FILE_TYPE_GIF     = 32;
@@ -235,6 +240,8 @@
         addFileType("PPT", FILE_TYPE_MS_POWERPOINT, "application/mspowerpoint", MtpConstants.FORMAT_MS_POWERPOINT_PRESENTATION);
         addFileType("FLAC", FILE_TYPE_FLAC, "audio/flac", MtpConstants.FORMAT_FLAC);
         addFileType("ZIP", FILE_TYPE_ZIP, "application/zip");
+        addFileType("MPG", FILE_TYPE_MP2PS, "video/mp2p");
+        addFileType("MPEG", FILE_TYPE_MP2PS, "video/mp2p");
     }
 
     public static boolean isAudioFileType(int fileType) {
@@ -246,7 +253,9 @@
 
     public static boolean isVideoFileType(int fileType) {
         return (fileType >= FIRST_VIDEO_FILE_TYPE &&
-                fileType <= LAST_VIDEO_FILE_TYPE);
+                fileType <= LAST_VIDEO_FILE_TYPE)
+            || (fileType >= FIRST_VIDEO_FILE_TYPE2 &&
+                fileType <= LAST_VIDEO_FILE_TYPE2);
     }
 
     public static boolean isImageFileType(int fileType) {
diff --git a/media/jni/android_media_MediaPlayer.cpp b/media/jni/android_media_MediaPlayer.cpp
index f3174fe..63cbf5e 100644
--- a/media/jni/android_media_MediaPlayer.cpp
+++ b/media/jni/android_media_MediaPlayer.cpp
@@ -274,8 +274,14 @@
     sp<ISurfaceTexture> new_st;
     if (jsurface) {
         sp<Surface> surface(Surface_getSurface(env, jsurface));
-        new_st = surface->getSurfaceTexture();
-        new_st->incStrong(thiz);
+        if (surface != NULL) {
+            new_st = surface->getSurfaceTexture();
+            new_st->incStrong(thiz);
+        } else {
+            jniThrowException(env, "java/lang/IllegalArgumentException",
+                    "The surface has been released");
+            return;
+        }
     }
 
     env->SetIntField(thiz, fields.surface_texture, (int)new_st.get());
diff --git a/media/libmediaplayerservice/Android.mk b/media/libmediaplayerservice/Android.mk
index ec7d8a0..a3e2517 100644
--- a/media/libmediaplayerservice/Android.mk
+++ b/media/libmediaplayerservice/Android.mk
@@ -32,8 +32,8 @@
 	libdl
 
 LOCAL_STATIC_LIBRARIES := \
-        libstagefright_rtsp                     \
         libstagefright_nuplayer                 \
+        libstagefright_rtsp                     \
 
 LOCAL_C_INCLUDES :=                                                 \
 	$(JNI_H_INCLUDE)                                                \
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index b5eef94..24e1bfb 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -584,6 +584,10 @@
         }
     }
 
+    if (!strncasecmp("rtsp://", url, 7)) {
+        return NU_PLAYER;
+    }
+
     // use MidiFile for MIDI extensions
     int lenURL = strlen(url);
     for (int i = 0; i < NELEM(FILE_EXTS); ++i) {
diff --git a/media/libmediaplayerservice/nuplayer/Android.mk b/media/libmediaplayerservice/nuplayer/Android.mk
index e761509..33e2f93 100644
--- a/media/libmediaplayerservice/nuplayer/Android.mk
+++ b/media/libmediaplayerservice/nuplayer/Android.mk
@@ -8,6 +8,7 @@
         NuPlayerDriver.cpp              \
         NuPlayerRenderer.cpp            \
         NuPlayerStreamListener.cpp      \
+        RTSPSource.cpp                  \
         StreamingSource.cpp             \
 
 LOCAL_C_INCLUDES := \
@@ -15,6 +16,7 @@
 	$(TOP)/frameworks/base/media/libstagefright/include             \
         $(TOP)/frameworks/base/media/libstagefright/mpeg2ts             \
         $(TOP)/frameworks/base/media/libstagefright/httplive            \
+        $(TOP)/frameworks/base/media/libstagefright/rtsp                \
 
 LOCAL_MODULE:= libstagefright_nuplayer
 
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index 6b40528..4c710b4 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
@@ -25,6 +25,7 @@
 #include "NuPlayerDriver.h"
 #include "NuPlayerRenderer.h"
 #include "NuPlayerSource.h"
+#include "RTSPSource.h"
 #include "StreamingSource.h"
 
 #include "ATSParser.h"
@@ -87,7 +88,14 @@
         const char *url, const KeyedVector<String8, String8> *headers) {
     sp<AMessage> msg = new AMessage(kWhatSetDataSource, id());
 
-    msg->setObject("source", new HTTPLiveSource(url, headers, mUIDValid, mUID));
+    if (!strncasecmp(url, "rtsp://", 7)) {
+        msg->setObject(
+                "source", new RTSPSource(url, headers, mUIDValid, mUID));
+    } else {
+        msg->setObject(
+                "source", new HTTPLiveSource(url, headers, mUIDValid, mUID));
+    }
+
     msg->post();
 }
 
@@ -568,8 +576,15 @@
     CHECK(mAudioDecoder == NULL);
     CHECK(mVideoDecoder == NULL);
 
+    ++mScanSourcesGeneration;
+    mScanSourcesPending = false;
+
     mRenderer.clear();
-    mSource.clear();
+
+    if (mSource != NULL) {
+        mSource->stop();
+        mSource.clear();
+    }
 
     if (mDriver != NULL) {
         sp<NuPlayerDriver> driver = mDriver.promote();
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.h b/media/libmediaplayerservice/nuplayer/NuPlayer.h
index a5382b4..f90759d 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.h
@@ -68,6 +68,7 @@
     struct Renderer;
     struct Source;
     struct StreamingSource;
+    struct RTSPSource;
 
     enum {
         kWhatSetDataSource              = '=DaS',
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
index 07e347e..bf19040 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerRenderer.cpp
@@ -219,7 +219,9 @@
 
 bool NuPlayer::Renderer::onDrainAudioQueue() {
     uint32_t numFramesPlayed;
-    CHECK_EQ(mAudioSink->getPosition(&numFramesPlayed), (status_t)OK);
+    if (mAudioSink->getPosition(&numFramesPlayed) != OK) {
+        return false;
+    }
 
     ssize_t numFramesAvailableToWrite =
         mAudioSink->frameCount() - (mNumFramesWritten - numFramesPlayed);
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayerSource.h b/media/libmediaplayerservice/nuplayer/NuPlayerSource.h
index 8a7eece..531b29f 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayerSource.h
+++ b/media/libmediaplayerservice/nuplayer/NuPlayerSource.h
@@ -28,6 +28,7 @@
     Source() {}
 
     virtual void start() = 0;
+    virtual void stop() {}
 
     // Returns OK iff more data was available,
     // an error or ERROR_END_OF_STREAM if not.
diff --git a/media/libmediaplayerservice/nuplayer/RTSPSource.cpp b/media/libmediaplayerservice/nuplayer/RTSPSource.cpp
new file mode 100644
index 0000000..e72adc4
--- /dev/null
+++ b/media/libmediaplayerservice/nuplayer/RTSPSource.cpp
@@ -0,0 +1,354 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "RTSPSource"
+#include <utils/Log.h>
+
+#include "RTSPSource.h"
+
+#include "AnotherPacketSource.h"
+#include "MyHandler.h"
+
+#include <media/stagefright/MetaData.h>
+
+namespace android {
+
+NuPlayer::RTSPSource::RTSPSource(
+        const char *url,
+        const KeyedVector<String8, String8> *headers,
+        bool uidValid,
+        uid_t uid)
+    : mURL(url),
+      mUIDValid(uidValid),
+      mUID(uid),
+      mFlags(0),
+      mState(DISCONNECTED),
+      mFinalResult(OK),
+      mDisconnectReplyID(0) {
+    if (headers) {
+        mExtraHeaders = *headers;
+
+        ssize_t index =
+            mExtraHeaders.indexOfKey(String8("x-hide-urls-from-log"));
+
+        if (index >= 0) {
+            mFlags |= kFlagIncognito;
+
+            mExtraHeaders.removeItemsAt(index);
+        }
+    }
+}
+
+NuPlayer::RTSPSource::~RTSPSource() {
+    if (mLooper != NULL) {
+        mLooper->stop();
+    }
+}
+
+void NuPlayer::RTSPSource::start() {
+    if (mLooper == NULL) {
+        mLooper = new ALooper;
+        mLooper->setName("rtsp");
+        mLooper->start();
+
+        mReflector = new AHandlerReflector<RTSPSource>(this);
+        mLooper->registerHandler(mReflector);
+    }
+
+    CHECK(mHandler == NULL);
+
+    sp<AMessage> notify = new AMessage(kWhatNotify, mReflector->id());
+
+    mHandler = new MyHandler(mURL.c_str(), notify, mUIDValid, mUID);
+    mLooper->registerHandler(mHandler);
+
+    CHECK_EQ(mState, (int)DISCONNECTED);
+    mState = CONNECTING;
+
+    mHandler->connect();
+}
+
+void NuPlayer::RTSPSource::stop() {
+    sp<AMessage> msg = new AMessage(kWhatDisconnect, mReflector->id());
+
+    sp<AMessage> dummy;
+    msg->postAndAwaitResponse(&dummy);
+}
+
+status_t NuPlayer::RTSPSource::feedMoreTSData() {
+    return mFinalResult;
+}
+
+sp<MetaData> NuPlayer::RTSPSource::getFormat(bool audio) {
+    sp<AnotherPacketSource> source = getSource(audio);
+
+    if (source == NULL) {
+        return NULL;
+    }
+
+    return source->getFormat();
+}
+
+status_t NuPlayer::RTSPSource::dequeueAccessUnit(
+        bool audio, sp<ABuffer> *accessUnit) {
+    sp<AnotherPacketSource> source = getSource(audio);
+
+    if (source == NULL) {
+        return -EWOULDBLOCK;
+    }
+
+    status_t finalResult;
+    if (!source->hasBufferAvailable(&finalResult)) {
+        return finalResult == OK ? -EWOULDBLOCK : finalResult;
+    }
+
+    return source->dequeueAccessUnit(accessUnit);
+}
+
+sp<AnotherPacketSource> NuPlayer::RTSPSource::getSource(bool audio) {
+    return audio ? mAudioTrack : mVideoTrack;
+}
+
+status_t NuPlayer::RTSPSource::getDuration(int64_t *durationUs) {
+    *durationUs = 0ll;
+
+    int64_t audioDurationUs;
+    if (mAudioTrack != NULL
+            && mAudioTrack->getFormat()->findInt64(
+                kKeyDuration, &audioDurationUs)
+            && audioDurationUs > *durationUs) {
+        *durationUs = audioDurationUs;
+    }
+
+    int64_t videoDurationUs;
+    if (mVideoTrack != NULL
+            && mVideoTrack->getFormat()->findInt64(
+                kKeyDuration, &videoDurationUs)
+            && videoDurationUs > *durationUs) {
+        *durationUs = videoDurationUs;
+    }
+
+    return OK;
+}
+
+status_t NuPlayer::RTSPSource::seekTo(int64_t seekTimeUs) {
+    if (mState != CONNECTED) {
+        return UNKNOWN_ERROR;
+    }
+
+    mState = SEEKING;
+    mHandler->seek(seekTimeUs);
+
+    return OK;
+}
+
+bool NuPlayer::RTSPSource::isSeekable() {
+    return true;
+}
+
+void NuPlayer::RTSPSource::onMessageReceived(const sp<AMessage> &msg) {
+    if (msg->what() == kWhatDisconnect) {
+        uint32_t replyID;
+        CHECK(msg->senderAwaitsResponse(&replyID));
+
+        mDisconnectReplyID = replyID;
+        finishDisconnectIfPossible();
+        return;
+    }
+
+    CHECK_EQ(msg->what(), (int)kWhatNotify);
+
+    int32_t what;
+    CHECK(msg->findInt32("what", &what));
+
+    switch (what) {
+        case MyHandler::kWhatConnected:
+            onConnected();
+            break;
+
+        case MyHandler::kWhatDisconnected:
+            onDisconnected(msg);
+            break;
+
+        case MyHandler::kWhatSeekDone:
+        {
+            mState = CONNECTED;
+            break;
+        }
+
+        case MyHandler::kWhatAccessUnit:
+        {
+            size_t trackIndex;
+            CHECK(msg->findSize("trackIndex", &trackIndex));
+            CHECK_LT(trackIndex, mTracks.size());
+
+            sp<RefBase> obj;
+            CHECK(msg->findObject("accessUnit", &obj));
+
+            sp<ABuffer> accessUnit = static_cast<ABuffer *>(obj.get());
+
+            int32_t damaged;
+            if (accessUnit->meta()->findInt32("damaged", &damaged)
+                    && damaged) {
+                LOGI("dropping damaged access unit.");
+                break;
+            }
+
+            const TrackInfo &info = mTracks.editItemAt(trackIndex);
+            sp<AnotherPacketSource> source = info.mSource;
+            if (source != NULL) {
+#if 1
+                uint32_t rtpTime;
+                CHECK(accessUnit->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
+
+                int64_t nptUs =
+                    ((double)rtpTime - (double)info.mRTPTime)
+                        / info.mTimeScale
+                        * 1000000ll
+                        + info.mNormalPlaytimeUs;
+
+                accessUnit->meta()->setInt64("timeUs", nptUs);
+#endif
+
+                source->queueAccessUnit(accessUnit);
+            }
+            break;
+        }
+
+        case MyHandler::kWhatEOS:
+        {
+            size_t trackIndex;
+            CHECK(msg->findSize("trackIndex", &trackIndex));
+            CHECK_LT(trackIndex, mTracks.size());
+
+            int32_t finalResult;
+            CHECK(msg->findInt32("finalResult", &finalResult));
+            CHECK_NE(finalResult, (status_t)OK);
+
+            TrackInfo *info = &mTracks.editItemAt(trackIndex);
+            sp<AnotherPacketSource> source = info->mSource;
+            if (source != NULL) {
+                source->signalEOS(finalResult);
+            }
+
+            break;
+        }
+
+        case MyHandler::kWhatSeekDiscontinuity:
+        {
+            size_t trackIndex;
+            CHECK(msg->findSize("trackIndex", &trackIndex));
+            CHECK_LT(trackIndex, mTracks.size());
+
+            TrackInfo *info = &mTracks.editItemAt(trackIndex);
+            sp<AnotherPacketSource> source = info->mSource;
+            if (source != NULL) {
+                source->queueDiscontinuity(ATSParser::DISCONTINUITY_SEEK, NULL);
+            }
+
+            break;
+        }
+
+        case MyHandler::kWhatNormalPlayTimeMapping:
+        {
+            size_t trackIndex;
+            CHECK(msg->findSize("trackIndex", &trackIndex));
+            CHECK_LT(trackIndex, mTracks.size());
+
+            uint32_t rtpTime;
+            CHECK(msg->findInt32("rtpTime", (int32_t *)&rtpTime));
+
+            int64_t nptUs;
+            CHECK(msg->findInt64("nptUs", &nptUs));
+
+            TrackInfo *info = &mTracks.editItemAt(trackIndex);
+            info->mRTPTime = rtpTime;
+            info->mNormalPlaytimeUs = nptUs;
+            break;
+        }
+
+        default:
+            TRESPASS();
+    }
+}
+
+void NuPlayer::RTSPSource::onConnected() {
+    CHECK(mAudioTrack == NULL);
+    CHECK(mVideoTrack == NULL);
+
+    size_t numTracks = mHandler->countTracks();
+    for (size_t i = 0; i < numTracks; ++i) {
+        int32_t timeScale;
+        sp<MetaData> format = mHandler->getTrackFormat(i, &timeScale);
+
+        const char *mime;
+        CHECK(format->findCString(kKeyMIMEType, &mime));
+
+        bool isAudio = !strncasecmp(mime, "audio/", 6);
+        bool isVideo = !strncasecmp(mime, "video/", 6);
+
+        TrackInfo info;
+        info.mTimeScale = timeScale;
+        info.mRTPTime = 0;
+        info.mNormalPlaytimeUs = 0ll;
+
+        if ((isAudio && mAudioTrack == NULL)
+                || (isVideo && mVideoTrack == NULL)) {
+            sp<AnotherPacketSource> source = new AnotherPacketSource(format);
+
+            if (isAudio) {
+                mAudioTrack = source;
+            } else {
+                mVideoTrack = source;
+            }
+
+            info.mSource = source;
+        }
+
+        mTracks.push(info);
+    }
+
+    mState = CONNECTED;
+}
+
+void NuPlayer::RTSPSource::onDisconnected(const sp<AMessage> &msg) {
+    status_t err;
+    CHECK(msg->findInt32("result", &err));
+    CHECK_NE(err, (status_t)OK);
+
+    mLooper->unregisterHandler(mHandler->id());
+    mHandler.clear();
+
+    mState = DISCONNECTED;
+    mFinalResult = err;
+
+    if (mDisconnectReplyID != 0) {
+        finishDisconnectIfPossible();
+    }
+}
+
+void NuPlayer::RTSPSource::finishDisconnectIfPossible() {
+    if (mState != DISCONNECTED) {
+        mHandler->disconnect();
+        return;
+    }
+
+    (new AMessage)->postReply(mDisconnectReplyID);
+    mDisconnectReplyID = 0;
+}
+
+}  // namespace android
diff --git a/media/libmediaplayerservice/nuplayer/RTSPSource.h b/media/libmediaplayerservice/nuplayer/RTSPSource.h
new file mode 100644
index 0000000..66eab72
--- /dev/null
+++ b/media/libmediaplayerservice/nuplayer/RTSPSource.h
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef RTSP_SOURCE_H_
+
+#define RTSP_SOURCE_H_
+
+#include "NuPlayerSource.h"
+
+#include <media/stagefright/foundation/AHandlerReflector.h>
+
+namespace android {
+
+struct ALooper;
+struct AnotherPacketSource;
+struct MyHandler;
+
+struct NuPlayer::RTSPSource : public NuPlayer::Source {
+    RTSPSource(
+            const char *url,
+            const KeyedVector<String8, String8> *headers,
+            bool uidValid = false,
+            uid_t uid = 0);
+
+    virtual void start();
+    virtual void stop();
+
+    virtual status_t feedMoreTSData();
+
+    virtual sp<MetaData> getFormat(bool audio);
+    virtual status_t dequeueAccessUnit(bool audio, sp<ABuffer> *accessUnit);
+
+    virtual status_t getDuration(int64_t *durationUs);
+    virtual status_t seekTo(int64_t seekTimeUs);
+    virtual bool isSeekable();
+
+    void onMessageReceived(const sp<AMessage> &msg);
+
+protected:
+    virtual ~RTSPSource();
+
+private:
+    enum {
+        kWhatNotify          = 'noti',
+        kWhatDisconnect      = 'disc',
+    };
+
+    enum State {
+        DISCONNECTED,
+        CONNECTING,
+        CONNECTED,
+        SEEKING,
+    };
+
+    enum Flags {
+        // Don't log any URLs.
+        kFlagIncognito = 1,
+    };
+
+    struct TrackInfo {
+        sp<AnotherPacketSource> mSource;
+
+        int32_t mTimeScale;
+        uint32_t mRTPTime;
+        int64_t mNormalPlaytimeUs;
+    };
+
+    AString mURL;
+    KeyedVector<String8, String8> mExtraHeaders;
+    bool mUIDValid;
+    uid_t mUID;
+    uint32_t mFlags;
+    State mState;
+    status_t mFinalResult;
+    uint32_t mDisconnectReplyID;
+
+    sp<ALooper> mLooper;
+    sp<AHandlerReflector<RTSPSource> > mReflector;
+    sp<MyHandler> mHandler;
+
+    Vector<TrackInfo> mTracks;
+    sp<AnotherPacketSource> mAudioTrack;
+    sp<AnotherPacketSource> mVideoTrack;
+
+    sp<AnotherPacketSource> getSource(bool audio);
+
+    void onConnected();
+    void onDisconnected(const sp<AMessage> &msg);
+    void finishDisconnectIfPossible();
+
+    DISALLOW_EVIL_CONSTRUCTORS(RTSPSource);
+};
+
+}  // namespace android
+
+#endif  // RTSP_SOURCE_H_
diff --git a/media/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index 9cb18de..d947760 100644
--- a/media/libstagefright/ACodec.cpp
+++ b/media/libstagefright/ACodec.cpp
@@ -681,6 +681,10 @@
     static const MimeToRole kMimeToRole[] = {
         { MEDIA_MIMETYPE_AUDIO_MPEG,
             "audio_decoder.mp3", "audio_encoder.mp3" },
+        { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I,
+            "audio_decoder.mp1", "audio_encoder.mp1" },
+        { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II,
+            "audio_decoder.mp2", "audio_encoder.mp2" },
         { MEDIA_MIMETYPE_AUDIO_AMR_NB,
             "audio_decoder.amrnb", "audio_encoder.amrnb" },
         { MEDIA_MIMETYPE_AUDIO_AMR_WB,
diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk
index 0b1a2af..0aeb515 100644
--- a/media/libstagefright/Android.mk
+++ b/media/libstagefright/Android.mk
@@ -58,7 +58,6 @@
         $(TOP)/frameworks/base/include/media/stagefright/openmax \
         $(TOP)/external/flac/include \
         $(TOP)/external/tremolo \
-        $(TOP)/frameworks/base/media/libstagefright/rtsp \
         $(TOP)/external/openssl/include \
 
 LOCAL_SHARED_LIBRARIES := \
@@ -88,7 +87,6 @@
         libvpx \
         libstagefright_mpeg2ts \
         libstagefright_httplive \
-        libstagefright_rtsp \
         libstagefright_id3 \
         libFLAC \
 
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
index 1165af5..1c7e58d 100644
--- a/media/libstagefright/AwesomePlayer.cpp
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -22,7 +22,6 @@
 
 #include <dlfcn.h>
 
-#include "include/ARTSPController.h"
 #include "include/AwesomePlayer.h"
 #include "include/DRMExtractor.h"
 #include "include/SoftwareRenderer.h"
@@ -53,7 +52,6 @@
 #include <gui/SurfaceTextureClient.h>
 #include <surfaceflinger/ISurfaceComposer.h>
 
-#include <media/stagefright/foundation/ALooper.h>
 #include <media/stagefright/foundation/AMessage.h>
 
 #include <cutils/properties.h>
@@ -65,7 +63,6 @@
 
 static int64_t kLowWaterMarkUs = 2000000ll;  // 2secs
 static int64_t kHighWaterMarkUs = 5000000ll;  // 5secs
-static int64_t kHighWaterMarkRTSPUs = 4000000ll;  // 4secs
 static const size_t kLowWaterMarkBytes = 40000;
 static const size_t kHighWaterMarkBytes = 200000;
 
@@ -485,9 +482,6 @@
         if (mConnectingDataSource != NULL) {
             LOGI("interrupting the connection process");
             mConnectingDataSource->disconnect();
-        } else if (mConnectingRTSPController != NULL) {
-            LOGI("interrupting the connection process");
-            mConnectingRTSPController->disconnect();
         }
 
         if (mFlags & PREPARING_CONNECTED) {
@@ -534,11 +528,6 @@
 
     mVideoRenderer.clear();
 
-    if (mRTSPController != NULL) {
-        mRTSPController->disconnect();
-        mRTSPController.clear();
-    }
-
     if (mVideoSource != NULL) {
         shutdownVideoDecoder_l();
     }
@@ -612,10 +601,7 @@
 bool AwesomePlayer::getCachedDuration_l(int64_t *durationUs, bool *eos) {
     int64_t bitrate;
 
-    if (mRTSPController != NULL) {
-        *durationUs = mRTSPController->getQueueDurationUs(eos);
-        return true;
-    } else if (mCachedSource != NULL && getBitrate(&bitrate)) {
+    if (mCachedSource != NULL && getBitrate(&bitrate)) {
         status_t finalStatus;
         size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus);
         *durationUs = cachedDataRemaining * 8000000ll / bitrate;
@@ -751,9 +737,6 @@
         LOGV("cachedDurationUs = %.2f secs, eos=%d",
              cachedDurationUs / 1E6, eos);
 
-        int64_t highWaterMarkUs =
-            (mRTSPController != NULL) ? kHighWaterMarkRTSPUs : kHighWaterMarkUs;
-
         if ((mFlags & PLAYING) && !eos
                 && (cachedDurationUs < kLowWaterMarkUs)) {
             LOGI("cache is running low (%.2f secs) , pausing.",
@@ -763,7 +746,7 @@
             ensureCacheIsFetching_l();
             sendCacheStats();
             notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START);
-        } else if (eos || cachedDurationUs > highWaterMarkUs) {
+        } else if (eos || cachedDurationUs > kHighWaterMarkUs) {
             if (mFlags & CACHE_UNDERRUN) {
                 LOGI("cache has filled up (%.2f secs), resuming.",
                      cachedDurationUs / 1E6);
@@ -1081,7 +1064,8 @@
 
     if (USE_SURFACE_ALLOC
             && !strncmp(component, "OMX.", 4)
-            && strncmp(component, "OMX.google.", 11)) {
+            && strncmp(component, "OMX.google.", 11)
+            && strcmp(component, "OMX.Nvidia.mpeg2v.decode")) {
         // Hardware decoders avoid the CPU color conversion by decoding
         // directly to ANativeBuffers, so we must use a renderer that
         // just pushes those buffers to the ANativeWindow.
@@ -1263,10 +1247,7 @@
 }
 
 status_t AwesomePlayer::getPosition(int64_t *positionUs) {
-    if (mRTSPController != NULL) {
-        *positionUs = mRTSPController->getNormalPlayTimeUs();
-    }
-    else if (mSeeking != NO_SEEK) {
+    if (mSeeking != NO_SEEK) {
         *positionUs = mSeekTimeUs;
     } else if (mVideoSource != NULL
             && (mAudioPlayer == NULL || !(mFlags & VIDEO_AT_EOS))) {
@@ -1316,25 +1297,7 @@
     }
 }
 
-// static
-void AwesomePlayer::OnRTSPSeekDoneWrapper(void *cookie) {
-    static_cast<AwesomePlayer *>(cookie)->onRTSPSeekDone();
-}
-
-void AwesomePlayer::onRTSPSeekDone() {
-    if (!mSeekNotificationSent) {
-        notifyListener_l(MEDIA_SEEK_COMPLETE);
-        mSeekNotificationSent = true;
-    }
-}
-
 status_t AwesomePlayer::seekTo_l(int64_t timeUs) {
-    if (mRTSPController != NULL) {
-        mSeekNotificationSent = false;
-        mRTSPController->seekAsync(timeUs, OnRTSPSeekDoneWrapper, this);
-        return OK;
-    }
-
     if (mFlags & CACHE_UNDERRUN) {
         modifyFlags(CACHE_UNDERRUN, CLEAR);
         play_l();
@@ -1770,7 +1733,6 @@
         int64_t latenessUs = nowUs - timeUs;
 
         if (latenessUs > 500000ll
-                && mRTSPController == NULL
                 && mAudioPlayer != NULL
                 && mAudioPlayer->getMediaTimeMapping(
                     &realTimeUs, &mediaTimeUs)) {
@@ -2085,34 +2047,6 @@
                 return UNKNOWN_ERROR;
             }
         }
-    } else if (!strncasecmp("rtsp://", mUri.string(), 7)) {
-        if (mLooper == NULL) {
-            mLooper = new ALooper;
-            mLooper->setName("rtsp");
-            mLooper->start();
-        }
-        mRTSPController = new ARTSPController(mLooper);
-        mConnectingRTSPController = mRTSPController;
-
-        if (mUIDValid) {
-            mConnectingRTSPController->setUID(mUID);
-        }
-
-        mLock.unlock();
-        status_t err = mRTSPController->connect(mUri.string());
-        mLock.lock();
-
-        mConnectingRTSPController.clear();
-
-        LOGI("ARTSPController::connect returned %d", err);
-
-        if (err != OK) {
-            mRTSPController.clear();
-            return err;
-        }
-
-        sp<MediaExtractor> extractor = mRTSPController.get();
-        return setDataSource_l(extractor);
     } else {
         dataSource = DataSource::CreateFromURI(mUri.string(), &mUriHeaders);
     }
@@ -2224,7 +2158,7 @@
 
     modifyFlags(PREPARING_CONNECTED, SET);
 
-    if (isStreamingHTTP() || mRTSPController != NULL) {
+    if (isStreamingHTTP()) {
         postBufferingEvent_l();
     } else {
         finishAsyncPrepare_l();
diff --git a/media/libstagefright/DataSource.cpp b/media/libstagefright/DataSource.cpp
index c16b3b5..70523c1 100644
--- a/media/libstagefright/DataSource.cpp
+++ b/media/libstagefright/DataSource.cpp
@@ -20,6 +20,7 @@
 #include "include/MPEG4Extractor.h"
 #include "include/WAVExtractor.h"
 #include "include/OggExtractor.h"
+#include "include/MPEG2PSExtractor.h"
 #include "include/MPEG2TSExtractor.h"
 #include "include/NuCachedSource2.h"
 #include "include/HTTPBase.h"
@@ -113,6 +114,7 @@
     RegisterSniffer(SniffMP3);
     RegisterSniffer(SniffAAC);
     RegisterSniffer(SniffAVI);
+    RegisterSniffer(SniffMPEG2PS);
 
     char value[PROPERTY_VALUE_MAX];
     if (property_get("drm.service.enabled", value, NULL)
diff --git a/media/libstagefright/MP3Extractor.cpp b/media/libstagefright/MP3Extractor.cpp
index 92e84c2..34e9cd7 100644
--- a/media/libstagefright/MP3Extractor.cpp
+++ b/media/libstagefright/MP3Extractor.cpp
@@ -25,11 +25,11 @@
 #include "include/VBRISeeker.h"
 #include "include/XINGSeeker.h"
 
+#include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/AMessage.h>
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/MediaBuffer.h>
 #include <media/stagefright/MediaBufferGroup.h>
-#include <media/stagefright/MediaDebug.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/MediaSource.h>
@@ -289,9 +289,24 @@
     GetMPEGAudioFrameSize(
             header, &frame_size, &sample_rate, &num_channels, &bitrate);
 
+    unsigned layer = 4 - ((header >> 17) & 3);
+
     mMeta = new MetaData;
 
-    mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
+    switch (layer) {
+        case 1:
+            mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
+            break;
+        case 2:
+            mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
+            break;
+        case 3:
+            mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
+            break;
+        default:
+            TRESPASS();
+    }
+
     mMeta->setInt32(kKeySampleRate, sample_rate);
     mMeta->setInt32(kKeyBitRate, bitrate * 1000);
     mMeta->setInt32(kKeyChannelCount, num_channels);
diff --git a/media/libstagefright/MediaDefs.cpp b/media/libstagefright/MediaDefs.cpp
index 01f1fba..444e823 100644
--- a/media/libstagefright/MediaDefs.cpp
+++ b/media/libstagefright/MediaDefs.cpp
@@ -30,6 +30,8 @@
 const char *MEDIA_MIMETYPE_AUDIO_AMR_NB = "audio/3gpp";
 const char *MEDIA_MIMETYPE_AUDIO_AMR_WB = "audio/amr-wb";
 const char *MEDIA_MIMETYPE_AUDIO_MPEG = "audio/mpeg";
+const char *MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I = "audio/mpeg-L1";
+const char *MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II = "audio/mpeg-L2";
 const char *MEDIA_MIMETYPE_AUDIO_AAC = "audio/mp4a-latm";
 const char *MEDIA_MIMETYPE_AUDIO_QCELP = "audio/qcelp";
 const char *MEDIA_MIMETYPE_AUDIO_VORBIS = "audio/vorbis";
@@ -45,6 +47,7 @@
 const char *MEDIA_MIMETYPE_CONTAINER_MATROSKA = "video/x-matroska";
 const char *MEDIA_MIMETYPE_CONTAINER_MPEG2TS = "video/mp2ts";
 const char *MEDIA_MIMETYPE_CONTAINER_AVI = "video/avi";
+const char *MEDIA_MIMETYPE_CONTAINER_MPEG2PS = "video/mp2p";
 
 const char *MEDIA_MIMETYPE_CONTAINER_WVM = "video/wvm";
 
diff --git a/media/libstagefright/MediaExtractor.cpp b/media/libstagefright/MediaExtractor.cpp
index a8023df..2221268 100644
--- a/media/libstagefright/MediaExtractor.cpp
+++ b/media/libstagefright/MediaExtractor.cpp
@@ -24,6 +24,7 @@
 #include "include/MPEG4Extractor.h"
 #include "include/WAVExtractor.h"
 #include "include/OggExtractor.h"
+#include "include/MPEG2PSExtractor.h"
 #include "include/MPEG2TSExtractor.h"
 #include "include/DRMExtractor.h"
 #include "include/WVMExtractor.h"
@@ -115,6 +116,8 @@
         ret = new WVMExtractor(source);
     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AAC_ADTS)) {
         ret = new AACExtractor(source);
+    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_MPEG2PS)) {
+        ret = new MPEG2PSExtractor(source);
     }
 
     if (ret != NULL) {
diff --git a/media/libstagefright/OMXCodec.cpp b/media/libstagefright/OMXCodec.cpp
index 7c34257..86bd267 100755
--- a/media/libstagefright/OMXCodec.cpp
+++ b/media/libstagefright/OMXCodec.cpp
@@ -102,6 +102,7 @@
     { MEDIA_MIMETYPE_IMAGE_JPEG, "OMX.TI.JPEG.decode" },
 //    { MEDIA_MIMETYPE_AUDIO_MPEG, "OMX.TI.MP3.decode" },
     { MEDIA_MIMETYPE_AUDIO_MPEG, "OMX.google.mp3.decoder" },
+    { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II, "OMX.Nvidia.mp2.decoder" },
 //    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.TI.AMR.decode" },
 //    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.Nvidia.amr.decoder" },
     { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.google.amrnb.decoder" },
@@ -1462,7 +1463,9 @@
       mOutputPortSettingsChangedPending(false),
       mLeftOverBuffer(NULL),
       mPaused(false),
-      mNativeWindow(!strncmp(componentName, "OMX.google.", 11)
+      mNativeWindow(
+              (!strncmp(componentName, "OMX.google.", 11)
+              || !strcmp(componentName, "OMX.Nvidia.mpeg2v.decode"))
                         ? NULL : nativeWindow) {
     mPortStatus[kPortIndexInput] = ENABLED;
     mPortStatus[kPortIndexOutput] = ENABLED;
@@ -1483,6 +1486,12 @@
     static const MimeToRole kMimeToRole[] = {
         { MEDIA_MIMETYPE_AUDIO_MPEG,
             "audio_decoder.mp3", "audio_encoder.mp3" },
+        { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I,
+            "audio_decoder.mp1", "audio_encoder.mp1" },
+        { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II,
+            "audio_decoder.mp2", "audio_encoder.mp2" },
+        { MEDIA_MIMETYPE_AUDIO_MPEG,
+            "audio_decoder.mp3", "audio_encoder.mp3" },
         { MEDIA_MIMETYPE_AUDIO_AMR_NB,
             "audio_decoder.amrnb", "audio_encoder.amrnb" },
         { MEDIA_MIMETYPE_AUDIO_AMR_WB,
diff --git a/media/libstagefright/StagefrightMediaScanner.cpp b/media/libstagefright/StagefrightMediaScanner.cpp
index 571e8be27..bb6e4cd 100644
--- a/media/libstagefright/StagefrightMediaScanner.cpp
+++ b/media/libstagefright/StagefrightMediaScanner.cpp
@@ -38,7 +38,7 @@
         ".mpeg", ".ogg", ".mid", ".smf", ".imy", ".wma", ".aac",
         ".wav", ".amr", ".midi", ".xmf", ".rtttl", ".rtx", ".ota",
         ".mkv", ".mka", ".webm", ".ts", ".fl", ".flac", ".mxmf",
-        ".avi",
+        ".avi", ".mpeg", ".mpg"
     };
     static const size_t kNumValidExtensions =
         sizeof(kValidExtensions) / sizeof(kValidExtensions[0]);
diff --git a/media/libstagefright/include/ARTSPController.h b/media/libstagefright/include/ARTSPController.h
deleted file mode 100644
index 2bd5be6..0000000
--- a/media/libstagefright/include/ARTSPController.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef A_RTSP_CONTROLLER_H_
-
-#define A_RTSP_CONTROLLER_H_
-
-#include <media/stagefright/foundation/ABase.h>
-#include <media/stagefright/foundation/AHandlerReflector.h>
-#include <media/stagefright/MediaExtractor.h>
-
-namespace android {
-
-struct ALooper;
-struct MyHandler;
-
-struct ARTSPController : public MediaExtractor {
-    ARTSPController(const sp<ALooper> &looper);
-
-    void setUID(uid_t uid);
-
-    status_t connect(const char *url);
-    void disconnect();
-
-    void seekAsync(int64_t timeUs, void (*seekDoneCb)(void *), void *cookie);
-
-    virtual size_t countTracks();
-    virtual sp<MediaSource> getTrack(size_t index);
-
-    virtual sp<MetaData> getTrackMetaData(
-            size_t index, uint32_t flags);
-
-    int64_t getNormalPlayTimeUs();
-    int64_t getQueueDurationUs(bool *eos);
-
-    void onMessageReceived(const sp<AMessage> &msg);
-
-    virtual uint32_t flags() const {
-        // Seeking 10secs forward or backward is a very expensive operation
-        // for rtsp, so let's not enable that.
-        // The user can always use the seek bar.
-
-        return CAN_PAUSE | CAN_SEEK;
-    }
-
-protected:
-    virtual ~ARTSPController();
-
-private:
-    enum {
-        kWhatConnectDone    = 'cdon',
-        kWhatDisconnectDone = 'ddon',
-        kWhatSeekDone       = 'sdon',
-    };
-
-    enum State {
-        DISCONNECTED,
-        CONNECTED,
-        CONNECTING,
-    };
-
-    Mutex mLock;
-    Condition mCondition;
-
-    State mState;
-    status_t mConnectionResult;
-
-    sp<ALooper> mLooper;
-    sp<MyHandler> mHandler;
-    sp<AHandlerReflector<ARTSPController> > mReflector;
-
-    bool mUIDValid;
-    uid_t mUID;
-
-    void (*mSeekDoneCb)(void *);
-    void *mSeekDoneCookie;
-    int64_t mLastSeekCompletedTimeUs;
-
-    DISALLOW_EVIL_CONSTRUCTORS(ARTSPController);
-};
-
-}  // namespace android
-
-#endif  // A_RTSP_CONTROLLER_H_
diff --git a/media/libstagefright/include/AwesomePlayer.h b/media/libstagefright/include/AwesomePlayer.h
index 8e73121..7d6bcad 100644
--- a/media/libstagefright/include/AwesomePlayer.h
+++ b/media/libstagefright/include/AwesomePlayer.h
@@ -38,9 +38,6 @@
 struct NuCachedSource2;
 struct ISurfaceTexture;
 
-struct ALooper;
-struct ARTSPController;
-
 class DrmManagerClinet;
 class DecryptHandle;
 
@@ -233,10 +230,6 @@
     sp<HTTPBase> mConnectingDataSource;
     sp<NuCachedSource2> mCachedSource;
 
-    sp<ALooper> mLooper;
-    sp<ARTSPController> mRTSPController;
-    sp<ARTSPController> mConnectingRTSPController;
-
     DrmManagerClient *mDrmManagerClient;
     sp<DecryptHandle> mDecryptHandle;
 
@@ -287,9 +280,6 @@
 
     static bool ContinuePreparation(void *cookie);
 
-    static void OnRTSPSeekDoneWrapper(void *cookie);
-    void onRTSPSeekDone();
-
     bool getBitrate(int64_t *bitrate);
 
     void finishSeekIfNecessary(int64_t videoTimeUs);
diff --git a/media/libstagefright/include/MPEG2PSExtractor.h b/media/libstagefright/include/MPEG2PSExtractor.h
new file mode 100644
index 0000000..fb76564
--- /dev/null
+++ b/media/libstagefright/include/MPEG2PSExtractor.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef MPEG2_PS_EXTRACTOR_H_
+
+#define MPEG2_PS_EXTRACTOR_H_
+
+#include <media/stagefright/foundation/ABase.h>
+#include <media/stagefright/MediaExtractor.h>
+#include <utils/threads.h>
+#include <utils/KeyedVector.h>
+
+namespace android {
+
+struct ABuffer;
+struct AMessage;
+struct Track;
+struct String8;
+
+struct MPEG2PSExtractor : public MediaExtractor {
+    MPEG2PSExtractor(const sp<DataSource> &source);
+
+    virtual size_t countTracks();
+    virtual sp<MediaSource> getTrack(size_t index);
+    virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
+
+    virtual sp<MetaData> getMetaData();
+
+    virtual uint32_t flags() const;
+
+protected:
+    virtual ~MPEG2PSExtractor();
+
+private:
+    struct Track;
+    struct WrappedTrack;
+
+    mutable Mutex mLock;
+    sp<DataSource> mDataSource;
+
+    off64_t mOffset;
+    status_t mFinalResult;
+    sp<ABuffer> mBuffer;
+    KeyedVector<unsigned, sp<Track> > mTracks;
+    bool mScanning;
+
+    bool mProgramStreamMapValid;
+    KeyedVector<unsigned, unsigned> mStreamTypeByESID;
+
+    status_t feedMore();
+
+    status_t dequeueChunk();
+    ssize_t dequeuePack();
+    ssize_t dequeueSystemHeader();
+    ssize_t dequeuePES();
+
+    DISALLOW_EVIL_CONSTRUCTORS(MPEG2PSExtractor);
+};
+
+bool SniffMPEG2PS(
+        const sp<DataSource> &source, String8 *mimeType, float *confidence,
+        sp<AMessage> *);
+
+}  // namespace android
+
+#endif  // MPEG2_PS_EXTRACTOR_H_
+
diff --git a/media/libstagefright/mpeg2ts/ATSParser.h b/media/libstagefright/mpeg2ts/ATSParser.h
index 388cb54..878e534 100644
--- a/media/libstagefright/mpeg2ts/ATSParser.h
+++ b/media/libstagefright/mpeg2ts/ATSParser.h
@@ -64,12 +64,9 @@
 
     bool PTSTimeDeltaEstablished();
 
-protected:
-    virtual ~ATSParser();
-
-private:
     enum {
         // From ISO/IEC 13818-1: 2000 (E), Table 2-29
+        STREAMTYPE_RESERVED             = 0x00,
         STREAMTYPE_MPEG1_VIDEO          = 0x01,
         STREAMTYPE_MPEG2_VIDEO          = 0x02,
         STREAMTYPE_MPEG1_AUDIO          = 0x03,
@@ -79,6 +76,10 @@
         STREAMTYPE_H264                 = 0x1b,
     };
 
+protected:
+    virtual ~ATSParser();
+
+private:
     struct Program;
     struct Stream;
 
diff --git a/media/libstagefright/mpeg2ts/Android.mk b/media/libstagefright/mpeg2ts/Android.mk
index 4a30416..578c669 100644
--- a/media/libstagefright/mpeg2ts/Android.mk
+++ b/media/libstagefright/mpeg2ts/Android.mk
@@ -6,6 +6,7 @@
         AnotherPacketSource.cpp   \
         ATSParser.cpp             \
         ESQueue.cpp               \
+        MPEG2PSExtractor.cpp      \
         MPEG2TSExtractor.cpp      \
 
 LOCAL_C_INCLUDES:= \
diff --git a/media/libstagefright/mpeg2ts/ESQueue.cpp b/media/libstagefright/mpeg2ts/ESQueue.cpp
index a56da36..b9a4826 100644
--- a/media/libstagefright/mpeg2ts/ESQueue.cpp
+++ b/media/libstagefright/mpeg2ts/ESQueue.cpp
@@ -585,6 +585,8 @@
         return NULL;
     }
 
+    unsigned layer = 4 - ((header >> 17) & 3);
+
     sp<ABuffer> accessUnit = new ABuffer(frameSize);
     memcpy(accessUnit->data(), data, frameSize);
 
@@ -601,7 +603,24 @@
 
     if (mFormat == NULL) {
         mFormat = new MetaData;
-        mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
+
+        switch (layer) {
+            case 1:
+                mFormat->setCString(
+                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I);
+                break;
+            case 2:
+                mFormat->setCString(
+                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II);
+                break;
+            case 3:
+                mFormat->setCString(
+                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
+                break;
+            default:
+                TRESPASS();
+        }
+
         mFormat->setInt32(kKeySampleRate, samplingRate);
         mFormat->setInt32(kKeyChannelCount, numChannels);
     }
diff --git a/media/libstagefright/mpeg2ts/MPEG2PSExtractor.cpp b/media/libstagefright/mpeg2ts/MPEG2PSExtractor.cpp
new file mode 100644
index 0000000..f55be6e
--- /dev/null
+++ b/media/libstagefright/mpeg2ts/MPEG2PSExtractor.cpp
@@ -0,0 +1,715 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "MPEG2PSExtractor"
+#include <utils/Log.h>
+
+#include "include/MPEG2PSExtractor.h"
+
+#include "AnotherPacketSource.h"
+#include "ESQueue.h"
+
+#include <media/stagefright/foundation/ABitReader.h>
+#include <media/stagefright/foundation/ABuffer.h>
+#include <media/stagefright/foundation/ADebug.h>
+#include <media/stagefright/foundation/AMessage.h>
+#include <media/stagefright/foundation/hexdump.h>
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MediaErrors.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/Utils.h>
+#include <utils/String8.h>
+
+namespace android {
+
+struct MPEG2PSExtractor::Track : public MediaSource {
+    Track(MPEG2PSExtractor *extractor,
+          unsigned stream_id, unsigned stream_type);
+
+    virtual status_t start(MetaData *params);
+    virtual status_t stop();
+    virtual sp<MetaData> getFormat();
+
+    virtual status_t read(
+            MediaBuffer **buffer, const ReadOptions *options);
+
+protected:
+    virtual ~Track();
+
+private:
+    friend struct MPEG2PSExtractor;
+
+    MPEG2PSExtractor *mExtractor;
+
+    unsigned mStreamID;
+    unsigned mStreamType;
+    ElementaryStreamQueue *mQueue;
+    sp<AnotherPacketSource> mSource;
+
+    status_t appendPESData(
+            unsigned PTS_DTS_flags,
+            uint64_t PTS, uint64_t DTS,
+            const uint8_t *data, size_t size);
+
+    DISALLOW_EVIL_CONSTRUCTORS(Track);
+};
+
+struct MPEG2PSExtractor::WrappedTrack : public MediaSource {
+    WrappedTrack(const sp<MPEG2PSExtractor> &extractor, const sp<Track> &track);
+
+    virtual status_t start(MetaData *params);
+    virtual status_t stop();
+    virtual sp<MetaData> getFormat();
+
+    virtual status_t read(
+            MediaBuffer **buffer, const ReadOptions *options);
+
+protected:
+    virtual ~WrappedTrack();
+
+private:
+    sp<MPEG2PSExtractor> mExtractor;
+    sp<MPEG2PSExtractor::Track> mTrack;
+
+    DISALLOW_EVIL_CONSTRUCTORS(WrappedTrack);
+};
+
+////////////////////////////////////////////////////////////////////////////////
+
+MPEG2PSExtractor::MPEG2PSExtractor(const sp<DataSource> &source)
+    : mDataSource(source),
+      mOffset(0),
+      mFinalResult(OK),
+      mBuffer(new ABuffer(0)),
+      mScanning(true),
+      mProgramStreamMapValid(false) {
+    for (size_t i = 0; i < 500; ++i) {
+        if (feedMore() != OK) {
+            break;
+        }
+    }
+
+    // Remove all tracks that were unable to determine their format.
+    for (size_t i = mTracks.size(); i-- > 0;) {
+        if (mTracks.valueAt(i)->getFormat() == NULL) {
+            mTracks.removeItemsAt(i);
+        }
+    }
+
+    mScanning = false;
+}
+
+MPEG2PSExtractor::~MPEG2PSExtractor() {
+}
+
+size_t MPEG2PSExtractor::countTracks() {
+    return mTracks.size();
+}
+
+sp<MediaSource> MPEG2PSExtractor::getTrack(size_t index) {
+    if (index >= mTracks.size()) {
+        return NULL;
+    }
+
+    return new WrappedTrack(this, mTracks.valueAt(index));
+}
+
+sp<MetaData> MPEG2PSExtractor::getTrackMetaData(size_t index, uint32_t flags) {
+    if (index >= mTracks.size()) {
+        return NULL;
+    }
+
+    return mTracks.valueAt(index)->getFormat();
+}
+
+sp<MetaData> MPEG2PSExtractor::getMetaData() {
+    sp<MetaData> meta = new MetaData;
+    meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_CONTAINER_MPEG2PS);
+
+    return meta;
+}
+
+uint32_t MPEG2PSExtractor::flags() const {
+    return CAN_PAUSE;
+}
+
+status_t MPEG2PSExtractor::feedMore() {
+    Mutex::Autolock autoLock(mLock);
+
+    // How much data we're reading at a time
+    static const size_t kChunkSize = 8192;
+
+    for (;;) {
+        status_t err = dequeueChunk();
+
+        if (err == -EAGAIN && mFinalResult == OK) {
+            memmove(mBuffer->base(), mBuffer->data(), mBuffer->size());
+            mBuffer->setRange(0, mBuffer->size());
+
+            if (mBuffer->size() + kChunkSize > mBuffer->capacity()) {
+                size_t newCapacity = mBuffer->capacity() + kChunkSize;
+                sp<ABuffer> newBuffer = new ABuffer(newCapacity);
+                memcpy(newBuffer->data(), mBuffer->data(), mBuffer->size());
+                newBuffer->setRange(0, mBuffer->size());
+                mBuffer = newBuffer;
+            }
+
+            ssize_t n = mDataSource->readAt(
+                    mOffset, mBuffer->data() + mBuffer->size(), kChunkSize);
+
+            if (n < (ssize_t)kChunkSize) {
+                mFinalResult = (n < 0) ? (status_t)n : ERROR_END_OF_STREAM;
+                return mFinalResult;
+            }
+
+            mBuffer->setRange(mBuffer->offset(), mBuffer->size() + n);
+            mOffset += n;
+        } else if (err != OK) {
+            mFinalResult = err;
+            return err;
+        } else {
+            return OK;
+        }
+    }
+}
+
+status_t MPEG2PSExtractor::dequeueChunk() {
+    if (mBuffer->size() < 4) {
+        return -EAGAIN;
+    }
+
+    if (memcmp("\x00\x00\x01", mBuffer->data(), 3)) {
+        return ERROR_MALFORMED;
+    }
+
+    unsigned chunkType = mBuffer->data()[3];
+
+    ssize_t res;
+
+    switch (chunkType) {
+        case 0xba:
+        {
+            res = dequeuePack();
+            break;
+        }
+
+        case 0xbb:
+        {
+            res = dequeueSystemHeader();
+            break;
+        }
+
+        default:
+        {
+            res = dequeuePES();
+            break;
+        }
+    }
+
+    if (res > 0) {
+        if (mBuffer->size() < (size_t)res) {
+            return -EAGAIN;
+        }
+
+        mBuffer->setRange(mBuffer->offset() + res, mBuffer->size() - res);
+        res = OK;
+    }
+
+    return res;
+}
+
+ssize_t MPEG2PSExtractor::dequeuePack() {
+    // 32 + 2 + 3 + 1 + 15 + 1 + 15+ 1 + 9 + 1 + 22 + 1 + 1 | +5
+
+    if (mBuffer->size() < 14) {
+        return -EAGAIN;
+    }
+
+    unsigned pack_stuffing_length = mBuffer->data()[13] & 7;
+
+    return pack_stuffing_length + 14;
+}
+
+ssize_t MPEG2PSExtractor::dequeueSystemHeader() {
+    if (mBuffer->size() < 6) {
+        return -EAGAIN;
+    }
+
+    unsigned header_length = U16_AT(mBuffer->data() + 4);
+
+    return header_length + 6;
+}
+
+ssize_t MPEG2PSExtractor::dequeuePES() {
+    if (mBuffer->size() < 6) {
+        return -EAGAIN;
+    }
+
+    unsigned PES_packet_length = U16_AT(mBuffer->data() + 4);
+    CHECK_NE(PES_packet_length, 0u);
+
+    size_t n = PES_packet_length + 6;
+
+    if (mBuffer->size() < n) {
+        return -EAGAIN;
+    }
+
+    ABitReader br(mBuffer->data(), n);
+
+    unsigned packet_startcode_prefix = br.getBits(24);
+
+    LOGV("packet_startcode_prefix = 0x%08x", packet_startcode_prefix);
+
+    if (packet_startcode_prefix != 1) {
+        LOGV("Supposedly payload_unit_start=1 unit does not start "
+             "with startcode.");
+
+        return ERROR_MALFORMED;
+    }
+
+    CHECK_EQ(packet_startcode_prefix, 0x000001u);
+
+    unsigned stream_id = br.getBits(8);
+    LOGV("stream_id = 0x%02x", stream_id);
+
+    /* unsigned PES_packet_length = */br.getBits(16);
+
+    if (stream_id == 0xbc) {
+        // program_stream_map
+
+        if (!mScanning) {
+            return n;
+        }
+
+        mStreamTypeByESID.clear();
+
+        /* unsigned current_next_indicator = */br.getBits(1);
+        /* unsigned reserved = */br.getBits(2);
+        /* unsigned program_stream_map_version = */br.getBits(5);
+        /* unsigned reserved = */br.getBits(7);
+        /* unsigned marker_bit = */br.getBits(1);
+        unsigned program_stream_info_length = br.getBits(16);
+
+        size_t offset = 0;
+        while (offset < program_stream_info_length) {
+            if (offset + 2 > program_stream_info_length) {
+                return ERROR_MALFORMED;
+            }
+
+            unsigned descriptor_tag = br.getBits(8);
+            unsigned descriptor_length = br.getBits(8);
+
+            LOGI("found descriptor tag 0x%02x of length %u",
+                 descriptor_tag, descriptor_length);
+
+            if (offset + 2 + descriptor_length > program_stream_info_length) {
+                return ERROR_MALFORMED;
+            }
+
+            br.skipBits(8 * descriptor_length);
+
+            offset += 2 + descriptor_length;
+        }
+
+        unsigned elementary_stream_map_length = br.getBits(16);
+
+        offset = 0;
+        while (offset < elementary_stream_map_length) {
+            if (offset + 4 > elementary_stream_map_length) {
+                return ERROR_MALFORMED;
+            }
+
+            unsigned stream_type = br.getBits(8);
+            unsigned elementary_stream_id = br.getBits(8);
+
+            LOGI("elementary stream id 0x%02x has stream type 0x%02x",
+                 elementary_stream_id, stream_type);
+
+            mStreamTypeByESID.add(elementary_stream_id, stream_type);
+
+            unsigned elementary_stream_info_length = br.getBits(16);
+
+            if (offset + 4 + elementary_stream_info_length
+                    > elementary_stream_map_length) {
+                return ERROR_MALFORMED;
+            }
+
+            offset += 4 + elementary_stream_info_length;
+        }
+
+        /* unsigned CRC32 = */br.getBits(32);
+
+        mProgramStreamMapValid = true;
+    } else if (stream_id != 0xbe  // padding_stream
+            && stream_id != 0xbf  // private_stream_2
+            && stream_id != 0xf0  // ECM
+            && stream_id != 0xf1  // EMM
+            && stream_id != 0xff  // program_stream_directory
+            && stream_id != 0xf2  // DSMCC
+            && stream_id != 0xf8) {  // H.222.1 type E
+        CHECK_EQ(br.getBits(2), 2u);
+
+        /* unsigned PES_scrambling_control = */br.getBits(2);
+        /* unsigned PES_priority = */br.getBits(1);
+        /* unsigned data_alignment_indicator = */br.getBits(1);
+        /* unsigned copyright = */br.getBits(1);
+        /* unsigned original_or_copy = */br.getBits(1);
+
+        unsigned PTS_DTS_flags = br.getBits(2);
+        LOGV("PTS_DTS_flags = %u", PTS_DTS_flags);
+
+        unsigned ESCR_flag = br.getBits(1);
+        LOGV("ESCR_flag = %u", ESCR_flag);
+
+        unsigned ES_rate_flag = br.getBits(1);
+        LOGV("ES_rate_flag = %u", ES_rate_flag);
+
+        unsigned DSM_trick_mode_flag = br.getBits(1);
+        LOGV("DSM_trick_mode_flag = %u", DSM_trick_mode_flag);
+
+        unsigned additional_copy_info_flag = br.getBits(1);
+        LOGV("additional_copy_info_flag = %u", additional_copy_info_flag);
+
+        /* unsigned PES_CRC_flag = */br.getBits(1);
+        /* PES_extension_flag = */br.getBits(1);
+
+        unsigned PES_header_data_length = br.getBits(8);
+        LOGV("PES_header_data_length = %u", PES_header_data_length);
+
+        unsigned optional_bytes_remaining = PES_header_data_length;
+
+        uint64_t PTS = 0, DTS = 0;
+
+        if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
+            CHECK_GE(optional_bytes_remaining, 5u);
+
+            CHECK_EQ(br.getBits(4), PTS_DTS_flags);
+
+            PTS = ((uint64_t)br.getBits(3)) << 30;
+            CHECK_EQ(br.getBits(1), 1u);
+            PTS |= ((uint64_t)br.getBits(15)) << 15;
+            CHECK_EQ(br.getBits(1), 1u);
+            PTS |= br.getBits(15);
+            CHECK_EQ(br.getBits(1), 1u);
+
+            LOGV("PTS = %llu", PTS);
+            // LOGI("PTS = %.2f secs", PTS / 90000.0f);
+
+            optional_bytes_remaining -= 5;
+
+            if (PTS_DTS_flags == 3) {
+                CHECK_GE(optional_bytes_remaining, 5u);
+
+                CHECK_EQ(br.getBits(4), 1u);
+
+                DTS = ((uint64_t)br.getBits(3)) << 30;
+                CHECK_EQ(br.getBits(1), 1u);
+                DTS |= ((uint64_t)br.getBits(15)) << 15;
+                CHECK_EQ(br.getBits(1), 1u);
+                DTS |= br.getBits(15);
+                CHECK_EQ(br.getBits(1), 1u);
+
+                LOGV("DTS = %llu", DTS);
+
+                optional_bytes_remaining -= 5;
+            }
+        }
+
+        if (ESCR_flag) {
+            CHECK_GE(optional_bytes_remaining, 6u);
+
+            br.getBits(2);
+
+            uint64_t ESCR = ((uint64_t)br.getBits(3)) << 30;
+            CHECK_EQ(br.getBits(1), 1u);
+            ESCR |= ((uint64_t)br.getBits(15)) << 15;
+            CHECK_EQ(br.getBits(1), 1u);
+            ESCR |= br.getBits(15);
+            CHECK_EQ(br.getBits(1), 1u);
+
+            LOGV("ESCR = %llu", ESCR);
+            /* unsigned ESCR_extension = */br.getBits(9);
+
+            CHECK_EQ(br.getBits(1), 1u);
+
+            optional_bytes_remaining -= 6;
+        }
+
+        if (ES_rate_flag) {
+            CHECK_GE(optional_bytes_remaining, 3u);
+
+            CHECK_EQ(br.getBits(1), 1u);
+            /* unsigned ES_rate = */br.getBits(22);
+            CHECK_EQ(br.getBits(1), 1u);
+
+            optional_bytes_remaining -= 3;
+        }
+
+        br.skipBits(optional_bytes_remaining * 8);
+
+        // ES data follows.
+
+        CHECK_GE(PES_packet_length, PES_header_data_length + 3);
+
+        unsigned dataLength =
+            PES_packet_length - 3 - PES_header_data_length;
+
+        if (br.numBitsLeft() < dataLength * 8) {
+            LOGE("PES packet does not carry enough data to contain "
+                 "payload. (numBitsLeft = %d, required = %d)",
+                 br.numBitsLeft(), dataLength * 8);
+
+            return ERROR_MALFORMED;
+        }
+
+        CHECK_GE(br.numBitsLeft(), dataLength * 8);
+
+        ssize_t index = mTracks.indexOfKey(stream_id);
+        if (index < 0 && mScanning) {
+            unsigned streamType;
+
+            ssize_t streamTypeIndex;
+            if (mProgramStreamMapValid
+                    && (streamTypeIndex =
+                            mStreamTypeByESID.indexOfKey(stream_id)) >= 0) {
+                streamType = mStreamTypeByESID.valueAt(streamTypeIndex);
+            } else if ((stream_id & ~0x1f) == 0xc0) {
+                // ISO/IEC 13818-3 or ISO/IEC 11172-3 or ISO/IEC 13818-7
+                // or ISO/IEC 14496-3 audio
+                streamType = ATSParser::STREAMTYPE_MPEG2_AUDIO;
+            } else if ((stream_id & ~0x0f) == 0xe0) {
+                // ISO/IEC 13818-2 or ISO/IEC 11172-2 or ISO/IEC 14496-2 video
+                streamType = ATSParser::STREAMTYPE_MPEG2_VIDEO;
+            } else {
+                streamType = ATSParser::STREAMTYPE_RESERVED;
+            }
+
+            index = mTracks.add(
+                    stream_id, new Track(this, stream_id, streamType));
+        }
+
+        status_t err = OK;
+
+        if (index >= 0) {
+            err =
+                mTracks.editValueAt(index)->appendPESData(
+                    PTS_DTS_flags, PTS, DTS, br.data(), dataLength);
+        }
+
+        br.skipBits(dataLength * 8);
+
+        if (err != OK) {
+            return err;
+        }
+    } else if (stream_id == 0xbe) {  // padding_stream
+        CHECK_NE(PES_packet_length, 0u);
+        br.skipBits(PES_packet_length * 8);
+    } else {
+        CHECK_NE(PES_packet_length, 0u);
+        br.skipBits(PES_packet_length * 8);
+    }
+
+    return n;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+MPEG2PSExtractor::Track::Track(
+        MPEG2PSExtractor *extractor, unsigned stream_id, unsigned stream_type)
+    : mExtractor(extractor),
+      mStreamID(stream_id),
+      mStreamType(stream_type),
+      mQueue(NULL) {
+    bool supported = true;
+    ElementaryStreamQueue::Mode mode;
+
+    switch (mStreamType) {
+        case ATSParser::STREAMTYPE_H264:
+            mode = ElementaryStreamQueue::H264;
+            break;
+        case ATSParser::STREAMTYPE_MPEG2_AUDIO_ATDS:
+            mode = ElementaryStreamQueue::AAC;
+            break;
+        case ATSParser::STREAMTYPE_MPEG1_AUDIO:
+        case ATSParser::STREAMTYPE_MPEG2_AUDIO:
+            mode = ElementaryStreamQueue::MPEG_AUDIO;
+            break;
+
+        case ATSParser::STREAMTYPE_MPEG1_VIDEO:
+        case ATSParser::STREAMTYPE_MPEG2_VIDEO:
+            mode = ElementaryStreamQueue::MPEG_VIDEO;
+            break;
+
+        case ATSParser::STREAMTYPE_MPEG4_VIDEO:
+            mode = ElementaryStreamQueue::MPEG4_VIDEO;
+            break;
+
+        default:
+            supported = false;
+            break;
+    }
+
+    if (supported) {
+        mQueue = new ElementaryStreamQueue(mode);
+    } else {
+        LOGI("unsupported stream ID 0x%02x", stream_id);
+    }
+}
+
+MPEG2PSExtractor::Track::~Track() {
+    delete mQueue;
+    mQueue = NULL;
+}
+
+status_t MPEG2PSExtractor::Track::start(MetaData *params) {
+    if (mSource == NULL) {
+        return NO_INIT;
+    }
+
+    return mSource->start(params);
+}
+
+status_t MPEG2PSExtractor::Track::stop() {
+    if (mSource == NULL) {
+        return NO_INIT;
+    }
+
+    return mSource->stop();
+}
+
+sp<MetaData> MPEG2PSExtractor::Track::getFormat() {
+    if (mSource == NULL) {
+        return NULL;
+    }
+
+    return mSource->getFormat();
+}
+
+status_t MPEG2PSExtractor::Track::read(
+        MediaBuffer **buffer, const ReadOptions *options) {
+    if (mSource == NULL) {
+        return NO_INIT;
+    }
+
+    status_t finalResult;
+    while (!mSource->hasBufferAvailable(&finalResult)) {
+        if (finalResult != OK) {
+            return ERROR_END_OF_STREAM;
+        }
+
+        status_t err = mExtractor->feedMore();
+
+        if (err != OK) {
+            mSource->signalEOS(err);
+        }
+    }
+
+    return mSource->read(buffer, options);
+}
+
+status_t MPEG2PSExtractor::Track::appendPESData(
+        unsigned PTS_DTS_flags,
+        uint64_t PTS, uint64_t DTS,
+        const uint8_t *data, size_t size) {
+    if (mQueue == NULL) {
+        return OK;
+    }
+
+    int64_t timeUs;
+    if (PTS_DTS_flags == 2 || PTS_DTS_flags == 3) {
+        timeUs = (PTS * 100) / 9;
+    } else {
+        timeUs = 0;
+    }
+
+    status_t err = mQueue->appendData(data, size, timeUs);
+
+    if (err != OK) {
+        return err;
+    }
+
+    sp<ABuffer> accessUnit;
+    while ((accessUnit = mQueue->dequeueAccessUnit()) != NULL) {
+        if (mSource == NULL) {
+            sp<MetaData> meta = mQueue->getFormat();
+
+            if (meta != NULL) {
+                LOGV("Stream ID 0x%02x now has data.", mStreamID);
+
+                mSource = new AnotherPacketSource(meta);
+                mSource->queueAccessUnit(accessUnit);
+            }
+        } else if (mQueue->getFormat() != NULL) {
+            mSource->queueAccessUnit(accessUnit);
+        }
+    }
+
+    return OK;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+MPEG2PSExtractor::WrappedTrack::WrappedTrack(
+        const sp<MPEG2PSExtractor> &extractor, const sp<Track> &track)
+    : mExtractor(extractor),
+      mTrack(track) {
+}
+
+MPEG2PSExtractor::WrappedTrack::~WrappedTrack() {
+}
+
+status_t MPEG2PSExtractor::WrappedTrack::start(MetaData *params) {
+    return mTrack->start(params);
+}
+
+status_t MPEG2PSExtractor::WrappedTrack::stop() {
+    return mTrack->stop();
+}
+
+sp<MetaData> MPEG2PSExtractor::WrappedTrack::getFormat() {
+    return mTrack->getFormat();
+}
+
+status_t MPEG2PSExtractor::WrappedTrack::read(
+        MediaBuffer **buffer, const ReadOptions *options) {
+    return mTrack->read(buffer, options);
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+bool SniffMPEG2PS(
+        const sp<DataSource> &source, String8 *mimeType, float *confidence,
+        sp<AMessage> *) {
+    uint8_t header[5];
+    if (source->readAt(0, header, sizeof(header)) < (ssize_t)sizeof(header)) {
+        return false;
+    }
+
+    if (memcmp("\x00\x00\x01\xba", header, 4) || (header[4] >> 6) != 1) {
+        return false;
+    }
+
+    *confidence = 0.25f;  // Slightly larger than .mp3 extractor's confidence
+
+    mimeType->setTo(MEDIA_MIMETYPE_CONTAINER_MPEG2PS);
+
+    return true;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/rtsp/APacketSource.cpp b/media/libstagefright/rtsp/APacketSource.cpp
index 4ecb92f..3f4cdb5 100644
--- a/media/libstagefright/rtsp/APacketSource.cpp
+++ b/media/libstagefright/rtsp/APacketSource.cpp
@@ -34,8 +34,8 @@
 #include <media/stagefright/foundation/AString.h>
 #include <media/stagefright/foundation/base64.h>
 #include <media/stagefright/foundation/hexdump.h>
-#include <media/stagefright/MediaBuffer.h>
 #include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/MetaData.h>
 #include <utils/Vector.h>
 
@@ -402,43 +402,15 @@
     return csd;
 }
 
-static bool GetClockRate(const AString &desc, uint32_t *clockRate) {
-    ssize_t slashPos = desc.find("/");
-    if (slashPos < 0) {
-        return false;
-    }
-
-    const char *s = desc.c_str() + slashPos + 1;
-
-    char *end;
-    unsigned long x = strtoul(s, &end, 10);
-
-    if (end == s || (*end != '\0' && *end != '/')) {
-        return false;
-    }
-
-    *clockRate = x;
-
-    return true;
-}
-
 APacketSource::APacketSource(
         const sp<ASessionDescription> &sessionDesc, size_t index)
     : mInitCheck(NO_INIT),
-      mFormat(new MetaData),
-      mEOSResult(OK),
-      mIsAVC(false),
-      mScanForIDR(true),
-      mRTPTimeBase(0),
-      mNormalPlayTimeBaseUs(0),
-      mLastNormalPlayTimeUs(0) {
+      mFormat(new MetaData) {
     unsigned long PT;
     AString desc;
     AString params;
     sessionDesc->getFormatType(index, &PT, &desc, &params);
 
-    CHECK(GetClockRate(desc, &mClockRate));
-
     int64_t durationUs;
     if (sessionDesc->getDurationUs(&durationUs)) {
         mFormat->setInt64(kKeyDuration, durationUs);
@@ -448,8 +420,6 @@
 
     mInitCheck = OK;
     if (!strncmp(desc.c_str(), "H264/", 5)) {
-        mIsAVC = true;
-
         mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
 
         int32_t width, height;
@@ -602,137 +572,8 @@
     return mInitCheck;
 }
 
-status_t APacketSource::start(MetaData *params) {
-    return OK;
-}
-
-status_t APacketSource::stop() {
-    return OK;
-}
-
 sp<MetaData> APacketSource::getFormat() {
     return mFormat;
 }
 
-status_t APacketSource::read(
-        MediaBuffer **out, const ReadOptions *) {
-    *out = NULL;
-
-    Mutex::Autolock autoLock(mLock);
-    while (mEOSResult == OK && mBuffers.empty()) {
-        mCondition.wait(mLock);
-    }
-
-    if (!mBuffers.empty()) {
-        const sp<ABuffer> buffer = *mBuffers.begin();
-
-        updateNormalPlayTime_l(buffer);
-
-        int64_t timeUs;
-        CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
-
-        MediaBuffer *mediaBuffer = new MediaBuffer(buffer);
-        mediaBuffer->meta_data()->setInt64(kKeyTime, timeUs);
-
-        *out = mediaBuffer;
-
-        mBuffers.erase(mBuffers.begin());
-        return OK;
-    }
-
-    return mEOSResult;
-}
-
-void APacketSource::updateNormalPlayTime_l(const sp<ABuffer> &buffer) {
-    uint32_t rtpTime;
-    CHECK(buffer->meta()->findInt32("rtp-time", (int32_t *)&rtpTime));
-
-    mLastNormalPlayTimeUs =
-        (((double)rtpTime - (double)mRTPTimeBase) / mClockRate)
-            * 1000000ll
-            + mNormalPlayTimeBaseUs;
-}
-
-void APacketSource::queueAccessUnit(const sp<ABuffer> &buffer) {
-    int32_t damaged;
-    if (buffer->meta()->findInt32("damaged", &damaged) && damaged) {
-        LOGV("discarding damaged AU");
-        return;
-    }
-
-    if (mScanForIDR && mIsAVC) {
-        // This pretty piece of code ensures that the first access unit
-        // fed to the decoder after stream-start or seek is guaranteed to
-        // be an IDR frame. This is to workaround limitations of a certain
-        // hardware h.264 decoder that requires this to be the case.
-
-        if (!IsIDR(buffer)) {
-            LOGV("skipping AU while scanning for next IDR frame.");
-            return;
-        }
-
-        mScanForIDR = false;
-    }
-
-    Mutex::Autolock autoLock(mLock);
-    mBuffers.push_back(buffer);
-    mCondition.signal();
-}
-
-void APacketSource::signalEOS(status_t result) {
-    CHECK(result != OK);
-
-    Mutex::Autolock autoLock(mLock);
-    mEOSResult = result;
-    mCondition.signal();
-}
-
-void APacketSource::flushQueue() {
-    Mutex::Autolock autoLock(mLock);
-    mBuffers.clear();
-
-    mScanForIDR = true;
-}
-
-int64_t APacketSource::getNormalPlayTimeUs() {
-    Mutex::Autolock autoLock(mLock);
-    return mLastNormalPlayTimeUs;
-}
-
-void APacketSource::setNormalPlayTimeMapping(
-        uint32_t rtpTime, int64_t normalPlayTimeUs) {
-    Mutex::Autolock autoLock(mLock);
-
-    mRTPTimeBase = rtpTime;
-    mNormalPlayTimeBaseUs = normalPlayTimeUs;
-}
-
-int64_t APacketSource::getQueueDurationUs(bool *eos) {
-    Mutex::Autolock autoLock(mLock);
-
-    *eos = (mEOSResult != OK);
-
-    if (mBuffers.size() < 2) {
-        return 0;
-    }
-
-    const sp<ABuffer> first = *mBuffers.begin();
-    const sp<ABuffer> last = *--mBuffers.end();
-
-    int64_t firstTimeUs;
-    CHECK(first->meta()->findInt64("timeUs", &firstTimeUs));
-
-    int64_t lastTimeUs;
-    CHECK(last->meta()->findInt64("timeUs", &lastTimeUs));
-
-    if (lastTimeUs < firstTimeUs) {
-        LOGE("Huh? Time moving backwards? %lld > %lld",
-             firstTimeUs, lastTimeUs);
-
-        return 0;
-    }
-
-    return lastTimeUs - firstTimeUs;
-}
-
 }  // namespace android
diff --git a/media/libstagefright/rtsp/APacketSource.h b/media/libstagefright/rtsp/APacketSource.h
index 7a77fc6..530e537 100644
--- a/media/libstagefright/rtsp/APacketSource.h
+++ b/media/libstagefright/rtsp/APacketSource.h
@@ -19,63 +19,27 @@
 #define A_PACKET_SOURCE_H_
 
 #include <media/stagefright/foundation/ABase.h>
-#include <media/stagefright/MediaSource.h>
-#include <utils/threads.h>
-#include <utils/List.h>
+#include <media/stagefright/MetaData.h>
+#include <utils/RefBase.h>
 
 namespace android {
 
-struct ABuffer;
 struct ASessionDescription;
 
-struct APacketSource : public MediaSource {
+struct APacketSource : public RefBase {
     APacketSource(const sp<ASessionDescription> &sessionDesc, size_t index);
 
     status_t initCheck() const;
 
-    virtual status_t start(MetaData *params = NULL);
-    virtual status_t stop();
     virtual sp<MetaData> getFormat();
 
-    virtual status_t read(
-            MediaBuffer **buffer, const ReadOptions *options = NULL);
-
-    void queueAccessUnit(const sp<ABuffer> &buffer);
-    void signalEOS(status_t result);
-
-    void flushQueue();
-
-    int64_t getNormalPlayTimeUs();
-
-    void setNormalPlayTimeMapping(
-            uint32_t rtpTime, int64_t normalPlayTimeUs);
-
-    int64_t getQueueDurationUs(bool *eos);
-
 protected:
     virtual ~APacketSource();
 
 private:
     status_t mInitCheck;
 
-    Mutex mLock;
-    Condition mCondition;
-
     sp<MetaData> mFormat;
-    List<sp<ABuffer> > mBuffers;
-    status_t mEOSResult;
-
-    bool mIsAVC;
-    bool mScanForIDR;
-
-    uint32_t mClockRate;
-
-    uint32_t mRTPTimeBase;
-    int64_t mNormalPlayTimeBaseUs;
-
-    int64_t mLastNormalPlayTimeUs;
-
-    void updateNormalPlayTime_l(const sp<ABuffer> &buffer);
 
     DISALLOW_EVIL_CONSTRUCTORS(APacketSource);
 };
diff --git a/media/libstagefright/rtsp/ARTSPController.cpp b/media/libstagefright/rtsp/ARTSPController.cpp
deleted file mode 100644
index 2ebae7e..0000000
--- a/media/libstagefright/rtsp/ARTSPController.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "ARTSPController.h"
-
-#include "MyHandler.h"
-
-#include <media/stagefright/foundation/ADebug.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MediaSource.h>
-#include <media/stagefright/MetaData.h>
-
-namespace android {
-
-ARTSPController::ARTSPController(const sp<ALooper> &looper)
-    : mState(DISCONNECTED),
-      mLooper(looper),
-      mUIDValid(false),
-      mSeekDoneCb(NULL),
-      mSeekDoneCookie(NULL),
-      mLastSeekCompletedTimeUs(-1) {
-    mReflector = new AHandlerReflector<ARTSPController>(this);
-    looper->registerHandler(mReflector);
-}
-
-ARTSPController::~ARTSPController() {
-    CHECK_EQ((int)mState, (int)DISCONNECTED);
-    mLooper->unregisterHandler(mReflector->id());
-}
-
-void ARTSPController::setUID(uid_t uid) {
-    mUIDValid = true;
-    mUID = uid;
-}
-
-status_t ARTSPController::connect(const char *url) {
-    Mutex::Autolock autoLock(mLock);
-
-    if (mState != DISCONNECTED) {
-        return ERROR_ALREADY_CONNECTED;
-    }
-
-    sp<AMessage> msg = new AMessage(kWhatConnectDone, mReflector->id());
-
-    mHandler = new MyHandler(url, mLooper, mUIDValid, mUID);
-
-    mState = CONNECTING;
-
-    mHandler->connect(msg);
-
-    while (mState == CONNECTING) {
-        mCondition.wait(mLock);
-    }
-
-    if (mState != CONNECTED) {
-        mHandler.clear();
-    }
-
-    return mConnectionResult;
-}
-
-void ARTSPController::disconnect() {
-    Mutex::Autolock autoLock(mLock);
-
-    if (mState == CONNECTING) {
-        mState = DISCONNECTED;
-        mConnectionResult = ERROR_IO;
-        mCondition.broadcast();
-
-        mHandler.clear();
-        return;
-    } else if (mState != CONNECTED) {
-        return;
-    }
-
-    sp<AMessage> msg = new AMessage(kWhatDisconnectDone, mReflector->id());
-    mHandler->disconnect(msg);
-
-    while (mState == CONNECTED) {
-        mCondition.wait(mLock);
-    }
-
-    mHandler.clear();
-}
-
-void ARTSPController::seekAsync(
-        int64_t timeUs,
-        void (*seekDoneCb)(void *), void *cookie) {
-    Mutex::Autolock autoLock(mLock);
-
-    CHECK(seekDoneCb != NULL);
-    CHECK(mSeekDoneCb == NULL);
-
-    // Ignore seek requests that are too soon after the previous one has
-    // completed, we don't want to swamp the server.
-
-    bool tooEarly =
-        mLastSeekCompletedTimeUs >= 0
-            && ALooper::GetNowUs() < mLastSeekCompletedTimeUs + 500000ll;
-
-    if (mState != CONNECTED || tooEarly) {
-        (*seekDoneCb)(cookie);
-        return;
-    }
-
-    mSeekDoneCb = seekDoneCb;
-    mSeekDoneCookie = cookie;
-
-    sp<AMessage> msg = new AMessage(kWhatSeekDone, mReflector->id());
-    mHandler->seek(timeUs, msg);
-}
-
-size_t ARTSPController::countTracks() {
-    if (mHandler == NULL) {
-        return 0;
-    }
-
-    return mHandler->countTracks();
-}
-
-sp<MediaSource> ARTSPController::getTrack(size_t index) {
-    CHECK(mHandler != NULL);
-
-    return mHandler->getPacketSource(index);
-}
-
-sp<MetaData> ARTSPController::getTrackMetaData(
-        size_t index, uint32_t flags) {
-    CHECK(mHandler != NULL);
-
-    return mHandler->getPacketSource(index)->getFormat();
-}
-
-void ARTSPController::onMessageReceived(const sp<AMessage> &msg) {
-    switch (msg->what()) {
-        case kWhatConnectDone:
-        {
-            Mutex::Autolock autoLock(mLock);
-
-            CHECK(msg->findInt32("result", &mConnectionResult));
-            mState = (mConnectionResult == OK) ? CONNECTED : DISCONNECTED;
-
-            mCondition.signal();
-            break;
-        }
-
-        case kWhatDisconnectDone:
-        {
-            Mutex::Autolock autoLock(mLock);
-            mState = DISCONNECTED;
-            mCondition.signal();
-            break;
-        }
-
-        case kWhatSeekDone:
-        {
-            LOGI("seek done");
-
-            mLastSeekCompletedTimeUs = ALooper::GetNowUs();
-
-            void (*seekDoneCb)(void *) = mSeekDoneCb;
-            mSeekDoneCb = NULL;
-
-            (*seekDoneCb)(mSeekDoneCookie);
-            break;
-        }
-
-        default:
-            TRESPASS();
-            break;
-    }
-}
-
-int64_t ARTSPController::getNormalPlayTimeUs() {
-    CHECK(mHandler != NULL);
-    return mHandler->getNormalPlayTimeUs();
-}
-
-int64_t ARTSPController::getQueueDurationUs(bool *eos) {
-    *eos = true;
-
-    int64_t minQueuedDurationUs = 0;
-    for (size_t i = 0; i < mHandler->countTracks(); ++i) {
-        sp<APacketSource> source = mHandler->getPacketSource(i);
-
-        bool newEOS;
-        int64_t queuedDurationUs = source->getQueueDurationUs(&newEOS);
-
-        if (!newEOS) {
-            *eos = false;
-        }
-
-        if (i == 0 || queuedDurationUs < minQueuedDurationUs) {
-            minQueuedDurationUs = queuedDurationUs;
-        }
-    }
-
-    return minQueuedDurationUs;
-}
-
-}  // namespace android
diff --git a/media/libstagefright/rtsp/Android.mk b/media/libstagefright/rtsp/Android.mk
index 8530ff3..8230347 100644
--- a/media/libstagefright/rtsp/Android.mk
+++ b/media/libstagefright/rtsp/Android.mk
@@ -15,7 +15,6 @@
         ARTPSource.cpp              \
         ARTPWriter.cpp              \
         ARTSPConnection.cpp         \
-        ARTSPController.cpp         \
         ASessionDescription.cpp     \
 
 LOCAL_C_INCLUDES:= \
diff --git a/media/libstagefright/rtsp/MyHandler.h b/media/libstagefright/rtsp/MyHandler.h
index 8128813..af7dd23 100644
--- a/media/libstagefright/rtsp/MyHandler.h
+++ b/media/libstagefright/rtsp/MyHandler.h
@@ -94,12 +94,24 @@
 }
 
 struct MyHandler : public AHandler {
+    enum {
+        kWhatConnected                  = 'conn',
+        kWhatDisconnected               = 'disc',
+        kWhatSeekDone                   = 'sdon',
+
+        kWhatAccessUnit                 = 'accU',
+        kWhatEOS                        = 'eos!',
+        kWhatSeekDiscontinuity          = 'seeD',
+        kWhatNormalPlayTimeMapping      = 'nptM',
+    };
+
     MyHandler(
-            const char *url, const sp<ALooper> &looper,
+            const char *url,
+            const sp<AMessage> &notify,
             bool uidValid = false, uid_t uid = 0)
-        : mUIDValid(uidValid),
+        : mNotify(notify),
+          mUIDValid(uidValid),
           mUID(uid),
-          mLooper(looper),
           mNetLooper(new ALooper),
           mConn(new ARTSPConnection(mUIDValid, mUID)),
           mRTPConn(new ARTPConnection),
@@ -145,12 +157,9 @@
         mSessionHost = host;
     }
 
-    void connect(const sp<AMessage> &doneMsg) {
-        mDoneMsg = doneMsg;
-
-        mLooper->registerHandler(this);
-        mLooper->registerHandler(mConn);
-        (1 ? mNetLooper : mLooper)->registerHandler(mRTPConn);
+    void connect() {
+        looper()->registerHandler(mConn);
+        (1 ? mNetLooper : looper())->registerHandler(mRTPConn);
 
         sp<AMessage> notify = new AMessage('biny', id());
         mConn->observeBinaryData(notify);
@@ -159,33 +168,16 @@
         mConn->connect(mOriginalSessionURL.c_str(), reply);
     }
 
-    void disconnect(const sp<AMessage> &doneMsg) {
-        mDoneMsg = doneMsg;
-
+    void disconnect() {
         (new AMessage('abor', id()))->post();
     }
 
-    void seek(int64_t timeUs, const sp<AMessage> &doneMsg) {
+    void seek(int64_t timeUs) {
         sp<AMessage> msg = new AMessage('seek', id());
         msg->setInt64("time", timeUs);
-        msg->setMessage("doneMsg", doneMsg);
         msg->post();
     }
 
-    int64_t getNormalPlayTimeUs() {
-        int64_t maxTimeUs = 0;
-        for (size_t i = 0; i < mTracks.size(); ++i) {
-            int64_t timeUs = mTracks.editItemAt(i).mPacketSource
-                ->getNormalPlayTimeUs();
-
-            if (i == 0 || timeUs > maxTimeUs) {
-                maxTimeUs = timeUs;
-            }
-        }
-
-        return maxTimeUs;
-    }
-
     static void addRR(const sp<ABuffer> &buf) {
         uint8_t *ptr = buf->data() + buf->size();
         ptr[0] = 0x80 | 0;
@@ -619,7 +611,9 @@
                 for (size_t i = 0; i < mTracks.size(); ++i) {
                     TrackInfo *info = &mTracks.editItemAt(i);
 
-                    info->mPacketSource->signalEOS(ERROR_END_OF_STREAM);
+                    if (!mFirstAccessUnit) {
+                        postQueueEOS(i, ERROR_END_OF_STREAM);
+                    }
 
                     if (!info->mUsingInterleavedTCP) {
                         mRTPConn->removeStream(info->mRTPSocket, info->mRTCPSocket);
@@ -690,11 +684,10 @@
 
             case 'quit':
             {
-                if (mDoneMsg != NULL) {
-                    mDoneMsg->setInt32("result", UNKNOWN_ERROR);
-                    mDoneMsg->post();
-                    mDoneMsg = NULL;
-                }
+                sp<AMessage> msg = mNotify->dup();
+                msg->setInt32("what", kWhatDisconnected);
+                msg->setInt32("result", UNKNOWN_ERROR);
+                msg->post();
                 break;
             }
 
@@ -795,17 +788,12 @@
 
             case 'seek':
             {
-                sp<AMessage> doneMsg;
-                CHECK(msg->findMessage("doneMsg", &doneMsg));
-
-                if (mSeekPending) {
-                    doneMsg->post();
-                    break;
-                }
-
                 if (!mSeekable) {
                     LOGW("This is a live stream, ignoring seek request.");
-                    doneMsg->post();
+
+                    sp<AMessage> msg = mNotify->dup();
+                    msg->setInt32("what", kWhatSeekDone);
+                    msg->post();
                     break;
                 }
 
@@ -831,7 +819,6 @@
 
                 sp<AMessage> reply = new AMessage('see1', id());
                 reply->setInt64("time", timeUs);
-                reply->setMessage("doneMsg", doneMsg);
                 mConn->sendRequest(request.c_str(), reply);
                 break;
             }
@@ -842,7 +829,8 @@
                 for (size_t i = 0; i < mTracks.size(); ++i) {
                     TrackInfo *info = &mTracks.editItemAt(i);
 
-                    info->mPacketSource->flushQueue();
+                    postQueueSeekDiscontinuity(i);
+
                     info->mRTPAnchor = 0;
                     info->mNTPAnchorUs = -1;
                 }
@@ -866,11 +854,7 @@
 
                 request.append("\r\n");
 
-                sp<AMessage> doneMsg;
-                CHECK(msg->findMessage("doneMsg", &doneMsg));
-
                 sp<AMessage> reply = new AMessage('see2', id());
-                reply->setMessage("doneMsg", doneMsg);
                 mConn->sendRequest(request.c_str(), reply);
                 break;
             }
@@ -915,10 +899,9 @@
 
                 mSeekPending = false;
 
-                sp<AMessage> doneMsg;
-                CHECK(msg->findMessage("doneMsg", &doneMsg));
-
-                doneMsg->post();
+                sp<AMessage> msg = mNotify->dup();
+                msg->setInt32("what", kWhatSeekDone);
+                msg->post();
                 break;
             }
 
@@ -1056,8 +1039,14 @@
 
             LOGV("track #%d: rtpTime=%u <=> npt=%.2f", n, rtpTime, npt1);
 
-            info->mPacketSource->setNormalPlayTimeMapping(
-                    rtpTime, (int64_t)(npt1 * 1E6));
+            info->mNormalPlayTimeRTP = rtpTime;
+            info->mNormalPlayTimeUs = (int64_t)(npt1 * 1E6);
+
+            if (!mFirstAccessUnit) {
+                postNormalPlayTimeMapping(
+                        trackIndex,
+                        info->mNormalPlayTimeRTP, info->mNormalPlayTimeUs);
+            }
 
             ++n;
         }
@@ -1065,11 +1054,15 @@
         mSeekable = true;
     }
 
-    sp<APacketSource> getPacketSource(size_t index) {
+    sp<MetaData> getTrackFormat(size_t index, int32_t *timeScale) {
         CHECK_GE(index, 0u);
         CHECK_LT(index, mTracks.size());
 
-        return mTracks.editItemAt(index).mPacketSource;
+        const TrackInfo &info = mTracks.itemAt(index);
+
+        *timeScale = info.mTimeScale;
+
+        return info.mPacketSource->getFormat();
     }
 
     size_t countTracks() const {
@@ -1089,6 +1082,9 @@
         int64_t mNTPAnchorUs;
         int32_t mTimeScale;
 
+        uint32_t mNormalPlayTimeRTP;
+        int64_t mNormalPlayTimeUs;
+
         sp<APacketSource> mPacketSource;
 
         // Stores packets temporarily while no notion of time
@@ -1096,9 +1092,9 @@
         List<sp<ABuffer> > mPackets;
     };
 
+    sp<AMessage> mNotify;
     bool mUIDValid;
     uid_t mUID;
-    sp<ALooper> mLooper;
     sp<ALooper> mNetLooper;
     sp<ARTSPConnection> mConn;
     sp<ARTPConnection> mRTPConn;
@@ -1127,8 +1123,6 @@
 
     Vector<TrackInfo> mTracks;
 
-    sp<AMessage> mDoneMsg;
-
     void setupTrack(size_t index) {
         sp<APacketSource> source =
             new APacketSource(mSessionDesc, index);
@@ -1158,6 +1152,8 @@
         info->mNewSegment = true;
         info->mRTPAnchor = 0;
         info->mNTPAnchorUs = -1;
+        info->mNormalPlayTimeRTP = 0;
+        info->mNormalPlayTimeUs = 0ll;
 
         unsigned long PT;
         AString formatDesc;
@@ -1283,9 +1279,17 @@
         LOGV("onAccessUnitComplete track %d", trackIndex);
 
         if (mFirstAccessUnit) {
-            mDoneMsg->setInt32("result", OK);
-            mDoneMsg->post();
-            mDoneMsg = NULL;
+            sp<AMessage> msg = mNotify->dup();
+            msg->setInt32("what", kWhatConnected);
+            msg->post();
+
+            for (size_t i = 0; i < mTracks.size(); ++i) {
+                TrackInfo *info = &mTracks.editItemAt(i);
+
+                postNormalPlayTimeMapping(
+                        i,
+                        info->mNormalPlayTimeRTP, info->mNormalPlayTimeUs);
+            }
 
             mFirstAccessUnit = false;
         }
@@ -1303,12 +1307,12 @@
             track->mPackets.erase(track->mPackets.begin());
 
             if (addMediaTimestamp(trackIndex, track, accessUnit)) {
-                track->mPacketSource->queueAccessUnit(accessUnit);
+                postQueueAccessUnit(trackIndex, accessUnit);
             }
         }
 
         if (addMediaTimestamp(trackIndex, track, accessUnit)) {
-            track->mPacketSource->queueAccessUnit(accessUnit);
+            postQueueAccessUnit(trackIndex, accessUnit);
         }
     }
 
@@ -1344,6 +1348,39 @@
         return true;
     }
 
+    void postQueueAccessUnit(
+            size_t trackIndex, const sp<ABuffer> &accessUnit) {
+        sp<AMessage> msg = mNotify->dup();
+        msg->setInt32("what", kWhatAccessUnit);
+        msg->setSize("trackIndex", trackIndex);
+        msg->setObject("accessUnit", accessUnit);
+        msg->post();
+    }
+
+    void postQueueEOS(size_t trackIndex, status_t finalResult) {
+        sp<AMessage> msg = mNotify->dup();
+        msg->setInt32("what", kWhatEOS);
+        msg->setSize("trackIndex", trackIndex);
+        msg->setInt32("finalResult", finalResult);
+        msg->post();
+    }
+
+    void postQueueSeekDiscontinuity(size_t trackIndex) {
+        sp<AMessage> msg = mNotify->dup();
+        msg->setInt32("what", kWhatSeekDiscontinuity);
+        msg->setSize("trackIndex", trackIndex);
+        msg->post();
+    }
+
+    void postNormalPlayTimeMapping(
+            size_t trackIndex, uint32_t rtpTime, int64_t nptUs) {
+        sp<AMessage> msg = mNotify->dup();
+        msg->setInt32("what", kWhatNormalPlayTimeMapping);
+        msg->setSize("trackIndex", trackIndex);
+        msg->setInt32("rtpTime", rtpTime);
+        msg->setInt64("nptUs", nptUs);
+        msg->post();
+    }
 
     DISALLOW_EVIL_CONSTRUCTORS(MyHandler);
 };
diff --git a/media/mtp/MtpServer.cpp b/media/mtp/MtpServer.cpp
index a9b539b..dc6c011 100644
--- a/media/mtp/MtpServer.cpp
+++ b/media/mtp/MtpServer.cpp
@@ -947,7 +947,12 @@
 
     if (mSendObjectFileSize - initialData > 0) {
         mfr.offset = initialData;
-        mfr.length = mSendObjectFileSize - initialData;
+        if (mSendObjectFileSize == 0xFFFFFFFF) {
+            // tell driver to read until it receives a short packet
+            mfr.length = 0xFFFFFFFF;
+        } else {
+            mfr.length = mSendObjectFileSize - initialData;
+        }
 
         LOGV("receiving %s\n", (const char *)mSendObjectFilePath);
         // transfer the file
diff --git a/opengl/java/android/opengl/GLSurfaceView.java b/opengl/java/android/opengl/GLSurfaceView.java
index 4c7f84e..0b4f403 100644
--- a/opengl/java/android/opengl/GLSurfaceView.java
+++ b/opengl/java/android/opengl/GLSurfaceView.java
@@ -768,6 +768,9 @@
      * {@link GLSurfaceView#setEGLWindowSurfaceFactory(EGLWindowSurfaceFactory)}
      */
     public interface EGLWindowSurfaceFactory {
+        /**
+         *  @return null if the surface cannot be constructed.
+         */
         EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display, EGLConfig config,
                 Object nativeWindow);
         void destroySurface(EGL10 egl, EGLDisplay display, EGLSurface surface);
@@ -777,7 +780,19 @@
 
         public EGLSurface createWindowSurface(EGL10 egl, EGLDisplay display,
                 EGLConfig config, Object nativeWindow) {
-            return egl.eglCreateWindowSurface(display, config, nativeWindow, null);
+            EGLSurface result = null;
+            try {
+                result = egl.eglCreateWindowSurface(display, config, nativeWindow, null);
+            } catch (IllegalArgumentException e) {
+                // This exception indicates that the surface flinger surface
+                // is not valid. This can happen if the surface flinger surface has
+                // been torn down, but the application has not yet been
+                // notified via SurfaceHolder.Callback.surfaceDestroyed.
+                // In theory the application should be notified first,
+                // but in practice sometimes it is not. See b/4588890
+                Log.e(TAG, "eglCreateWindowSurface", e);
+            }
+            return result;
         }
 
         public void destroySurface(EGL10 egl, EGLDisplay display,
@@ -1041,9 +1056,8 @@
                 int error = mEgl.eglGetError();
                 if (error == EGL10.EGL_BAD_NATIVE_WINDOW) {
                     Log.e("EglHelper", "createWindowSurface returned EGL_BAD_NATIVE_WINDOW.");
-                    return null;
                 }
-                throwEglException("createWindowSurface", error);
+                return null;
             }
 
             /*
diff --git a/packages/BackupRestoreConfirmation/res/values/strings.xml b/packages/BackupRestoreConfirmation/res/values/strings.xml
index e91c6e2..5c90fd0 100644
--- a/packages/BackupRestoreConfirmation/res/values/strings.xml
+++ b/packages/BackupRestoreConfirmation/res/values/strings.xml
@@ -35,8 +35,12 @@
 
     <!-- Text for message to user that they must enter their predefined backup password in order to perform this operation. -->
     <string name="current_password_text">Please enter your current backup password below:</string>
+    <!-- Text for message to user that they must enter their device encryption password in order to perform this restore operation. -->
+    <string name="device_encryption_restore_text">Please enter your device encryption password below.</string>
+    <!-- Text for message to user that they must enter their device encryption password in order to perform this backup operation. -->
+    <string name="device_encryption_backup_text">Please enter your device encryption password below. This will also be used to encrypt the backup archive.</string>
 
-    <!-- Text for message to user that they can must enter an encryption password to use for the full backup operation. -->
+    <!-- Text for message to user that they must enter an encryption password to use for the full backup operation. -->
     <string name="backup_enc_password_text">Please enter a password to use for encrypting the full backup data. If this is left blank, your current backup password will be used:</string>
     <!-- Text for message to user that they may optionally supply an encryption password to use for a full backup operation. -->
     <string name="backup_enc_password_optional">If you wish to encrypt the full backup data, enter a password below:</string>
diff --git a/packages/BackupRestoreConfirmation/src/com/android/backupconfirm/BackupRestoreConfirmation.java b/packages/BackupRestoreConfirmation/src/com/android/backupconfirm/BackupRestoreConfirmation.java
index fbdf3cc..7f1d059 100644
--- a/packages/BackupRestoreConfirmation/src/com/android/backupconfirm/BackupRestoreConfirmation.java
+++ b/packages/BackupRestoreConfirmation/src/com/android/backupconfirm/BackupRestoreConfirmation.java
@@ -27,6 +27,8 @@
 import android.os.Message;
 import android.os.RemoteException;
 import android.os.ServiceManager;
+import android.os.storage.IMountService;
+import android.util.Log;
 import android.util.Slog;
 import android.view.View;
 import android.widget.Button;
@@ -60,8 +62,10 @@
 
     Handler mHandler;
     IBackupManager mBackupManager;
+    IMountService mMountService;
     FullObserver mObserver;
     int mToken;
+    boolean mIsEncrypted;
     boolean mDidAcknowledge;
 
     TextView mStatusView;
@@ -152,6 +156,7 @@
         }
 
         mBackupManager = IBackupManager.Stub.asInterface(ServiceManager.getService(Context.BACKUP_SERVICE));
+        mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
 
         mHandler = new ObserverHandler(getApplicationContext());
         final Object oldObserver = getLastNonConfigurationInstance();
@@ -174,8 +179,23 @@
         mEncPassword = (TextView) findViewById(R.id.enc_password);
         TextView curPwDesc = (TextView) findViewById(R.id.password_desc);
 
-        // We vary the password prompt depending on whether one is predefined
-        if (!haveBackupPassword()) {
+        // We vary the password prompt depending on whether one is predefined, and whether
+        // the device is encrypted.
+        mIsEncrypted = deviceIsEncrypted();
+        if (mIsEncrypted) {
+            Log.d(TAG, "Device is encrypted: requiring encryption pw");
+            TextView pwPrompt = (TextView) findViewById(R.id.password_desc);
+            // this password is mandatory; we hide the other options during backup
+            if (layoutId == R.layout.confirm_backup) {
+                pwPrompt.setText(R.string.device_encryption_backup_text);
+                TextView tv = (TextView) findViewById(R.id.enc_password);
+                tv.setVisibility(View.GONE);
+                tv = (TextView) findViewById(R.id.enc_password_desc);
+                tv.setVisibility(View.GONE);
+            } else {
+                pwPrompt.setText(R.string.device_encryption_restore_text);
+            }
+        } else if (!haveBackupPassword()) {
             curPwDesc.setVisibility(View.GONE);
             mCurPassword.setVisibility(View.GONE);
             if (layoutId == R.layout.confirm_backup) {
@@ -226,10 +246,12 @@
             mDidAcknowledge = true;
 
             try {
+                CharSequence encPassword = (mIsEncrypted)
+                        ? mCurPassword.getText() : mEncPassword.getText();
                 mBackupManager.acknowledgeFullBackupOrRestore(mToken,
                         allow,
                         String.valueOf(mCurPassword.getText()),
-                        String.valueOf(mEncPassword.getText()),
+                        String.valueOf(encPassword),
                         mObserver);
             } catch (RemoteException e) {
                 // TODO: bail gracefully if we can't contact the backup manager
@@ -237,6 +259,16 @@
         }
     }
 
+    boolean deviceIsEncrypted() {
+        try {
+            return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE);
+        } catch (Exception e) {
+            // If we can't talk to the mount service we have a serious problem; fail
+            // "secure" i.e. assuming that the device is encrypted.
+            return true;
+        }
+    }
+
     boolean haveBackupPassword() {
         try {
             return mBackupManager.hasBackupPassword();
diff --git a/packages/SettingsProvider/res/drawable-hdpi/ic_launcher_settings.png b/packages/SettingsProvider/res/drawable-hdpi/ic_launcher_settings.png
index ff34a7f..8a5a2f7 100644
--- a/packages/SettingsProvider/res/drawable-hdpi/ic_launcher_settings.png
+++ b/packages/SettingsProvider/res/drawable-hdpi/ic_launcher_settings.png
Binary files differ
diff --git a/packages/SettingsProvider/res/drawable-mdpi/ic_launcher_settings.png b/packages/SettingsProvider/res/drawable-mdpi/ic_launcher_settings.png
index b08ad3b..803439f 100644
--- a/packages/SettingsProvider/res/drawable-mdpi/ic_launcher_settings.png
+++ b/packages/SettingsProvider/res/drawable-mdpi/ic_launcher_settings.png
Binary files differ
diff --git a/packages/SettingsProvider/res/drawable-xhdpi/ic_launcher_settings.png b/packages/SettingsProvider/res/drawable-xhdpi/ic_launcher_settings.png
new file mode 100644
index 0000000..ec3c8ea
--- /dev/null
+++ b/packages/SettingsProvider/res/drawable-xhdpi/ic_launcher_settings.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/recents_callout_line.9.png b/packages/SystemUI/res/drawable-hdpi/recents_callout_line.9.png
deleted file mode 100644
index 335d5a8..0000000
--- a/packages/SystemUI/res/drawable-hdpi/recents_callout_line.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/recents_thumbnail_bg_normal.9.png b/packages/SystemUI/res/drawable-hdpi/recents_thumbnail_bg_normal.9.png
new file mode 100644
index 0000000..d000f7e
--- /dev/null
+++ b/packages/SystemUI/res/drawable-hdpi/recents_thumbnail_bg_normal.9.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/recents_callout_line.9.png b/packages/SystemUI/res/drawable-mdpi/recents_callout_line.9.png
deleted file mode 100644
index 724a5cd..0000000
--- a/packages/SystemUI/res/drawable-mdpi/recents_callout_line.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/recents_thumbnail_bg_normal.9.png b/packages/SystemUI/res/drawable-mdpi/recents_thumbnail_bg_normal.9.png
new file mode 100644
index 0000000..f19dc93
--- /dev/null
+++ b/packages/SystemUI/res/drawable-mdpi/recents_thumbnail_bg_normal.9.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xhdpi/recents_callout_line.9.png b/packages/SystemUI/res/drawable-xhdpi/recents_callout_line.9.png
deleted file mode 100644
index 1bd018a..0000000
--- a/packages/SystemUI/res/drawable-xhdpi/recents_callout_line.9.png
+++ /dev/null
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xhdpi/recents_thumbnail_bg_normal.9.png b/packages/SystemUI/res/drawable-xhdpi/recents_thumbnail_bg_normal.9.png
new file mode 100644
index 0000000..80fc849
--- /dev/null
+++ b/packages/SystemUI/res/drawable-xhdpi/recents_thumbnail_bg_normal.9.png
Binary files differ
diff --git a/packages/SystemUI/res/layout-land/status_bar_recent_item.xml b/packages/SystemUI/res/layout-land/status_bar_recent_item.xml
index 58355bd..83c4faf 100644
--- a/packages/SystemUI/res/layout-land/status_bar_recent_item.xml
+++ b/packages/SystemUI/res/layout-land/status_bar_recent_item.xml
@@ -26,16 +26,17 @@
     android:paddingRight="@dimen/status_bar_recents_item_padding">
 
     <RelativeLayout android:id="@+id/recent_item"
-        android:layout_gravity="bottom"
+        android:layout_gravity="center_vertical"
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
-        android:paddingBottom="@*android:dimen/status_bar_height">
+        android:paddingTop="@*android:dimen/status_bar_height">
 
         <FrameLayout android:id="@+id/app_thumbnail"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentLeft="true"
             android:layout_alignParentTop="true"
+            android:layout_marginTop="@dimen/status_bar_recents_thumbnail_top_margin"
             android:layout_marginLeft="@dimen/status_bar_recents_thumbnail_left_margin"
             android:background="@drawable/recents_thumbnail_bg"
             android:foreground="@drawable/recents_thumbnail_fg">
@@ -44,19 +45,22 @@
                 android:layout_height="@dimen/status_bar_recents_thumbnail_height"
                 android:visibility="invisible"
             />
-
-            <ImageView android:id="@+id/app_icon"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_marginTop="@dimen/status_bar_recents_app_icon_top_margin"
-                android:layout_marginLeft="@dimen/status_bar_recents_app_icon_left_margin"
-                android:maxWidth="@dimen/status_bar_recents_app_icon_max_width"
-                android:maxHeight="@dimen/status_bar_recents_app_icon_max_height"
-                android:adjustViewBounds="true"
-                android:visibility="invisible"
-            />
         </FrameLayout>
 
+        <ImageView android:id="@+id/app_icon"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_marginTop="@dimen/status_bar_recents_app_icon_top_margin"
+            android:layout_marginLeft="@dimen/status_bar_recents_app_icon_left_margin"
+            android:layout_alignParentLeft="true"
+            android:layout_alignParentTop="true"
+            android:maxWidth="@dimen/status_bar_recents_app_icon_max_width"
+            android:maxHeight="@dimen/status_bar_recents_app_icon_max_height"
+            android:scaleType="centerInside"
+            android:adjustViewBounds="true"
+            android:visibility="invisible"
+        />
+
         <TextView android:id="@+id/app_label"
             android:layout_width="@dimen/status_bar_recents_app_label_width"
             android:layout_height="wrap_content"
@@ -67,6 +71,7 @@
             android:layout_alignLeft="@id/app_thumbnail"
             android:layout_below="@id/app_thumbnail"
             android:layout_marginTop="@dimen/status_bar_recents_text_description_padding"
+            android:layout_marginLeft="@dimen/status_bar_recents_app_label_left_margin"
             android:singleLine="true"
             android:ellipsize="marquee"
             android:visibility="invisible"
diff --git a/packages/SystemUI/res/layout-port/status_bar_recent_item.xml b/packages/SystemUI/res/layout-port/status_bar_recent_item.xml
index 8c82eb1..3d8b9d6 100644
--- a/packages/SystemUI/res/layout-port/status_bar_recent_item.xml
+++ b/packages/SystemUI/res/layout-port/status_bar_recent_item.xml
@@ -26,32 +26,10 @@
     android:paddingBottom="@dimen/status_bar_recents_item_padding">
 
     <RelativeLayout android:id="@+id/recent_item"
+        android:layout_gravity="center_horizontal"
         android:layout_height="wrap_content"
-        android:layout_width="match_parent">
+        android:layout_width="wrap_content">
 
-        <FrameLayout android:id="@+id/app_thumbnail"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_alignParentLeft="true"
-            android:layout_alignParentTop="true"
-            android:layout_marginLeft="@dimen/status_bar_recents_thumbnail_left_margin"
-            android:background="@drawable/recents_thumbnail_bg"
-            android:foreground="@drawable/recents_thumbnail_fg">
-            <ImageView android:id="@+id/app_thumbnail_image"
-                android:layout_width="@dimen/status_bar_recents_thumbnail_width"
-                android:layout_height="@dimen/status_bar_recents_thumbnail_height"
-                android:visibility="invisible"
-            />
-            <ImageView android:id="@+id/app_icon"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_marginLeft="@dimen/status_bar_recents_app_icon_left_margin"
-                android:layout_marginTop="@dimen/status_bar_recents_app_icon_top_margin"
-                android:maxWidth="@dimen/status_bar_recents_app_icon_max_width"
-                android:maxHeight="@dimen/status_bar_recents_app_icon_max_height"
-                android:adjustViewBounds="true"
-            />
-        </FrameLayout>
         <TextView android:id="@+id/app_label"
             android:layout_width="@dimen/status_bar_recents_app_label_width"
             android:layout_height="wrap_content"
@@ -61,12 +39,26 @@
             android:scrollHorizontally="true"
             android:layout_alignParentLeft="true"
             android:layout_alignTop="@id/app_icon"
+            android:paddingTop="2dp"
             android:layout_marginLeft="@dimen/status_bar_recents_app_label_left_margin"
             android:singleLine="true"
             android:ellipsize="marquee"
             android:textColor="@color/status_bar_recents_app_label_color"
         />
-
+        <FrameLayout android:id="@+id/app_thumbnail"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_alignParentTop="true"
+            android:layout_toRightOf="@id/app_label"
+            android:layout_marginLeft="@dimen/status_bar_recents_thumbnail_left_margin"
+            android:background="@drawable/recents_thumbnail_bg"
+            android:foreground="@drawable/recents_thumbnail_fg">
+            <ImageView android:id="@+id/app_thumbnail_image"
+                android:layout_width="@dimen/status_bar_recents_thumbnail_width"
+                android:layout_height="@dimen/status_bar_recents_thumbnail_height"
+                android:visibility="invisible"
+            />
+        </FrameLayout>
         <View android:id="@+id/recents_callout_line"
             android:layout_width="@dimen/status_bar_recents_app_label_width"
             android:layout_height="1dip"
@@ -79,6 +71,18 @@
             android:background="@drawable/recents_callout_line"
         />
 
+        <ImageView android:id="@+id/app_icon"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:layout_toRightOf="@id/app_label"
+            android:layout_marginLeft="@dimen/status_bar_recents_app_icon_left_margin"
+            android:layout_marginTop="@dimen/status_bar_recents_app_icon_top_margin"
+            android:maxWidth="@dimen/status_bar_recents_app_icon_max_width"
+            android:maxHeight="@dimen/status_bar_recents_app_icon_max_height"
+            android:scaleType="centerInside"
+            android:adjustViewBounds="true"
+        />
+
         <TextView android:id="@+id/app_description"
             android:layout_width="@dimen/status_bar_recents_app_label_width"
             android:layout_height="wrap_content"
diff --git a/packages/SystemUI/res/layout/global_screenshot.xml b/packages/SystemUI/res/layout/global_screenshot.xml
index 6cb8799..6d70135 100644
--- a/packages/SystemUI/res/layout/global_screenshot.xml
+++ b/packages/SystemUI/res/layout/global_screenshot.xml
@@ -25,6 +25,7 @@
         android:id="@+id/global_screenshot_container"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
+        android:layout_gravity="center"
         android:background="@drawable/global_screenshot_background"
         android:visibility="gone">
         <ImageView android:id="@+id/global_screenshot"
@@ -32,9 +33,4 @@
             android:layout_height="wrap_content"
             android:adjustViewBounds="true" />
     </FrameLayout>
-    <ImageView android:id="@+id/global_screenshot_flash"
-        android:layout_width="match_parent"
-        android:layout_height="match_parent"
-        android:background="#FFFFFFFF"
-        android:visibility="gone" />
 </FrameLayout>
diff --git a/packages/SystemUI/res/layout/status_bar.xml b/packages/SystemUI/res/layout/status_bar.xml
index a63893e..af2c93c 100644
--- a/packages/SystemUI/res/layout/status_bar.xml
+++ b/packages/SystemUI/res/layout/status_bar.xml
@@ -77,7 +77,6 @@
             android:layout_height="match_parent"
             android:singleLine="true"
             android:paddingRight="6dip"
-            android:textSize="16sp"
             android:gravity="center_vertical|left"
             />
     </LinearLayout>
@@ -89,17 +88,19 @@
         android:animationCache="false"
         android:orientation="horizontal" >
         <ImageSwitcher android:id="@+id/tickerIcon"
-            android:layout_width="wrap_content"
-            android:layout_height="match_parent"
-            android:layout_marginRight="8dip"
+            android:layout_width="@dimen/status_bar_icon_size"
+            android:layout_height="@dimen/status_bar_icon_size"
+            android:layout_marginRight="4dip"
             >
             <com.android.systemui.statusbar.AnimatedImageView
-                android:layout_width="25dip"
-                android:layout_height="25dip"
+                android:layout_width="@dimen/status_bar_icon_size"
+                android:layout_height="@dimen/status_bar_icon_size"
+                android:scaleType="center"
                 />
             <com.android.systemui.statusbar.AnimatedImageView
-                android:layout_width="25dip"
-                android:layout_height="25dip"
+                android:layout_width="@dimen/status_bar_icon_size"
+                android:layout_height="@dimen/status_bar_icon_size"
+                android:scaleType="center"
                 />
         </ImageSwitcher>
         <com.android.systemui.statusbar.phone.TickerView android:id="@+id/tickerText"
@@ -109,13 +110,13 @@
             android:paddingTop="2dip"
             android:paddingRight="10dip">
             <TextView
-                android:textAppearance="@*android:style/TextAppearance.StatusBar.Ticker"
+                android:textAppearance="@style/TextAppearance.StatusBar.PhoneTicker"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:singleLine="true"
                 />
             <TextView
-                android:textAppearance="@*android:style/TextAppearance.StatusBar.Ticker"
+                android:textAppearance="@style/TextAppearance.StatusBar.PhoneTicker"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:singleLine="true"
diff --git a/packages/SystemUI/res/layout/status_bar_expanded.xml b/packages/SystemUI/res/layout/status_bar_expanded.xml
index 3e2def5..cd4e37c 100644
--- a/packages/SystemUI/res/layout/status_bar_expanded.xml
+++ b/packages/SystemUI/res/layout/status_bar_expanded.xml
@@ -35,7 +35,7 @@
         android:background="@drawable/notification_header_bg"
         >
         <com.android.systemui.statusbar.policy.DateView android:id="@+id/date"
-            android:textAppearance="@style/TextAppearance.StatusBar.Clock"
+            android:textAppearance="@style/TextAppearance.StatusBar.Date"
             android:layout_width="wrap_content"
             android:layout_height="match_parent"
             android:layout_alignParentLeft="true"
diff --git a/packages/SystemUI/res/layout/status_bar_no_recent_apps.xml b/packages/SystemUI/res/layout/status_bar_no_recent_apps.xml
index 47ffb83..1675773 100644
--- a/packages/SystemUI/res/layout/status_bar_no_recent_apps.xml
+++ b/packages/SystemUI/res/layout/status_bar_no_recent_apps.xml
@@ -27,8 +27,8 @@
     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:textSize="24dp"
-        android:textColor="#ffffffff"
+        android:textSize="20dp"
+        android:textColor="@android:color/holo_blue_light"
         android:text="@string/status_bar_no_recent_apps"
         android:gravity="center_horizontal"
         android:layout_gravity="center"
diff --git a/packages/SystemUI/res/values-land/dimens.xml b/packages/SystemUI/res/values-land/dimens.xml
index 32ebc80..e7c8b1f 100644
--- a/packages/SystemUI/res/values-land/dimens.xml
+++ b/packages/SystemUI/res/values-land/dimens.xml
@@ -23,15 +23,18 @@
     <!-- How far the thumbnail for a recent app appears from left edge -->
     <dimen name="status_bar_recents_thumbnail_left_margin">0dp</dimen>
     <!-- How far the thumbnail for a recent app appears from top edge -->
-    <dimen name="status_bar_recents_thumbnail_top_margin">12dp</dimen>
+    <dimen name="status_bar_recents_thumbnail_top_margin">28dp</dimen>
     <!-- Padding for text descriptions -->
     <dimen name="status_bar_recents_text_description_padding">8dp</dimen>
     <!-- Width of application label text -->
     <dimen name="status_bar_recents_app_label_width">156dip</dimen>
     <!-- Left margin of application label text -->
-    <dimen name="status_bar_recents_app_label_left_margin">16dip</dimen>
+    <dimen name="status_bar_recents_app_label_left_margin">12dip</dimen>
     <!-- Margin between recents container and glow on the right -->
     <dimen name="status_bar_recents_right_glow_margin">0dip</dimen>
     <!-- Padding between recents items -->
     <dimen name="status_bar_recents_item_padding">2dip</dimen>
+    <!-- Where to place the app icon over the thumbnail -->
+    <dimen name="status_bar_recents_app_icon_left_margin">8dp</dimen>
+    <dimen name="status_bar_recents_app_icon_top_margin">8dp</dimen>
 </resources>
diff --git a/packages/SystemUI/res/values-port/dimens.xml b/packages/SystemUI/res/values-port/dimens.xml
index 2bafd30..de7b836 100644
--- a/packages/SystemUI/res/values-port/dimens.xml
+++ b/packages/SystemUI/res/values-port/dimens.xml
@@ -18,15 +18,18 @@
 <resources>
     <!-- Recent Applications parameters -->
     <!-- How far the thumbnail for a recent app appears from left edge -->
-    <dimen name="status_bar_recents_thumbnail_left_margin">110dp</dimen>
+    <dimen name="status_bar_recents_thumbnail_left_margin">20dp</dimen>
     <!-- Padding for text descriptions -->
     <dimen name="status_bar_recents_text_description_padding">8dp</dimen>
     <!-- Width of application label text -->
     <dimen name="status_bar_recents_app_label_width">88dip</dimen>
     <!-- Left margin of application label text -->
-    <dimen name="status_bar_recents_app_label_left_margin">16dip</dimen>
+    <dimen name="status_bar_recents_app_label_left_margin">0dip</dimen>
     <!-- Margin between recents container and glow on the right -->
     <dimen name="status_bar_recents_right_glow_margin">100dip</dimen>
     <!-- Padding between recents items -->
     <dimen name="status_bar_recents_item_padding">0dip</dimen>
+    <!-- Where to place the app icon over the thumbnail -->
+    <dimen name="status_bar_recents_app_icon_left_margin">0dp</dimen>
+    <dimen name="status_bar_recents_app_icon_top_margin">8dp</dimen>
 </resources>
diff --git a/packages/SystemUI/res/values/colors.xml b/packages/SystemUI/res/values/colors.xml
index c88d651..555baa2 100644
--- a/packages/SystemUI/res/values/colors.xml
+++ b/packages/SystemUI/res/values/colors.xml
@@ -29,4 +29,5 @@
     <drawable name="notification_header_bg">#d8000000</drawable>
     <drawable name="notification_tracking_bg">#d8000000</drawable>
     <color name="notification_list_shadow_top">#80000000</color>
+    <drawable name="recents_callout_line">#66ffffff</drawable>
 </resources>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 830506c..bbc66cf 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -21,21 +21,18 @@
 
     <!-- Recent Applications parameters -->
     <!-- Upper width limit for application icon -->
-    <dimen name="status_bar_recents_app_icon_max_width">64dp</dimen>
+    <dimen name="status_bar_recents_app_icon_max_width">48dp</dimen>
     <!-- Upper height limit for application icon -->
-    <dimen name="status_bar_recents_app_icon_max_height">64dp</dimen>
-    <!-- Where to place the app icon over the thumbnail -->
-    <dimen name="status_bar_recents_app_icon_left_margin">13dp</dimen>
-    <dimen name="status_bar_recents_app_icon_top_margin">13dp</dimen>
+    <dimen name="status_bar_recents_app_icon_max_height">48dp</dimen>
 
     <!-- Size of application thumbnail -->
     <dimen name="status_bar_recents_thumbnail_width">164dp</dimen>
     <dimen name="status_bar_recents_thumbnail_height">145dp</dimen>
 
     <!-- Size of application label text -->
-    <dimen name="status_bar_recents_app_label_text_size">16dip</dimen>
+    <dimen name="status_bar_recents_app_label_text_size">14dip</dimen>
     <!-- Size of application description text -->
-    <dimen name="status_bar_recents_app_description_text_size">16dip</dimen>
+    <dimen name="status_bar_recents_app_description_text_size">14dip</dimen>
     <!-- Size of fading edge for scroll effect -->
     <dimen name="status_bar_recents_fading_edge_length">20dip</dimen>
     <!-- Margin between recents container and glow on the right -->
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index e971896..612c8e7 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -70,7 +70,7 @@
     <string name="status_bar_latest_events_title">Notifications</string>
 
     <!-- When the battery is low, this is displayed to the user in a dialog.  The title of the low battery alert.  [CHAR LIMIT=NONE]-->
-    <string name="battery_low_title">Please connect charger</string>
+    <string name="battery_low_title">Connect charger</string>
 
     <!-- When the battery is low, this is displayed to the user in a dialog. The subtitle of the low battery alert. [CHAR LIMIT=NONE] -->
     <string name="battery_low_subtitle">The battery is getting low.</string>
@@ -122,16 +122,16 @@
     <!-- Network connection string for Bluetooth Reverse Tethering -->
     <string name="bluetooth_tethered">Bluetooth tethered</string>
     <!-- Title of a button to open the settings for input methods [CHAR LIMIT=30] -->
-    <string name="status_bar_input_method_settings_configure_input_methods">Configure input methods</string>
+    <string name="status_bar_input_method_settings_configure_input_methods">Set up input methods</string>
 
     <!-- Label of a toggle switch to disable use of the physical keyboard in favor of the IME. [CHAR LIMIT=25] -->
     <string name="status_bar_use_physical_keyboard">Use physical keyboard</string>
 
     <!-- Prompt for the USB device permission dialog [CHAR LIMIT=80] -->
-    <string name="usb_device_permission_prompt">Allow the application <xliff:g id="application">%1$s</xliff:g> to access the USB device?</string>
+    <string name="usb_device_permission_prompt">Allow the app <xliff:g id="application">%1$s</xliff:g> to access the USB device?</string>
 
     <!-- Prompt for the USB accessory permission dialog [CHAR LIMIT=80] -->
-    <string name="usb_accessory_permission_prompt">Allow the application <xliff:g id="application">%1$s</xliff:g> to access the USB accessory?</string>
+    <string name="usb_accessory_permission_prompt">Allow the app <xliff:g id="application">%1$s</xliff:g> to access the USB accessory?</string>
 
     <!-- Prompt for the USB device confirm dialog [CHAR LIMIT=80] -->
     <string name="usb_device_confirm_prompt">Open <xliff:g id="activity">%1$s</xliff:g> when this USB device is connected?</string>
@@ -140,7 +140,7 @@
     <string name="usb_accessory_confirm_prompt">Open <xliff:g id="activity">%1$s</xliff:g> when this USB accessory is connected?</string>
 
     <!-- Prompt for the USB accessory URI dialog [CHAR LIMIT=80] -->
-    <string name="usb_accessory_uri_prompt">No installed applications work with this USB accessory. Learn more about this accessory at <xliff:g id="url">%1$s</xliff:g></string>
+    <string name="usb_accessory_uri_prompt">No installed apps work with this USB accessory. Learn more about this accessory at <xliff:g id="url">%1$s</xliff:g></string>
 
     <!-- Title for USB accessory dialog.  Used when the name of the accessory cannot be determined.  [CHAR LIMIT=50] -->
     <string name="title_usb_accessory">USB accessory</string>
@@ -163,15 +163,25 @@
     <string name="compat_mode_off">Stretch to fill screen</string>
 
     <!-- Compatibility mode help screen: header text. [CHAR LIMIT=50] -->
-    <string name="compat_mode_help_header">Compatibility Zoom</string>
+    <string name="compat_mode_help_header">Compatibility zoom</string>
 
     <!-- Compatibility mode help screen: body text. [CHAR LIMIT=150] -->
     <string name="compat_mode_help_body">When an app was designed for a smaller screen, a zoom control will appear by the clock.</string>
 
-    <!-- toast message displayed when a screenshot is saved to the Gallery. -->
-    <string name="screenshot_saving_toast">Screenshot saved to Gallery</string>
-    <!-- toast message displayed when we fail to take a screenshot. -->
-    <string name="screenshot_failed_toast">Could not save screenshot. External storage may be in use.</string>
+    <!-- Notification ticker displayed when a screenshot is being saved to the Gallery. [CHAR LIMIT=30] -->
+    <string name="screenshot_saving_ticker">Saving\u2026</string>
+    <!-- Notification title displayed when a screenshot is being saved to the Gallery. [CHAR LIMIT=50] -->
+    <string name="screenshot_saving_title">Saving screenshot\u2026</string>
+    <!-- Notification text displayed when a screenshot is being saved to the Gallery. [CHAR LIMIT=100] -->
+    <string name="screenshot_saving_text">Screenshot is being saved.</string>
+    <!-- Notification title displayed when a screenshot is saved to the Gallery. [CHAR LIMIT=50] -->
+    <string name="screenshot_saved_title">Screenshot captured.</string>
+    <!-- Notification text displayed when a screenshot is saved to the Gallery. [CHAR LIMIT=100] -->
+    <string name="screenshot_saved_text">Touch to view your screenshot.</string>
+    <!-- Notification title displayed when we fail to take a screenshot. [CHAR LIMIT=50] -->
+    <string name="screenshot_failed_title">Couldn\'t capture screenshot.</string>
+    <!-- Notification text displayed when we fail to take a screenshot. [CHAR LIMIT=100] -->
+    <string name="screenshot_failed_text">Couldn\'t save screenshot. External storage may be in use.</string>
 
     <!-- Title for the USB function chooser in UsbPreferenceActivity. [CHAR LIMIT=30] -->
     <string name="usb_preference_title">USB file transfer options</string>
@@ -180,7 +190,7 @@
     <!-- Label for the PTP USB function in UsbPreferenceActivity. [CHAR LIMIT=50] -->
     <string name="use_ptp_button_title">Mount as a camera (PTP)</string>
     <!-- Label for the installer CD image option in UsbPreferenceActivity. [CHAR LIMIT=50] -->
-    <string name="installer_cd_button_title">Install Android File Transfer application for Mac</string>
+    <string name="installer_cd_button_title">Install Android File Transfer app for Mac</string>
 
     <!-- Content description of the back button for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
     <string name="accessibility_back">Back</string>
@@ -238,15 +248,15 @@
     <string name="accessibility_data_signal_full">Data signal full.</string>
 
     <!-- Content description of the WIFI signal when no signal for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
-    <string name="accessibility_no_wifi">No WiFi.</string>
+    <string name="accessibility_no_wifi">No Wi-Fi.</string>
     <!-- Content description of the WIFI signal when it is one bar for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
-    <string name="accessibility_wifi_one_bar">WiFi one bar.</string>
+    <string name="accessibility_wifi_one_bar">Wi-Fi one bar.</string>
     <!-- Content description of the WIFI signal when it is two bars for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
-    <string name="accessibility_wifi_two_bars">WiFi two bars.</string>
+    <string name="accessibility_wifi_two_bars">Wi-Fi two bars.</string>
     <!-- Content description of the WIFI signal when it is three bars for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
-    <string name="accessibility_wifi_three_bars">WiFi three bars.</string>
+    <string name="accessibility_wifi_three_bars">Wi-Fi three bars.</string>
     <!-- Content description of the WIFI signal when it is full for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
-    <string name="accessibility_wifi_signal_full">WiFi signal full.</string>
+    <string name="accessibility_wifi_signal_full">Wi-Fi signal full.</string>
 
     <!-- Content description of the data connection type GPRS for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
     <string name="accessibility_data_connection_gprs">GPRS</string>
@@ -267,7 +277,7 @@
     <string name="accessibility_data_connection_edge">Edge</string>
 
     <!-- Content description of the data connection type WiFi for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
-    <string name="accessibility_data_connection_wifi">WiFi</string>
+    <string name="accessibility_data_connection_wifi">Wi-Fi</string>
 
     <!-- Content description of the data connection with no SIM for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
     <string name="accessibility_no_sim">No SIM.</string>
@@ -305,6 +315,9 @@
     <!-- Content description of the ringer silent icon in the notification panel for accessibility (not shown on the screen). [CHAR LIMIT=NONE] -->
     <string name="accessibility_ringer_silent">Ringer silent.</string>
 
+    <!-- Content description to tell the user an application has been removed from recents -->
+    <string name="accessibility_recents_item_dismissed"><xliff:g id="app" example="Calendar">%s</xliff:g> dismissed.</string>
+
     <!-- Title of dialog shown when 2G-3G data usage has exceeded limit and has been disabled. [CHAR LIMIT=48] -->
     <string name="data_usage_disabled_dialog_3g_title">2G-3G data disabled</string>
     <!-- Title of dialog shown when 4G data usage has exceeded limit and has been disabled. [CHAR LIMIT=48] -->
@@ -314,7 +327,7 @@
     <!-- Title of dialog shown when data usage has exceeded limit and has been disabled. [CHAR LIMIT=48] -->
     <string name="data_usage_disabled_dialog_title">Data disabled</string>
     <!-- Body of dialog shown when data usage has exceeded limit and has been disabled. [CHAR LIMIT=NONE] -->
-    <string name="data_usage_disabled_dialog">The specified data usage limit has been reached.\n\nAdditional data use may incur carrier charges.</string>
+    <string name="data_usage_disabled_dialog">You\'ve reached the specified data usage limit.\n\nIf you re-enable data, you may be charged by the operator.</string>
     <!-- Dialog button indicating that data connection should be re-enabled. [CHAR LIMIT=28] -->
     <string name="data_usage_disabled_dialog_enable">Re-enable data</string>
 
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index 3d49cd1..dc5c540 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -41,6 +41,13 @@
     </style>
 
     <style name="TextAppearance.StatusBar.Clock" parent="@*android:style/TextAppearance.StatusBar.Icon">
+        <!-- Note: must be dp to fit in status bar -->
+        <item name="android:textSize">16dp</item>
+        <item name="android:textStyle">normal</item>
+        <item name="android:textColor">@android:color/holo_blue_light</item>
+    </style>
+
+    <style name="TextAppearance.StatusBar.Date" parent="@*android:style/TextAppearance.StatusBar.Icon">
         <item name="android:textSize">16sp</item>
         <item name="android:textStyle">normal</item>
         <item name="android:textColor">@android:color/holo_blue_light</item>
@@ -69,4 +76,10 @@
         <item name="android:windowExitAnimation">@anim/priority_alert_exit</item>
     </style>
 
+    <style name="TextAppearance.StatusBar.PhoneTicker"
+        parent="@*android:style/TextAppearance.StatusBar.Ticker">
+        <!-- Note: must be dp to fit in status bar -->
+        <item name="android:textSize">14dp</item>
+    </style>
+    
 </resources>
diff --git a/packages/SystemUI/src/com/android/systemui/recent/RecentsPanelView.java b/packages/SystemUI/src/com/android/systemui/recent/RecentsPanelView.java
index 5b4c33e..8d5c33f 100644
--- a/packages/SystemUI/src/com/android/systemui/recent/RecentsPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/recent/RecentsPanelView.java
@@ -38,6 +38,7 @@
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup;
+import android.view.accessibility.AccessibilityEvent;
 import android.view.animation.AnimationUtils;
 import android.widget.AdapterView;
 import android.widget.BaseAdapter;
@@ -483,7 +484,8 @@
         } else {
             Intent intent = ad.intent;
             intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
-                    | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
+                    | Intent.FLAG_ACTIVITY_TASK_ON_HOME
+                    | Intent.FLAG_ACTIVITY_NEW_TASK);
             if (DEBUG) Log.v(TAG, "Starting activity " + intent);
             context.startActivity(intent);
         }
@@ -511,6 +513,12 @@
         final ActivityManager am = (ActivityManager)
                 mContext.getSystemService(Context.ACTIVITY_SERVICE);
         am.removeTask(ad.persistentTaskId, ActivityManager.REMOVE_TASK_KILL_PROCESS);
+
+        // Accessibility feedback
+        setContentDescription(
+                mContext.getString(R.string.accessibility_recents_item_dismissed, ad.getLabel()));
+        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
+        setContentDescription(null);
     }
 
     private void startApplicationDetailsActivity(String packageName) {
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java b/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java
index 3fa3078..cf073c4 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java
@@ -19,27 +19,27 @@
 import android.animation.Animator;
 import android.animation.AnimatorListenerAdapter;
 import android.animation.AnimatorSet;
-import android.animation.ObjectAnimator;
 import android.animation.TimeInterpolator;
 import android.animation.ValueAnimator;
 import android.animation.ValueAnimator.AnimatorUpdateListener;
-import android.app.Activity;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
 import android.content.ContentResolver;
 import android.content.ContentValues;
 import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
 import android.graphics.Matrix;
 import android.graphics.PixelFormat;
-import android.media.MediaScannerConnection;
 import android.net.Uri;
 import android.os.AsyncTask;
-import android.os.Binder;
 import android.os.Environment;
 import android.os.ServiceManager;
 import android.provider.MediaStore;
 import android.util.DisplayMetrics;
-import android.util.Log;
 import android.view.Display;
 import android.view.IWindowManager;
 import android.view.LayoutInflater;
@@ -50,16 +50,11 @@
 import android.view.WindowManager;
 import android.widget.FrameLayout;
 import android.widget.ImageView;
-import android.widget.TextView;
-import android.widget.Toast;
 
 import com.android.systemui.R;
 
 import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
 import java.io.OutputStream;
-import java.lang.Thread;
 import java.text.SimpleDateFormat;
 import java.util.Date;
 
@@ -83,6 +78,46 @@
     private static final String SCREENSHOT_FILE_NAME_TEMPLATE = "Screenshot_%s.png";
     private static final String SCREENSHOT_FILE_PATH_TEMPLATE = "%s/%s/%s";
 
+    private int mNotificationId;
+    private NotificationManager mNotificationManager;
+    private Notification.Builder mNotificationBuilder;
+    private Intent mLaunchIntent;
+    private String mImageDir;
+    private String mImageFileName;
+    private String mImageFilePath;
+    private String mImageDate;
+    private long mImageTime;
+
+    SaveImageInBackgroundTask(Context context, NotificationManager nManager, int nId) {
+        Resources r = context.getResources();
+
+        // Prepare all the output metadata
+        mImageTime = System.currentTimeMillis();
+        mImageDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(mImageTime));
+        mImageDir = Environment.getExternalStoragePublicDirectory(
+                Environment.DIRECTORY_PICTURES).getAbsolutePath();
+        mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, mImageDate);
+        mImageFilePath = String.format(SCREENSHOT_FILE_PATH_TEMPLATE, mImageDir,
+                SCREENSHOTS_DIR_NAME, mImageFileName);
+
+        // Show the intermediate notification
+        mLaunchIntent = new Intent(Intent.ACTION_VIEW);
+        mLaunchIntent.setDataAndType(Uri.fromFile(new File(mImageFilePath)), "image/png");
+        mLaunchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        mNotificationId = nId;
+        mNotificationBuilder = new Notification.Builder(context)
+            .setTicker(r.getString(R.string.screenshot_saving_ticker))
+            .setContentTitle(r.getString(R.string.screenshot_saving_title))
+            .setContentText(r.getString(R.string.screenshot_saving_text))
+            .setSmallIcon(android.R.drawable.ic_menu_gallery)
+            .setWhen(System.currentTimeMillis());
+        Notification n = mNotificationBuilder.getNotification();
+        n.flags |= Notification.FLAG_NO_CLEAR;
+
+        mNotificationManager = nManager;
+        mNotificationManager.notify(nId, n);
+    }
+
     @Override
     protected SaveImageInBackgroundData doInBackground(SaveImageInBackgroundData... params) {
         if (params.length != 1) return null;
@@ -91,23 +126,15 @@
         Bitmap image = params[0].image;
 
         try {
-            long currentTime = System.currentTimeMillis();
-            String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(currentTime));
-            String imageDir = Environment.getExternalStoragePublicDirectory(
-                    Environment.DIRECTORY_PICTURES).getAbsolutePath();
-            String imageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, date);
-            String imageFilePath = String.format(SCREENSHOT_FILE_PATH_TEMPLATE, imageDir,
-                    SCREENSHOTS_DIR_NAME, imageFileName);
-
             // Save the screenshot to the MediaStore
             ContentValues values = new ContentValues();
             ContentResolver resolver = context.getContentResolver();
-            values.put(MediaStore.Images.ImageColumns.DATA, imageFilePath);
-            values.put(MediaStore.Images.ImageColumns.TITLE, imageFileName);
-            values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, imageFileName);
-            values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, currentTime);
-            values.put(MediaStore.Images.ImageColumns.DATE_ADDED, currentTime);
-            values.put(MediaStore.Images.ImageColumns.DATE_MODIFIED, currentTime);
+            values.put(MediaStore.Images.ImageColumns.DATA, mImageFilePath);
+            values.put(MediaStore.Images.ImageColumns.TITLE, mImageFileName);
+            values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, mImageFileName);
+            values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, mImageTime);
+            values.put(MediaStore.Images.ImageColumns.DATE_ADDED, mImageTime);
+            values.put(MediaStore.Images.ImageColumns.DATE_MODIFIED, mImageTime);
             values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/png");
             Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
 
@@ -118,7 +145,7 @@
 
             // update file size in the database
             values.clear();
-            values.put(MediaStore.Images.ImageColumns.SIZE, new File(imageFilePath).length());
+            values.put(MediaStore.Images.ImageColumns.SIZE, new File(mImageFilePath).length());
             resolver.update(uri, values, null, null);
 
             params[0].result = 0;
@@ -135,12 +162,22 @@
     protected void onPostExecute(SaveImageInBackgroundData params) {
         if (params.result > 0) {
             // Show a message that we've failed to save the image to disk
-            Toast.makeText(params.context, R.string.screenshot_failed_toast,
-                    Toast.LENGTH_SHORT).show();
+            GlobalScreenshot.notifyScreenshotError(params.context, mNotificationManager);
         } else {
-            // Show a message that we've saved the screenshot to disk
-            Toast.makeText(params.context, R.string.screenshot_saving_toast,
-                    Toast.LENGTH_SHORT).show();
+            // Show the final notification to indicate screenshot saved
+            Resources r = params.context.getResources();
+
+            mNotificationBuilder
+                .setTicker(r.getString(R.string.screenshot_saved_title))
+                .setContentTitle(r.getString(R.string.screenshot_saved_title))
+                .setContentText(r.getString(R.string.screenshot_saved_text))
+                .setContentIntent(PendingIntent.getActivity(params.context, 0, mLaunchIntent, 0))
+                .setWhen(System.currentTimeMillis())
+                .setAutoCancel(true);
+
+            Notification n = mNotificationBuilder.getNotification();
+            n.flags &= ~Notification.FLAG_NO_CLEAR;
+            mNotificationManager.notify(mNotificationId, n);
         }
         params.finisher.run();
     };
@@ -154,22 +191,21 @@
  */
 class GlobalScreenshot {
     private static final String TAG = "GlobalScreenshot";
-    private static final int SCREENSHOT_FADE_IN_DURATION = 900;
+    private static final int SCREENSHOT_NOTIFICATION_ID = 789;
+    private static final int SCREENSHOT_FADE_IN_DURATION = 500;
     private static final int SCREENSHOT_FADE_OUT_DELAY = 1000;
-    private static final int SCREENSHOT_FADE_OUT_DURATION = 450;
-    private static final int TOAST_FADE_IN_DURATION = 500;
-    private static final int TOAST_FADE_OUT_DELAY = 1000;
-    private static final int TOAST_FADE_OUT_DURATION = 500;
+    private static final int SCREENSHOT_FADE_OUT_DURATION = 300;
     private static final float BACKGROUND_ALPHA = 0.65f;
-    private static final float SCREENSHOT_SCALE = 0.85f;
-    private static final float SCREENSHOT_MIN_SCALE = 0.7f;
-    private static final float SCREENSHOT_ROTATION = -6.75f; // -12.5f;
+    private static final float SCREENSHOT_SCALE_FUDGE = 0.075f; // To account for the border padding
+    private static final float SCREENSHOT_SCALE = 0.8f;
+    private static final float SCREENSHOT_MIN_SCALE = 0.775f;
 
     private Context mContext;
     private LayoutInflater mLayoutInflater;
     private IWindowManager mIWindowManager;
     private WindowManager mWindowManager;
     private WindowManager.LayoutParams mWindowLayoutParams;
+    private NotificationManager mNotificationManager;
     private Display mDisplay;
     private DisplayMetrics mDisplayMetrics;
     private Matrix mDisplayMatrix;
@@ -182,10 +218,15 @@
 
     private AnimatorSet mScreenshotAnimation;
 
-    // General use cubic interpolator
-    final TimeInterpolator mCubicInterpolator = new TimeInterpolator() {
+    // Fade interpolators
+    final TimeInterpolator mFadeInInterpolator = new TimeInterpolator() {
         public float getInterpolation(float t) {
-            return t*t*t;
+            return (float) Math.pow(t, 1.5f);
+        }
+    };
+    final TimeInterpolator mFadeOutInterpolator = new TimeInterpolator() {
+        public float getInterpolation(float t) {
+            return (float) t;
         }
     };
     // The interpolator used to control the background alpha at the start of the animation
@@ -237,6 +278,8 @@
                 PixelFormat.TRANSLUCENT);
         mWindowLayoutParams.setTitle("ScreenshotAnimation");
         mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
+        mNotificationManager =
+            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
         mDisplay = mWindowManager.getDefaultDisplay();
     }
 
@@ -248,7 +291,8 @@
         data.context = mContext;
         data.image = mScreenBitmap;
         data.finisher = finisher;
-        new SaveImageInBackgroundTask().execute(data);
+        new SaveImageInBackgroundTask(mContext, mNotificationManager, SCREENSHOT_NOTIFICATION_ID)
+                .execute(data);
     }
 
     /**
@@ -300,8 +344,7 @@
 
         // If we couldn't take the screenshot, notify the user
         if (mScreenBitmap == null) {
-            Toast.makeText(mContext, R.string.screenshot_failed_toast,
-                    Toast.LENGTH_SHORT).show();
+            notifyScreenshotError(mContext, mNotificationManager);
             finisher.run();
             return;
         }
@@ -341,12 +384,13 @@
     }
     private ValueAnimator createScreenshotFadeInAnimation() {
         ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
-        anim.setInterpolator(mCubicInterpolator);
+        anim.setInterpolator(mFadeInInterpolator);
         anim.setDuration(SCREENSHOT_FADE_IN_DURATION);
         anim.addListener(new AnimatorListenerAdapter() {
             @Override
             public void onAnimationStart(Animator animation) {
                 mBackgroundView.setVisibility(View.VISIBLE);
+                mScreenshotContainerView.setTranslationY(0f);
                 mScreenshotContainerView.setVisibility(View.VISIBLE);
             }
         });
@@ -356,18 +400,19 @@
                 float t = ((Float) animation.getAnimatedValue()).floatValue();
                 mBackgroundView.setAlpha(mBackgroundViewAlphaInterpolator.getInterpolation(t) *
                         BACKGROUND_ALPHA);
-                float scaleT = SCREENSHOT_SCALE + (1f - t) * SCREENSHOT_SCALE;
+                float scaleT = SCREENSHOT_SCALE
+                        + (1f - t) * (1f - SCREENSHOT_SCALE)
+                        + SCREENSHOT_SCALE_FUDGE;
                 mScreenshotContainerView.setAlpha(t*t*t*t);
                 mScreenshotContainerView.setScaleX(scaleT);
                 mScreenshotContainerView.setScaleY(scaleT);
-                mScreenshotContainerView.setRotation(t * SCREENSHOT_ROTATION);
             }
         });
         return anim;
     }
     private ValueAnimator createScreenshotFadeOutAnimation() {
         ValueAnimator anim = ValueAnimator.ofFloat(1f, 0f);
-        anim.setInterpolator(mCubicInterpolator);
+        anim.setInterpolator(mFadeOutInterpolator);
         anim.setStartDelay(SCREENSHOT_FADE_OUT_DELAY);
         anim.setDuration(SCREENSHOT_FADE_OUT_DURATION);
         anim.addListener(new AnimatorListenerAdapter() {
@@ -381,8 +426,9 @@
             @Override
             public void onAnimationUpdate(ValueAnimator animation) {
                 float t = ((Float) animation.getAnimatedValue()).floatValue();
-                float scaleT = SCREENSHOT_MIN_SCALE +
-                        t*(SCREENSHOT_SCALE - SCREENSHOT_MIN_SCALE);
+                float scaleT = SCREENSHOT_MIN_SCALE
+                        + t * (SCREENSHOT_SCALE - SCREENSHOT_MIN_SCALE)
+                        + SCREENSHOT_SCALE_FUDGE;
                 mScreenshotContainerView.setAlpha(t);
                 mScreenshotContainerView.setScaleX(scaleT);
                 mScreenshotContainerView.setScaleY(scaleT);
@@ -391,4 +437,19 @@
         });
         return anim;
     }
+
+    static void notifyScreenshotError(Context context, NotificationManager nManager) {
+        Resources r = context.getResources();
+
+        // Clear all existing notification, compose the new notification and show it
+        Notification n = new Notification.Builder(context)
+            .setTicker(r.getString(R.string.screenshot_failed_title))
+            .setContentTitle(r.getString(R.string.screenshot_failed_title))
+            .setContentText(r.getString(R.string.screenshot_failed_text))
+            .setSmallIcon(android.R.drawable.ic_menu_report_image)
+            .setWhen(System.currentTimeMillis())
+            .setAutoCancel(true)
+            .getNotification();
+        nManager.notify(SCREENSHOT_NOTIFICATION_ID, n);
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java b/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
index 05ff8be..d112b5e 100644
--- a/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
+++ b/packages/SystemUI/src/com/android/systemui/screenshot/TakeScreenshotService.java
@@ -17,26 +17,12 @@
 package com.android.systemui.screenshot;
 
 import android.app.Service;
-import android.app.AlertDialog;
-import android.content.ActivityNotFoundException;
-import android.content.Context;
-import android.content.DialogInterface;
 import android.content.Intent;
-import android.net.Uri;
-import android.hardware.usb.UsbAccessory;
-import android.hardware.usb.UsbManager;
-import android.os.Bundle;
 import android.os.Handler;
 import android.os.IBinder;
 import android.os.Message;
 import android.os.Messenger;
 import android.os.RemoteException;
-import android.util.Log;
-
-import com.android.internal.app.AlertActivity;
-import com.android.internal.app.AlertController;
-
-import com.android.systemui.R;
 
 public class TakeScreenshotService extends Service {
     private static final String TAG = "TakeScreenshotService";
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBar.java
index 5959537..2e1803e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBar.java
@@ -146,4 +146,26 @@
 
         mDoNotDisturb = new DoNotDisturb(mContext);
     }
+
+    protected View updateNotificationVetoButton(View row, StatusBarNotification n) {
+        View vetoButton = row.findViewById(R.id.veto);
+        if (n.isClearable()) {
+            final String _pkg = n.pkg;
+            final String _tag = n.tag;
+            final int _id = n.id;
+            vetoButton.setOnClickListener(new View.OnClickListener() {
+                    public void onClick(View v) {
+                        try {
+                            mBarService.onNotificationClear(_pkg, _tag, _id);
+                        } catch (RemoteException ex) {
+                            // system process is dead if we're here.
+                        }
+                    }
+                });
+            vetoButton.setVisibility(View.VISIBLE);
+        } else {
+            vetoButton.setVisibility(View.GONE);
+        }
+        return vetoButton;
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
index e3a64a8..694da20 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
@@ -116,15 +116,13 @@
 
         mDisabledFlags = disabledFlags;
 
-        final boolean disableNavigation = ((disabledFlags & View.STATUS_BAR_DISABLE_NAVIGATION) != 0);
+        final boolean disableHome = ((disabledFlags & View.STATUS_BAR_DISABLE_HOME) != 0);
+        final boolean disableRecent = ((disabledFlags & View.STATUS_BAR_DISABLE_RECENT) != 0);
         final boolean disableBack = ((disabledFlags & View.STATUS_BAR_DISABLE_BACK) != 0);
 
         getBackButton()   .setVisibility(disableBack       ? View.INVISIBLE : View.VISIBLE);
-        getHomeButton()   .setVisibility(disableNavigation ? View.INVISIBLE : View.VISIBLE);
-        getRecentsButton().setVisibility(disableNavigation ? View.INVISIBLE : View.VISIBLE);
- 
-        getMenuButton()   .setVisibility((disableNavigation || !mShowMenu)
-                                                           ? View.INVISIBLE : View.VISIBLE);
+        getHomeButton()   .setVisibility(disableHome       ? View.INVISIBLE : View.VISIBLE);
+        getRecentsButton().setVisibility(disableRecent     ? View.INVISIBLE : View.VISIBLE);
     }
 
     public void setMenuVisibility(final boolean show) {
@@ -136,9 +134,7 @@
 
         mShowMenu = show;
 
-        getMenuButton().setVisibility(
-            (0 != (mDisabledFlags & View.STATUS_BAR_DISABLE_NAVIGATION) || !mShowMenu)
-                ? View.INVISIBLE : View.VISIBLE);
+        getMenuButton().setVisibility(mShowMenu ? View.VISIBLE : View.INVISIBLE);
     }
 
     public void setLowProfile(final boolean lightsOut) {
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 e54de59..4e9b411 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -94,7 +94,7 @@
     public static final boolean DUMPTRUCK = true; // extra dumpsys info
 
     // additional instrumentation for testing purposes; intended to be left on during development
-    public static final boolean CHATTY = DEBUG || true;
+    public static final boolean CHATTY = DEBUG;
 
     public static final String ACTION_STATUSBAR_START
             = "com.android.internal.policy.statusbar.START";
@@ -300,18 +300,6 @@
                     (NavigationBarView) View.inflate(context, R.layout.navigation_bar, null);
 
                 mNavigationBarView.setDisabledFlags(mDisabled);
-
-                sb.setOnSystemUiVisibilityChangeListener(
-                    new View.OnSystemUiVisibilityChangeListener() {
-                        @Override
-                        public void onSystemUiVisibilityChange(int visibility) {
-                            if (DEBUG) {
-                                Slog.d(TAG, "systemUi: " + visibility);
-                            }
-                            boolean hide = (0 != (visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION));
-                            mNavigationBarView.setHidden(hide);
-                        }
-                    });
             }
         } catch (Resources.NotFoundException ex) {
             // no nav bar for you
@@ -630,6 +618,10 @@
         boolean orderUnchanged = notification.notification.when==oldNotification.notification.when
                 && notification.priority == oldNotification.priority;
                 // priority now encompasses isOngoing()
+
+        boolean updateTicker = notification.notification.tickerText != null
+                && !TextUtils.equals(notification.notification.tickerText,
+                        oldEntry.notification.notification.tickerText);
         boolean isFirstAnyway = rowParent.indexOfChild(oldEntry.row) == 0;
         if (contentsUnchanged && (orderUnchanged || isFirstAnyway)) {
             if (DEBUG) Slog.d(TAG, "reusing notification for key: " + key);
@@ -677,10 +669,13 @@
             addNotificationViews(key, notification);
         }
 
+        // Update the veto button accordingly (and as a result, whether this row is
+        // swipe-dismissable)
+        updateNotificationVetoButton(oldEntry.row, notification);
+
         // Restart the ticker if it's still running
-        if (notification.notification.tickerText != null
-                && !TextUtils.equals(notification.notification.tickerText,
-                    oldEntry.notification.notification.tickerText)) {
+        if (updateTicker) {
+            mTicker.halt();
             tick(notification);
         }
 
@@ -723,23 +718,7 @@
         View row = inflater.inflate(R.layout.status_bar_notification_row, parent, false);
 
         // wire up the veto button
-        View vetoButton = row.findViewById(R.id.veto);
-        if (notification.isClearable()) {
-            final String _pkg = notification.pkg;
-            final String _tag = notification.tag;
-            final int _id = notification.id;
-            vetoButton.setOnClickListener(new View.OnClickListener() {
-                    public void onClick(View v) {
-                        try {
-                            mBarService.onNotificationClear(_pkg, _tag, _id);
-                        } catch (RemoteException ex) {
-                            // system process is dead if we're here.
-                        }
-                    }
-                });
-        } else {
-            vetoButton.setVisibility(View.GONE);
-        }
+        View vetoButton = updateNotificationVetoButton(row, notification);
         vetoButton.setContentDescription(mContext.getString(
                 R.string.accessibility_remove_notification));
 
@@ -909,23 +888,7 @@
         LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(
                 Context.LAYOUT_INFLATER_SERVICE);
         View row = inflater.inflate(R.layout.status_bar_notification_row, parent, false);
-        View vetoButton = row.findViewById(R.id.veto);
-        if (entry.notification.isClearable()) {
-            final String _pkg = sbn.pkg;
-            final String _tag = sbn.tag;
-            final int _id = sbn.id;
-            vetoButton.setOnClickListener(new View.OnClickListener() {
-                    public void onClick(View v) {
-                        try {
-                            mBarService.onNotificationClear(_pkg, _tag, _id);
-                        } catch (RemoteException ex) {
-                            // system process is dead if we're here.
-                        }
-                    }
-                });
-        } else {
-            vetoButton.setVisibility(View.GONE);
-        }
+        View vetoButton = updateNotificationVetoButton(row, sbn);
         vetoButton.setContentDescription(mContext.getString(
                 R.string.accessibility_remove_notification));
 
@@ -1064,10 +1027,12 @@
         flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) ? "* " : " ");
         flagdbg.append(((state & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "SYSTEM_INFO" : "system_info");
         flagdbg.append(((diff  & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "* " : " ");
-        flagdbg.append(((state & StatusBarManager.DISABLE_NAVIGATION) != 0) ? "NAVIGATION" : "navigation");
-        flagdbg.append(((diff  & StatusBarManager.DISABLE_NAVIGATION) != 0) ? "* " : " ");
         flagdbg.append(((state & StatusBarManager.DISABLE_BACK) != 0) ? "BACK" : "back");
         flagdbg.append(((diff  & StatusBarManager.DISABLE_BACK) != 0) ? "* " : " ");
+        flagdbg.append(((state & StatusBarManager.DISABLE_HOME) != 0) ? "HOME" : "home");
+        flagdbg.append(((diff  & StatusBarManager.DISABLE_HOME) != 0) ? "* " : " ");
+        flagdbg.append(((state & StatusBarManager.DISABLE_RECENT) != 0) ? "RECENT" : "recent");
+        flagdbg.append(((diff  & StatusBarManager.DISABLE_RECENT) != 0) ? "* " : " ");
         flagdbg.append(((state & StatusBarManager.DISABLE_CLOCK) != 0) ? "CLOCK" : "clock");
         flagdbg.append(((diff  & StatusBarManager.DISABLE_CLOCK) != 0) ? "* " : " ");
         flagdbg.append(">");
@@ -1083,11 +1048,13 @@
             }
         }
 
-        if ((diff & (StatusBarManager.DISABLE_NAVIGATION | StatusBarManager.DISABLE_BACK)) != 0) {
-            // the nav bar will take care of DISABLE_NAVIGATION and DISABLE_BACK
+        if ((diff & (StatusBarManager.DISABLE_HOME 
+                        | StatusBarManager.DISABLE_RECENT 
+                        | StatusBarManager.DISABLE_BACK)) != 0) {
+            // the nav bar will take care of these
             if (mNavigationBarView != null) mNavigationBarView.setDisabledFlags(state);
 
-            if ((state & StatusBarManager.DISABLE_NAVIGATION) != 0) {
+            if ((state & StatusBarManager.DISABLE_RECENT) != 0) {
                 // close recents if it's visible
                 mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
                 mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/Ticker.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/Ticker.java
index e76fe51..f5ceed0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/Ticker.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/Ticker.java
@@ -17,6 +17,7 @@
 package com.android.systemui.statusbar.phone;
 
 import android.content.Context;
+import android.content.res.Resources;
 import android.graphics.drawable.Drawable;
 import android.os.Handler;
 import android.text.StaticLayout;
@@ -50,6 +51,7 @@
     private View mTickerView;
     private ImageSwitcher mIconSwitcher;
     private TextSwitcher mTextSwitcher;
+    private float mIconScale;
 
     private final class Segment {
         StatusBarNotification notification;
@@ -145,6 +147,11 @@
 
     public Ticker(Context context, View sb) {
         mContext = context;
+        final Resources res = context.getResources();
+        final int outerBounds = res.getDimensionPixelSize(R.dimen.status_bar_icon_size);
+        final int imageBounds = res.getDimensionPixelSize(R.dimen.status_bar_icon_drawing_size);
+        mIconScale = (float)imageBounds / (float)outerBounds;
+
         mTickerView = sb.findViewById(R.id.ticker);
 
         mIconSwitcher = (ImageSwitcher)sb.findViewById(R.id.tickerIcon);
@@ -152,6 +159,8 @@
                     AnimationUtils.loadAnimation(context, com.android.internal.R.anim.push_up_in));
         mIconSwitcher.setOutAnimation(
                     AnimationUtils.loadAnimation(context, com.android.internal.R.anim.push_up_out));
+        mIconSwitcher.setScaleX(mIconScale);
+        mIconSwitcher.setScaleY(mIconScale);
 
         mTextSwitcher = (TextSwitcher)sb.findViewById(R.id.tickerText);
         mTextSwitcher.setInAnimation(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
index 8d964e3..4f9eb38 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
@@ -61,7 +61,7 @@
     // debug
     static final String TAG = "StatusBar.NetworkController";
     static final boolean DEBUG = false;
-    static final boolean CHATTY = true; // additional diagnostics, but not logspew
+    static final boolean CHATTY = false; // additional diagnostics, but not logspew
 
     // telephony
     boolean mHspaDataDistinguishable;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
index 271e508..f0a10f3 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
@@ -840,6 +840,9 @@
         boolean orderUnchanged = notification.notification.when==oldNotification.notification.when
                 && notification.priority == oldNotification.priority;
                 // priority now encompasses isOngoing()
+        boolean updateTicker = notification.notification.tickerText != null
+                && !TextUtils.equals(notification.notification.tickerText,
+                        oldEntry.notification.notification.tickerText);
         boolean isLastAnyway = rowParent.indexOfChild(oldEntry.row) == rowParent.getChildCount()-1;
         if (contentsUnchanged && (orderUnchanged || isLastAnyway)) {
             if (DEBUG) Slog.d(TAG, "reusing notification for key: " + key);
@@ -896,9 +899,8 @@
         }
 
         // Restart the ticker if it's still running
-        if (notification.notification.tickerText != null
-                && !TextUtils.equals(notification.notification.tickerText,
-                    oldEntry.notification.notification.tickerText)) {
+        if (updateTicker) {
+            mTicker.halt();
             tick(key, notification, false);
         }
 
@@ -964,34 +966,24 @@
                 mTicker.halt();
             }
         }
-        if ((diff & (StatusBarManager.DISABLE_NAVIGATION | StatusBarManager.DISABLE_BACK)) != 0) {
-            setNavigationVisibility(state &
-                    (StatusBarManager.DISABLE_NAVIGATION | StatusBarManager.DISABLE_BACK));
+        if ((diff & (StatusBarManager.DISABLE_RECENT 
+                        | StatusBarManager.DISABLE_BACK 
+                        | StatusBarManager.DISABLE_HOME)) != 0) {
+            setNavigationVisibility(state);
         }
     }
 
     private void setNavigationVisibility(int visibility) {
-        boolean disableNavigation = ((visibility & StatusBarManager.DISABLE_NAVIGATION) != 0);
+        boolean disableHome = ((visibility & StatusBarManager.DISABLE_HOME) != 0);
+        boolean disableRecent = ((visibility & StatusBarManager.DISABLE_RECENT) != 0);
         boolean disableBack = ((visibility & StatusBarManager.DISABLE_BACK) != 0);
 
-        Slog.i(TAG, "DISABLE_BACK: " + (disableBack ? "yes" : "no"));
-        Slog.i(TAG, "DISABLE_NAVIGATION: " + (disableNavigation ? "yes" : "no"));
+        mBackButton.setVisibility(disableBack ? View.INVISIBLE : View.VISIBLE);
+        mHomeButton.setVisibility(disableHome ? View.INVISIBLE : View.VISIBLE);
+        mRecentButton.setVisibility(disableRecent ? View.INVISIBLE : View.VISIBLE);
 
-        if (disableNavigation && disableBack) {
-            mNavigationArea.setVisibility(View.INVISIBLE);
-        } else {
-            int backVisiblity = (disableBack ? View.INVISIBLE : View.VISIBLE);
-            int navVisibility = (disableNavigation ? View.INVISIBLE : View.VISIBLE);
-
-            mBackButton.setVisibility(backVisiblity);
-            mHomeButton.setVisibility(navVisibility);
-            mRecentButton.setVisibility(navVisibility);
-            // don't change menu button visibility here
-
-            mNavigationArea.setVisibility(View.VISIBLE);
-        }
-
-        mInputMethodSwitchButton.setScreenLocked(disableNavigation);
+        mInputMethodSwitchButton.setScreenLocked(
+                (visibility & StatusBarManager.DISABLE_SYSTEM_INFO) != 0);
     }
 
     private boolean hasTicker(Notification n) {
@@ -1746,23 +1738,7 @@
                 Context.LAYOUT_INFLATER_SERVICE);
         View row = inflater.inflate(R.layout.status_bar_notification_row, parent, false);
         workAroundBadLayerDrawableOpacity(row);
-        View vetoButton = row.findViewById(R.id.veto);
-        if (entry.notification.isClearable()) {
-            final String _pkg = sbn.pkg;
-            final String _tag = sbn.tag;
-            final int _id = sbn.id;
-            vetoButton.setOnClickListener(new View.OnClickListener() {
-                    public void onClick(View v) {
-                        try {
-                            mBarService.onNotificationClear(_pkg, _tag, _id);
-                        } catch (RemoteException ex) {
-                            // system process is dead if we're here.
-                        }
-                    }
-                });
-        } else {
-            vetoButton.setVisibility(View.GONE);
-        }
+        View vetoButton = updateNotificationVetoButton(row, entry.notification);
         vetoButton.setContentDescription(mContext.getString(
                 R.string.accessibility_remove_notification));
 
diff --git a/policy/src/com/android/internal/policy/impl/KeyguardStatusViewManager.java b/policy/src/com/android/internal/policy/impl/KeyguardStatusViewManager.java
index 8343bbd..6614d79 100644
--- a/policy/src/com/android/internal/policy/impl/KeyguardStatusViewManager.java
+++ b/policy/src/com/android/internal/policy/impl/KeyguardStatusViewManager.java
@@ -609,6 +609,10 @@
         public void onClockVisibilityChanged() {
             // ignored
         }
+
+        public void onDeviceProvisioned() {
+            // ignored
+        }
     };
 
     private SimStateCallback mSimStateCallback = new SimStateCallback() {
diff --git a/policy/src/com/android/internal/policy/impl/KeyguardUpdateMonitor.java b/policy/src/com/android/internal/policy/impl/KeyguardUpdateMonitor.java
index f67f0e0..2d8185b 100644
--- a/policy/src/com/android/internal/policy/impl/KeyguardUpdateMonitor.java
+++ b/policy/src/com/android/internal/policy/impl/KeyguardUpdateMonitor.java
@@ -99,6 +99,7 @@
     private static final int MSG_RINGER_MODE_CHANGED = 305;
     private static final int MSG_PHONE_STATE_CHANGED = 306;
     private static final int MSG_CLOCK_VISIBILITY_CHANGED = 307;
+    private static final int MSG_DEVICE_PROVISIONED = 308;
 
     /**
      * When we receive a
@@ -178,6 +179,9 @@
                     case MSG_CLOCK_VISIBILITY_CHANGED:
                         handleClockVisibilityChanged();
                         break;
+                    case MSG_DEVICE_PROVISIONED:
+                        handleDeviceProvisioned();
+                        break;
                 }
             }
         };
@@ -197,10 +201,8 @@
                     super.onChange(selfChange);
                     mDeviceProvisioned = Settings.Secure.getInt(mContext.getContentResolver(),
                         Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
-                    if (mDeviceProvisioned && mContentObserver != null) {
-                        // We don't need the observer anymore...
-                        mContext.getContentResolver().unregisterContentObserver(mContentObserver);
-                        mContentObserver = null;
+                    if (mDeviceProvisioned) {
+                        mHandler.sendMessage(mHandler.obtainMessage(MSG_DEVICE_PROVISIONED));
                     }
                     if (DEBUG) Log.d(TAG, "DEVICE_PROVISIONED state = " + mDeviceProvisioned);
                 }
@@ -212,8 +214,14 @@
 
             // prevent a race condition between where we check the flag and where we register the
             // observer by grabbing the value once again...
-            mDeviceProvisioned = Settings.Secure.getInt(mContext.getContentResolver(),
+            boolean provisioned = Settings.Secure.getInt(mContext.getContentResolver(),
                 Settings.Secure.DEVICE_PROVISIONED, 0) != 0;
+            if (provisioned != mDeviceProvisioned) {
+                mDeviceProvisioned = provisioned;
+                if (mDeviceProvisioned) {
+                    mHandler.sendMessage(mHandler.obtainMessage(MSG_DEVICE_PROVISIONED));
+                }
+            }
         }
 
         // take a guess to start
@@ -271,6 +279,17 @@
         }, filter);
     }
 
+    protected void handleDeviceProvisioned() {
+        for (int i = 0; i < mInfoCallbacks.size(); i++) {
+            mInfoCallbacks.get(i).onDeviceProvisioned();
+        }
+        if (mContentObserver != null) {
+            // We don't need the observer anymore...
+            mContext.getContentResolver().unregisterContentObserver(mContentObserver);
+            mContentObserver = null;
+        }
+    }
+
     protected void handlePhoneStateChanged(String newState) {
         if (DEBUG) Log.d(TAG, "handlePhoneStateChanged(" + newState + ")");
         if (TelephonyManager.EXTRA_STATE_IDLE.equals(newState)) {
@@ -477,6 +496,10 @@
          */
         void onClockVisibilityChanged();
 
+        /**
+         * Called when the device becomes provisioned
+         */
+        void onDeviceProvisioned();
     }
 
     /**
diff --git a/policy/src/com/android/internal/policy/impl/KeyguardViewBase.java b/policy/src/com/android/internal/policy/impl/KeyguardViewBase.java
index 59b546d..de156c9 100644
--- a/policy/src/com/android/internal/policy/impl/KeyguardViewBase.java
+++ b/policy/src/com/android/internal/policy/impl/KeyguardViewBase.java
@@ -50,8 +50,6 @@
     public KeyguardViewBase(Context context) {
         super(context);
 
-        setSystemUiVisibility(STATUS_BAR_DISABLE_BACK);
-
         // This is a faster way to draw the background on devices without hardware acceleration
         setBackgroundDrawable(new Drawable() {
             @Override
diff --git a/policy/src/com/android/internal/policy/impl/KeyguardViewManager.java b/policy/src/com/android/internal/policy/impl/KeyguardViewManager.java
index 90972da..2fd165a 100644
--- a/policy/src/com/android/internal/policy/impl/KeyguardViewManager.java
+++ b/policy/src/com/android/internal/policy/impl/KeyguardViewManager.java
@@ -171,6 +171,17 @@
             }
         }
 
+        // Disable aspects of the system/status/navigation bars that are not appropriate or
+        // useful for the lockscreen but can be re-shown by dialogs or SHOW_WHEN_LOCKED activities.
+        // Other disabled bits are handled by the KeyguardViewMediator talking directly to the
+        // status bar service.
+        int visFlags =
+                ( View.STATUS_BAR_DISABLE_BACK
+                | View.STATUS_BAR_DISABLE_HOME
+                | View.STATUS_BAR_DISABLE_CLOCK
+                );
+        mKeyguardHost.setSystemUiVisibility(visFlags);
+
         mViewManager.updateViewLayout(mKeyguardHost, mWindowLayoutParams);
         mKeyguardHost.setVisibility(View.VISIBLE);
         mKeyguardView.requestFocus();
diff --git a/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java b/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java
index c25e3ca..0471dfe 100644
--- a/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java
+++ b/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java
@@ -1188,19 +1188,12 @@
                 }
             }
 
+            // Disable aspects of the system/status/navigation bars that must not be re-enabled by
+            // windows that appear on top, ever
             int flags = StatusBarManager.DISABLE_NONE;
             if (mShowing) {
-                // disable navigation status bar components if lock screen is up
-                flags |= StatusBarManager.DISABLE_NAVIGATION;
-                if (!mHidden) {
-                    // showing lockscreen exclusively (no activities in front of it)
-                    // disable back button too
-                    flags |= StatusBarManager.DISABLE_BACK;
-                    if (mUpdateMonitor.isClockVisible()) {
-                        // lockscreen showing a clock, so hide statusbar clock
-                        flags |= StatusBarManager.DISABLE_CLOCK;
-                    }
-                }
+                // disable navigation status bar components (home, recents) if lock screen is up
+                flags |= StatusBarManager.DISABLE_RECENT;
                 if (isSecure() || !ENABLE_INSECURE_STATUS_BAR_EXPAND) {
                     // showing secure lockscreen; disable expanding.
                     flags |= StatusBarManager.DISABLE_EXPAND;
@@ -1323,4 +1316,9 @@
     public void onTimeChanged() {
         // ignored
     }
+
+    /** {@inheritDoc} */
+    public void onDeviceProvisioned() {
+        mContext.sendBroadcast(mUserPresentIntent);
+    }
 }
diff --git a/policy/src/com/android/internal/policy/impl/LockPatternKeyguardView.java b/policy/src/com/android/internal/policy/impl/LockPatternKeyguardView.java
index 265024b..ebf380a 100644
--- a/policy/src/com/android/internal/policy/impl/LockPatternKeyguardView.java
+++ b/policy/src/com/android/internal/policy/impl/LockPatternKeyguardView.java
@@ -49,6 +49,7 @@
 import android.os.Handler;
 import android.os.Message;
 import android.os.IBinder;
+import android.os.Parcelable;
 import android.os.RemoteException;
 import android.os.SystemClock;
 import android.os.SystemProperties;
@@ -117,9 +118,21 @@
     private final int MSG_SHOW_FACELOCK_AREA_VIEW = 0;
     private final int MSG_HIDE_FACELOCK_AREA_VIEW = 1;
 
-    // Long enough to stay black while dialer comes up
-    // Short enough to not be black if the user goes back immediately
-    private final int FACELOCK_VIEW_AREA_EMERGENCY_HIDE_TIMEOUT = 1000;
+    // Long enough to stay visible while dialer comes up
+    // Short enough to not be visible if the user goes back immediately
+    private final int FACELOCK_VIEW_AREA_EMERGENCY_DIALER_TIMEOUT = 1000;
+
+    // Long enough to stay visible while the service starts
+    // Short enough to not have to wait long for backup if service fails to start or crashes
+    // The service can take a couple of seconds to start on the first try after boot
+    private final int FACELOCK_VIEW_AREA_SERVICE_TIMEOUT = 3000;
+
+    // So the user has a consistent amount of time when brought to the backup method from FaceLock
+    private final int BACKUP_LOCK_TIMEOUT = 5000;
+
+    // Needed to keep track of failed FaceUnlock attempts
+    private int mFailedFaceUnlockAttempts = 0;
+    private static final int FAILED_FACE_UNLOCK_ATTEMPTS_BEFORE_BACKUP = 15;
 
     /**
      * The current {@link KeyguardScreen} will use this to communicate back to us.
@@ -128,6 +141,10 @@
 
 
     private boolean mRequiresSim;
+    //True if we have some sort of overlay on top of the Lockscreen
+    //Also true if we've activated a phone call, either emergency dialing or incoming
+    //This resets when the phone is turned off with no current call
+    private boolean mHasOverlay;
 
 
     /**
@@ -209,6 +226,7 @@
     private Runnable mRecreateRunnable = new Runnable() {
         public void run() {
             updateScreen(mMode, true);
+            restoreWidgetState();
         }
     };
 
@@ -232,10 +250,20 @@
             // TODO: examine all widgets to derive clock status
             mUpdateMonitor.reportClockVisible(true);
         }
+
+        public boolean isVisible(View self) {
+            // TODO: this should be up to the lockscreen to determine if the view
+            // is currently showing. The idea is it can be used for the widget to
+            // avoid doing work if it's not visible. For now just returns the view's
+            // actual visibility.
+            return self.getVisibility() == View.VISIBLE;
+        }
     };
 
     private TransportControlView mTransportControlView;
 
+    private Parcelable mSavedState;
+
     /**
      * @return Whether we are stuck on the lock screen because the sim is
      *   missing.
@@ -268,6 +296,7 @@
         mUpdateMonitor = updateMonitor;
         mLockPatternUtils = lockPatternUtils;
         mWindowController = controller;
+        mHasOverlay = false;
 
         mUpdateMonitor.registerInfoCallback(this);
 
@@ -322,12 +351,15 @@
             }
 
             public void takeEmergencyCallAction() {
+                mHasOverlay = true;
                 // FaceLock must be stopped if it is running when emergency call is pressed
                 stopAndUnbindFromFaceLock();
 
-                // Delay hiding FaceLock area so unlock doesn't display while dialer is coming up
-                mHandler.sendEmptyMessageDelayed(MSG_HIDE_FACELOCK_AREA_VIEW,
-                        FACELOCK_VIEW_AREA_EMERGENCY_HIDE_TIMEOUT);
+                // Continue showing FaceLock area until dialer comes up
+                if (mLockPatternUtils.usingBiometricWeak() &&
+                        mLockPatternUtils.isBiometricWeakInstalled()) {
+                    showFaceLockAreaWithTimeout(FACELOCK_VIEW_AREA_EMERGENCY_DIALER_TIMEOUT);
+                }
 
                 pokeWakelock(EMERGENCY_CALL_TIMEOUT);
                 if (TelephonyManager.getDefault().getCallState()
@@ -351,6 +383,7 @@
 
             public void keyguardDone(boolean authenticated) {
                 getCallback().keyguardDone(authenticated);
+                mSavedState = null; // clear state so we re-establish when locked again
             }
 
             public void keyguardDoneDrawing() {
@@ -410,6 +443,7 @@
             }
 
             public void reportSuccessfulUnlockAttempt() {
+                mFailedFaceUnlockAttempts = 0;
                 mLockPatternUtils.reportSuccessfulPasswordAttempt();
             }
         };
@@ -504,14 +538,18 @@
 
     @Override
     public void onScreenTurnedOff() {
+        if (DEBUG) Log.d(TAG, "screen off");
         mScreenOn = false;
         mForgotPattern = false;
+        mHasOverlay = mUpdateMonitor.getPhoneState() != TelephonyManager.CALL_STATE_IDLE;
         if (mMode == Mode.LockScreen) {
             ((KeyguardScreen) mLockScreen).onPause();
         } else {
             ((KeyguardScreen) mUnlockScreen).onPause();
         }
 
+        saveWidgetState();
+
         // When screen is turned off, need to unbind from FaceLock service if using FaceLock
         stopAndUnbindFromFaceLock();
     }
@@ -520,29 +558,59 @@
      *  FaceLock, but only if we're not dealing with a call
     */
     private void activateFaceLockIfAble() {
-        final boolean transportInvisible = mTransportControlView == null ? true :
-                mTransportControlView.getVisibility() != View.VISIBLE;
+        final boolean tooManyFaceUnlockTries =
+                (mFailedFaceUnlockAttempts >= FAILED_FACE_UNLOCK_ATTEMPTS_BEFORE_BACKUP);
+        final int failedBackupAttempts = mUpdateMonitor.getFailedAttempts();
+        final boolean backupIsTimedOut =
+                (failedBackupAttempts >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT);
+        if (tooManyFaceUnlockTries) Log.i(TAG, "tooManyFaceUnlockTries: " + tooManyFaceUnlockTries);
         if (mUpdateMonitor.getPhoneState() == TelephonyManager.CALL_STATE_IDLE
-                && transportInvisible) {
+                && !mHasOverlay
+                && !tooManyFaceUnlockTries
+                && !backupIsTimedOut) {
             bindToFaceLock();
-            //Eliminate the black background so that the lockpattern will be visible
-            //If FaceUnlock is cancelled
-            mHandler.sendEmptyMessageDelayed(MSG_HIDE_FACELOCK_AREA_VIEW, 4000);
+            // Show FaceLock area, but only for a little bit so lockpattern will become visible if
+            // FaceLock fails to start or crashes
+            if (mLockPatternUtils.usingBiometricWeak() &&
+                    mLockPatternUtils.isBiometricWeakInstalled()) {
+                showFaceLockAreaWithTimeout(FACELOCK_VIEW_AREA_SERVICE_TIMEOUT);
+            }
         } else {
-            mHandler.sendEmptyMessage(MSG_HIDE_FACELOCK_AREA_VIEW);
+            hideFaceLockArea();
         }
     }
 
     @Override
     public void onScreenTurnedOn() {
+        if (DEBUG) Log.d(TAG, "screen on");
         boolean runFaceLock = false;
         //Make sure to start facelock iff the screen is both on and focused
         synchronized(mFaceLockStartupLock) {
             mScreenOn = true;
             runFaceLock = mWindowFocused;
         }
+
         show();
-        if(runFaceLock) activateFaceLockIfAble();
+
+        restoreWidgetState();
+
+        if (runFaceLock) activateFaceLockIfAble();
+    }
+
+    private void saveWidgetState() {
+        if (mTransportControlView != null) {
+            if (DEBUG) Log.v(TAG, "Saving widget state");
+            mSavedState = mTransportControlView.onSaveInstanceState();
+        }
+    }
+
+    private void restoreWidgetState() {
+        if (mTransportControlView != null) {
+            if (DEBUG) Log.v(TAG, "Restoring widget state");
+            if (mSavedState != null) {
+                mTransportControlView.onRestoreInstanceState(mSavedState);
+            }
+        }
     }
 
     /** Unbind from facelock if something covers this window (such as an alarm)
@@ -550,6 +618,7 @@
      */
     @Override
     public void onWindowFocusChanged (boolean hasWindowFocus) {
+        if (DEBUG) Log.d(TAG, hasWindowFocus ? "focused" : "unfocused");
         boolean runFaceLock = false;
         //Make sure to start facelock iff the screen is both on and focused
         synchronized(mFaceLockStartupLock) {
@@ -557,8 +626,9 @@
             mWindowFocused = hasWindowFocus;
         }
         if(!hasWindowFocus) {
+            mHasOverlay = true;
             stopAndUnbindFromFaceLock();
-            mHandler.sendEmptyMessage(MSG_HIDE_FACELOCK_AREA_VIEW);
+            hideFaceLockArea();
         } else if (runFaceLock) {
             activateFaceLockIfAble();
         }
@@ -573,10 +643,14 @@
         }
 
         if (mLockPatternUtils.usingBiometricWeak() &&
-                mLockPatternUtils.isBiometricWeakInstalled()) {
-            mHandler.sendEmptyMessage(MSG_SHOW_FACELOCK_AREA_VIEW);
+            mLockPatternUtils.isBiometricWeakInstalled() && !mHasOverlay) {
+            // Note that show() gets called before the screen turns off to set it up for next time
+            // it is turned on.  We don't want to set a timeout on the FaceLock area here because it
+            // may be gone by the time the screen is turned on again.  We set the timout when the
+            // screen turns on instead.
+            showFaceLockArea();
         } else {
-            mHandler.sendEmptyMessage(MSG_HIDE_FACELOCK_AREA_VIEW);
+            hideFaceLockArea();
         }
     }
 
@@ -620,6 +694,7 @@
         mShowLockBeforeUnlock = resources.getBoolean(R.bool.config_enableLockBeforeUnlockScreen);
         mConfiguration = newConfig;
         if (DEBUG_CONFIGURATION) Log.v(TAG, "**** re-creating lock screen since config changed");
+        saveWidgetState();
         removeCallbacks(mRecreateRunnable);
         post(mRecreateRunnable);
     }
@@ -636,13 +711,17 @@
     public void onRingerModeChanged(int state) {}
     @Override
     public void onClockVisibilityChanged() {}
+    @Override
+    public void onDeviceProvisioned() {}
 
     //We need to stop faceunlock when a phonecall comes in
     @Override
     public void onPhoneStateChanged(int phoneState) {
+        if (DEBUG) Log.d(TAG, "phone state: " + phoneState);
         if(phoneState == TelephonyManager.CALL_STATE_RINGING) {
+            mHasOverlay = true;
             stopAndUnbindFromFaceLock();
-            mHandler.sendEmptyMessage(MSG_HIDE_FACELOCK_AREA_VIEW);
+            hideFaceLockArea();
         }
     }
 
@@ -702,6 +781,16 @@
             this.removeView(mUnlockScreen);
             mUnlockScreen = null;
         }
+        mUpdateMonitor.removeCallback(this);
+        if (mFaceLockService != null) {
+            try {
+                mFaceLockService.unregisterCallback(mFaceLockCallback);
+            } catch (RemoteException e) {
+                // Not much we can do
+            }
+            stopFaceLock();
+            mFaceLockService = null;
+        }
     }
 
     private boolean isSecure() {
@@ -1075,6 +1164,32 @@
         return true;
     }
 
+    // Removes show and hide messages from the message queue
+    private void removeFaceLockAreaDisplayMessages() {
+        mHandler.removeMessages(MSG_SHOW_FACELOCK_AREA_VIEW);
+        mHandler.removeMessages(MSG_HIDE_FACELOCK_AREA_VIEW);
+    }
+
+    // Shows the FaceLock area immediately
+    private void showFaceLockArea() {
+        // Remove messages to prevent a delayed hide message from undo-ing the show
+        removeFaceLockAreaDisplayMessages();
+        mHandler.sendEmptyMessage(MSG_SHOW_FACELOCK_AREA_VIEW);
+    }
+
+    // Hides the FaceLock area immediately
+    private void hideFaceLockArea() {
+        // Remove messages to prevent a delayed show message from undo-ing the hide
+        removeFaceLockAreaDisplayMessages();
+        mHandler.sendEmptyMessage(MSG_HIDE_FACELOCK_AREA_VIEW);
+    }
+
+    // Shows the FaceLock area for a period of time
+    private void showFaceLockAreaWithTimeout(long timeoutMillis) {
+        showFaceLockArea();
+        mHandler.sendEmptyMessageDelayed(MSG_HIDE_FACELOCK_AREA_VIEW, timeoutMillis);
+    }
+
     // Binds to FaceLock service, but does not tell it to start
     public void bindToFaceLock() {
         if (mLockPatternUtils.usingBiometricWeak() &&
@@ -1100,6 +1215,13 @@
 
             if (mBoundToFaceLockService) {
                 if (DEBUG) Log.d(TAG, "before unbind from FaceLock service");
+                if (mFaceLockService != null) {
+                    try {
+                        mFaceLockService.unregisterCallback(mFaceLockCallback);
+                    } catch (RemoteException e) {
+                        // Not much we can do
+                    }
+                }
                 mContext.unbindService(mFaceLockConnection);
                 if (DEBUG) Log.d(TAG, "after unbind from FaceLock service");
                 mBoundToFaceLockService = false;
@@ -1120,7 +1242,10 @@
             try {
                 mFaceLockService.registerCallback(mFaceLockCallback);
             } catch (RemoteException e) {
-                throw new RuntimeException("Remote exception");
+                Log.e(TAG, "Caught exception connecting to FaceLock: " + e.toString());
+                mFaceLockService = null;
+                mBoundToFaceLockService = false;
+                return;
             }
 
             if (mFaceLockAreaView != null) {
@@ -1137,6 +1262,7 @@
                 mFaceLockService = null;
                 mFaceLockServiceRunning = false;
             }
+            mBoundToFaceLockService = false;
             Log.w(TAG, "Unexpected disconnect from FaceLock service");
         }
     };
@@ -1152,7 +1278,8 @@
                     try {
                         mFaceLockService.startUi(windowToken, x, y, h, w);
                     } catch (RemoteException e) {
-                        throw new RuntimeException("Remote exception");
+                        Log.e(TAG, "Caught exception starting FaceLock: " + e.toString());
+                        return;
                     }
                     mFaceLockServiceRunning = true;
                 } else {
@@ -1176,7 +1303,7 @@
                         if (DEBUG) Log.d(TAG, "Stopping FaceLock");
                         mFaceLockService.stopUi();
                     } catch (RemoteException e) {
-                        throw new RuntimeException("Remote exception");
+                        Log.e(TAG, "Caught exception stopping FaceLock: " + e.toString());
                     }
                     mFaceLockServiceRunning = false;
                 }
@@ -1191,7 +1318,7 @@
         @Override
         public void unlock() {
             if (DEBUG) Log.d(TAG, "FaceLock unlock()");
-            mHandler.sendEmptyMessage(MSG_SHOW_FACELOCK_AREA_VIEW); // Keep fallback covered
+            showFaceLockArea(); // Keep fallback covered
             stopFaceLock();
 
             mKeyguardScreenCallback.keyguardDone(true);
@@ -1199,12 +1326,24 @@
         }
 
         // Stops the FaceLock UI and exposes the backup method without unlocking
-        // This means either the user has cancelled out or FaceLock failed to recognize them
+        // This means the user has cancelled out
         @Override
         public void cancel() {
             if (DEBUG) Log.d(TAG, "FaceLock cancel()");
-            mHandler.sendEmptyMessage(MSG_HIDE_FACELOCK_AREA_VIEW); // Expose fallback
+            hideFaceLockArea(); // Expose fallback
             stopFaceLock();
+            mKeyguardScreenCallback.pokeWakelock(BACKUP_LOCK_TIMEOUT);
+        }
+
+        // Stops the FaceLock UI and exposes the backup method without unlocking
+        // This means FaceLock failed to recognize them
+        @Override
+        public void reportFailedAttempt() {
+            if (DEBUG) Log.d(TAG, "FaceLock reportFailedAttempt()");
+            mFailedFaceUnlockAttempts++;
+            hideFaceLockArea(); // Expose fallback
+            stopFaceLock();
+            mKeyguardScreenCallback.pokeWakelock(BACKUP_LOCK_TIMEOUT);
         }
 
         // Allows the Face Unlock service to poke the wake lock to keep the lockscreen alive
diff --git a/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java b/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
index ec0072c..3ad716b 100644
--- a/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
+++ b/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
@@ -28,6 +28,7 @@
 
 import android.os.CountDownTimer;
 import android.os.SystemClock;
+import android.provider.Settings;
 import android.security.KeyStore;
 import android.text.Editable;
 import android.text.InputType;
@@ -109,6 +110,10 @@
         mPasswordEntry.setOnEditorActionListener(this);
 
         mKeyboardHelper = new PasswordEntryKeyboardHelper(context, mKeyboardView, this, false);
+        mKeyboardHelper.setEnableHaptics(
+                Settings.Secure.getInt(mContext.getContentResolver(),
+                        Settings.Secure.LOCK_PATTERN_TACTILE_FEEDBACK_ENABLED, 0)
+                        != 0);
         if (mIsAlpha) {
             // We always use the system IME for alpha keyboard, so hide lockscreen's soft keyboard
             mKeyboardHelper.setKeyboardMode(PasswordEntryKeyboardHelper.KEYBOARD_MODE_ALPHA);
@@ -150,9 +155,6 @@
                     //KeyguardStatusViewManager.LOCK_ICON);
         }
 
-        mKeyboardHelper.setVibratePattern(mLockPatternUtils.isTactileFeedbackEnabled() ?
-                com.android.internal.R.array.config_virtualKeyVibePattern : 0);
-
         // Poke the wakelock any time the text is selected or modified
         mPasswordEntry.setOnClickListener(new OnClickListener() {
             public void onClick(View v) {
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindow.java b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
index de8d41a2..af86ae9 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindow.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
@@ -349,8 +349,9 @@
         }
 
         // Already prepared (isPrepared will be reset to false later)
-        if (st.isPrepared)
+        if (st.isPrepared) {
             return true;
+        }
         
         if ((mPreparedPanel != null) && (mPreparedPanel != st)) {
             // Another Panel is prepared and possibly open, so close it
@@ -800,14 +801,23 @@
                     closePanel(st, true);
 
                 } else if (st.isPrepared) {
+                    boolean show = true;
+                    if (st.refreshMenuContent) {
+                        // Something may have invalidated the menu since we prepared it.
+                        // Re-prepare it to refresh.
+                        st.isPrepared = false;
+                        show = preparePanel(st, event);
+                    }
 
-                    // Write 'menu opened' to event log
-                    EventLog.writeEvent(50001, 0);
+                    if (show) {
+                        // Write 'menu opened' to event log
+                        EventLog.writeEvent(50001, 0);
 
-                    // Show menu
-                    openPanel(st, event);
+                        // Show menu
+                        openPanel(st, event);
 
-                    playSoundEffect = true;
+                        playSoundEffect = true;
+                    }
                 }
             }
 
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
index 3eb04cb..8b09e00 100755
--- a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -128,7 +128,6 @@
 import android.view.WindowManagerImpl;
 import android.view.WindowManagerPolicy;
 import android.view.KeyCharacterMap.FallbackAction;
-import android.view.WindowManagerPolicy.WindowManagerFuncs;
 import android.view.accessibility.AccessibilityEvent;
 import android.view.animation.Animation;
 import android.view.animation.AnimationUtils;
@@ -180,26 +179,26 @@
     static final int PRIORITY_PHONE_LAYER = 7;
     // like the ANR / app crashed dialogs
     static final int SYSTEM_ALERT_LAYER = 8;
-    // system-level error dialogs
-    static final int SYSTEM_ERROR_LAYER = 9;
     // on-screen keyboards and other such input method user interfaces go here.
-    static final int INPUT_METHOD_LAYER = 10;
+    static final int INPUT_METHOD_LAYER = 9;
     // on-screen keyboards and other such input method user interfaces go here.
-    static final int INPUT_METHOD_DIALOG_LAYER = 11;
+    static final int INPUT_METHOD_DIALOG_LAYER = 10;
     // the keyguard; nothing on top of these can take focus, since they are
     // responsible for power management when displayed.
-    static final int KEYGUARD_LAYER = 12;
-    static final int KEYGUARD_DIALOG_LAYER = 13;
-    static final int STATUS_BAR_SUB_PANEL_LAYER = 14;
-    static final int STATUS_BAR_LAYER = 15;
-    static final int STATUS_BAR_PANEL_LAYER = 16;
+    static final int KEYGUARD_LAYER = 11;
+    static final int KEYGUARD_DIALOG_LAYER = 12;
+    static final int STATUS_BAR_SUB_PANEL_LAYER = 13;
+    static final int STATUS_BAR_LAYER = 14;
+    static final int STATUS_BAR_PANEL_LAYER = 15;
     // the on-screen volume indicator and controller shown when the user
     // changes the device volume
-    static final int VOLUME_OVERLAY_LAYER = 17;
+    static final int VOLUME_OVERLAY_LAYER = 16;
     // things in here CAN NOT take focus, but are shown on top of everything else.
-    static final int SYSTEM_OVERLAY_LAYER = 18;
+    static final int SYSTEM_OVERLAY_LAYER = 17;
     // the navigation bar, if available, shows atop most things
-    static final int NAVIGATION_BAR_LAYER = 19;
+    static final int NAVIGATION_BAR_LAYER = 18;
+    // system-level error dialogs
+    static final int SYSTEM_ERROR_LAYER = 19;
     // the drag layer: input for drag-and-drop is associated with this window,
     // which sits above all other focusable windows
     static final int DRAG_LAYER = 20;
@@ -354,8 +353,13 @@
     int mDockLeft, mDockTop, mDockRight, mDockBottom;
     // During layout, the layer at which the doc window is placed.
     int mDockLayer;
-    int mLastSystemUiVisibility;
-    int mForceClearingStatusBarVisibility = 0;
+    int mLastSystemUiFlags;
+    // Bits that we are in the process of clearing, so we want to prevent
+    // them from being set by applications until everything has been updated
+    // to have them clear.
+    int mResettingSystemUiFlags = 0;
+    // Bits that we are currently always keeping cleared.
+    int mForceClearedSystemUiFlags = 0;
 
     FakeWindow mHideNavFakeWindow = null;
 
@@ -1720,6 +1724,21 @@
         }
     }
 
+    /**
+     * A delayed callback use to determine when it is okay to re-allow applications
+     * to use certain system UI flags.  This is used to prevent applications from
+     * spamming system UI changes that prevent the navigation bar from being shown.
+     */
+    final Runnable mAllowSystemUiDelay = new Runnable() {
+        @Override public void run() {
+        }
+    };
+
+    /**
+     * Input handler used while nav bar is hidden.  Captures any touch on the screen,
+     * to determine when the nav bar should be shown and prevent applications from
+     * receiving those touches.
+     */
     final InputHandler mHideNavInputHandler = new BaseInputHandler() {
         @Override
         public void handleMotion(MotionEvent event, InputQueue.FinishedCallback finishedCallback) {
@@ -1732,12 +1751,30 @@
                         synchronized (mLock) {
                             // Any user activity always causes us to show the navigation controls,
                             // if they had been hidden.
-                            int newVal = mForceClearingStatusBarVisibility
+                            int newVal = mResettingSystemUiFlags
                                     | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
-                            if (mForceClearingStatusBarVisibility != newVal) {
-                                mForceClearingStatusBarVisibility = newVal;
+                            if (mResettingSystemUiFlags != newVal) {
+                                mResettingSystemUiFlags = newVal;
                                 changed = true;
                             }
+                            // We don't allow the system's nav bar to be hidden
+                            // again for 1 second, to prevent applications from
+                            // spamming us and keeping it from being shown.
+                            newVal = mForceClearedSystemUiFlags
+                                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
+                            if (mForceClearedSystemUiFlags != newVal) {
+                                mForceClearedSystemUiFlags = newVal;
+                                changed = true;
+                                mHandler.postDelayed(new Runnable() {
+                                    @Override public void run() {
+                                        synchronized (mLock) {
+                                            mForceClearedSystemUiFlags &=
+                                                    ~View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
+                                        }
+                                        mWindowManagerFuncs.reevaluateStatusBarVisibility();
+                                    }
+                                }, 1000);
+                            }
                         }
                         if (changed) {
                             mWindowManagerFuncs.reevaluateStatusBarVisibility();
@@ -1754,10 +1791,11 @@
     public int adjustSystemUiVisibilityLw(int visibility) {
         // Reset any bits in mForceClearingStatusBarVisibility that
         // are now clear.
-        mForceClearingStatusBarVisibility &= visibility;
+        mResettingSystemUiFlags &= visibility;
         // Clear any bits in the new visibility that are currently being
         // force cleared, before reporting it.
-        return visibility & ~mForceClearingStatusBarVisibility;
+        return visibility & ~mResettingSystemUiFlags
+                & ~mForceClearedSystemUiFlags;
     }
 
     public void getContentInsetHintLw(WindowManager.LayoutParams attrs, Rect contentInset) {
@@ -1796,11 +1834,28 @@
         pf.right = df.right = vf.right = mDockRight;
         pf.bottom = df.bottom = vf.bottom = mDockBottom;
 
+        final boolean navVisible = (mNavigationBar == null || mNavigationBar.isVisibleLw()) &&
+                (mLastSystemUiFlags&View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
+
+        // When the navigation bar isn't visible, we put up a fake
+        // input window to catch all touch events.  This way we can
+        // detect when the user presses anywhere to bring back the nav
+        // bar and ensure the application doesn't see the event.
+        if (navVisible) {
+            if (mHideNavFakeWindow != null) {
+                mHideNavFakeWindow.dismiss();
+                mHideNavFakeWindow = null;
+            }
+        } else if (mHideNavFakeWindow == null) {
+            mHideNavFakeWindow = mWindowManagerFuncs.addFakeWindow(
+                    mHandler.getLooper(), mHideNavInputHandler,
+                    "hidden nav", WindowManager.LayoutParams.TYPE_HIDDEN_NAV_CONSUMER,
+                    0, false, false, true);
+        }
+
         // decide where the status bar goes ahead of time
         if (mStatusBar != null) {
             if (mNavigationBar != null) {
-                final boolean navVisible = mNavigationBar.isVisibleLw() &&
-                        (mLastSystemUiVisibility&View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
                 // Force the navigation bar to its appropriate place and
                 // size.  We need to do this directly, instead of relying on
                 // it to bubble up from the nav bar, because this needs to
@@ -1832,21 +1887,6 @@
                         mTmpNavigationFrame.offset(mNavigationBarWidth, 0);
                     }
                 }
-                // When the navigation bar isn't visible, we put up a fake
-                // input window to catch all touch events.  This way we can
-                // detect when the user presses anywhere to bring back the nav
-                // bar and ensure the application doesn't see the event.
-                if (navVisible) {
-                    if (mHideNavFakeWindow != null) {
-                        mHideNavFakeWindow.dismiss();
-                        mHideNavFakeWindow = null;
-                    }
-                } else if (mHideNavFakeWindow == null) {
-                    mHideNavFakeWindow = mWindowManagerFuncs.addFakeWindow(
-                            mHandler.getLooper(), mHideNavInputHandler,
-                            "hidden nav", WindowManager.LayoutParams.TYPE_HIDDEN_NAV_CONSUMER,
-                            0, false, false, true);
-                }
                 // And compute the final frame.
                 mNavigationBar.computeFrameLw(mTmpNavigationFrame, mTmpNavigationFrame,
                         mTmpNavigationFrame, mTmpNavigationFrame);
@@ -3654,12 +3694,13 @@
             return 0;
         }
         final int visibility = mFocusedWindow.getSystemUiVisibility()
-                & ~mForceClearingStatusBarVisibility;
-        int diff = visibility ^ mLastSystemUiVisibility;
+                & ~mResettingSystemUiFlags
+                & ~mForceClearedSystemUiFlags;
+        int diff = visibility ^ mLastSystemUiFlags;
         if (diff == 0) {
             return 0;
         }
-        mLastSystemUiVisibility = visibility;
+        mLastSystemUiFlags = visibility;
         mHandler.post(new Runnable() {
                 public void run() {
                     if (mStatusBarService == null) {
@@ -3686,11 +3727,14 @@
         pw.print(prefix); pw.print("mLidOpen="); pw.print(mLidOpen);
                 pw.print(" mLidOpenRotation="); pw.print(mLidOpenRotation);
                 pw.print(" mHdmiPlugged="); pw.println(mHdmiPlugged);
-        if (mLastSystemUiVisibility != 0 || mForceClearingStatusBarVisibility != 0) {
-            pw.print(prefix); pw.print("mLastSystemUiVisibility=0x");
-                    pw.println(Integer.toHexString(mLastSystemUiVisibility));
-                    pw.print("  mForceClearingStatusBarVisibility=0x");
-                    pw.println(Integer.toHexString(mForceClearingStatusBarVisibility));
+        if (mLastSystemUiFlags != 0 || mResettingSystemUiFlags != 0
+                || mForceClearedSystemUiFlags != 0) {
+            pw.print(prefix); pw.print("mLastSystemUiFlags=0x");
+                    pw.print(Integer.toHexString(mLastSystemUiFlags));
+                    pw.print(" mResettingSystemUiFlags=0x");
+                    pw.print(Integer.toHexString(mResettingSystemUiFlags));
+                    pw.print(" mForceClearedSystemUiFlags=0x");
+                    pw.println(Integer.toHexString(mForceClearedSystemUiFlags));
         }
         pw.print(prefix); pw.print("mUiMode="); pw.print(mUiMode);
                 pw.print(" mDockMode="); pw.print(mDockMode);
diff --git a/services/java/com/android/server/AppWidgetService.java b/services/java/com/android/server/AppWidgetService.java
index dd649e7..eb75ebc 100644
--- a/services/java/com/android/server/AppWidgetService.java
+++ b/services/java/com/android/server/AppWidgetService.java
@@ -16,24 +16,6 @@
 
 package com.android.server;
 
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-
-import org.apache.commons.logging.impl.SimpleLog;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-import org.xmlpull.v1.XmlSerializer;
-
 import android.app.AlarmManager;
 import android.app.PendingIntent;
 import android.appwidget.AppWidgetManager;
@@ -42,9 +24,9 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
-import android.content.Intent.FilterComparison;
 import android.content.IntentFilter;
 import android.content.ServiceConnection;
+import android.content.Intent.FilterComparison;
 import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageInfo;
@@ -58,7 +40,6 @@
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.IBinder;
-import android.os.Process;
 import android.os.RemoteException;
 import android.os.SystemClock;
 import android.util.AttributeSet;
@@ -68,20 +49,37 @@
 import android.util.TypedValue;
 import android.util.Xml;
 import android.widget.RemoteViews;
-import android.widget.RemoteViewsService;
 
 import com.android.internal.appwidget.IAppWidgetHost;
 import com.android.internal.appwidget.IAppWidgetService;
+import com.android.internal.os.AtomicFile;
 import com.android.internal.util.FastXmlSerializer;
 import com.android.internal.widget.IRemoteViewsAdapterConnection;
 import com.android.internal.widget.IRemoteViewsFactory;
 
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlSerializer;
+
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+
 class AppWidgetService extends IAppWidgetService.Stub
 {
     private static final String TAG = "AppWidgetService";
 
     private static final String SETTINGS_FILENAME = "appwidgets.xml";
-    private static final String SETTINGS_TMP_FILENAME = SETTINGS_FILENAME + ".tmp";
     private static final int MIN_UPDATE_PERIOD = 30 * 60 * 1000; // 30 minutes
 
     /*
@@ -1159,70 +1157,46 @@
 
     // only call from initialization -- it assumes that the data structures are all empty
     void loadStateLocked() {
-        File temp = savedStateTempFile();
-        File real = savedStateRealFile();
+        AtomicFile file = savedStateFile();
+        try {
+            FileInputStream stream = file.openRead();
+            readStateFromFileLocked(stream);
 
-        // prefer the real file.  If it doesn't exist, use the temp one, and then copy it to the
-        // real one.  if there is both a real file and a temp one, assume that the temp one isn't
-        // fully written and delete it.
-        if (real.exists()) {
-            readStateFromFileLocked(real);
-            if (temp.exists()) {
-                //noinspection ResultOfMethodCallIgnored
-                temp.delete();
+            if (stream != null) {
+                try {
+                    stream.close();
+                } catch (IOException e) {
+                    Slog.w(TAG, "Failed to close state FileInputStream " + e);
+                }
             }
-        } else if (temp.exists()) {
-            readStateFromFileLocked(temp);
-            //noinspection ResultOfMethodCallIgnored
-            temp.renameTo(real);
+        } catch (FileNotFoundException e) {
+            Slog.w(TAG, "Failed to read state: " + e);
         }
     }
-    
+
     void saveStateLocked() {
-        File temp = savedStateTempFile();
-        File real = savedStateRealFile();
-
-        if (!real.exists()) {
-            // If the real one doesn't exist, it's either because this is the first time
-            // or because something went wrong while copying them.  In this case, we can't
-            // trust anything that's in temp.  In order to have the loadState code not
-            // use the temporary one until it's fully written, create an empty file
-            // for real, which will we'll shortly delete.
-            try {
-                //noinspection ResultOfMethodCallIgnored
-                real.createNewFile();
-            } catch (IOException e) {
-                // Ignore
+        AtomicFile file = savedStateFile();
+        FileOutputStream stream;
+        try {
+            stream = file.startWrite();
+            if (writeStateToFileLocked(stream)) {
+                file.finishWrite(stream);
+            } else {
+                file.failWrite(stream);
+                Slog.w(TAG, "Failed to save state, restoring backup.");
             }
+        } catch (IOException e) {
+            Slog.w(TAG, "Failed open state file for write: " + e);
         }
-
-        if (temp.exists()) {
-            //noinspection ResultOfMethodCallIgnored
-            temp.delete();
-        }
-
-        if (!writeStateToFileLocked(temp)) {
-            Slog.w(TAG, "Failed to persist new settings");
-            return;
-        }
-
-        //noinspection ResultOfMethodCallIgnored
-        real.delete();
-        //noinspection ResultOfMethodCallIgnored
-        temp.renameTo(real);
     }
 
-    boolean writeStateToFileLocked(File file) {
-        FileOutputStream stream = null;
+    boolean writeStateToFileLocked(FileOutputStream stream) {
         int N;
 
         try {
-            stream = new FileOutputStream(file, false);
             XmlSerializer out = new FastXmlSerializer();
             out.setOutput(stream, "utf-8");
             out.startDocument(null, true);
-
-            
             out.startTag(null, "gs");
 
             int providerIndex = 0;
@@ -1264,31 +1238,17 @@
             out.endTag(null, "gs");
 
             out.endDocument();
-            stream.close();
             return true;
         } catch (IOException e) {
-            try {
-                if (stream != null) {
-                    stream.close();
-                }
-            } catch (IOException ex) {
-                // Ignore
-            }
-            if (file.exists()) {
-                //noinspection ResultOfMethodCallIgnored
-                file.delete();
-            }
+            Slog.w(TAG, "Failed to write state: " + e);
             return false;
         }
     }
 
-    void readStateFromFileLocked(File file) {
-        FileInputStream stream = null;
-
+    void readStateFromFileLocked(FileInputStream stream) {
         boolean success = false;
 
         try {
-            stream = new FileInputStream(file);
             XmlPullParser parser = Xml.newPullParser();
             parser.setInput(stream, null);
 
@@ -1390,22 +1350,15 @@
             } while (type != XmlPullParser.END_DOCUMENT);
             success = true;
         } catch (NullPointerException e) {
-            Slog.w(TAG, "failed parsing " + file, e);
+            Slog.w(TAG, "failed parsing " + e);
         } catch (NumberFormatException e) {
-            Slog.w(TAG, "failed parsing " + file, e);
+            Slog.w(TAG, "failed parsing " + e);
         } catch (XmlPullParserException e) {
-            Slog.w(TAG, "failed parsing " + file, e);
+            Slog.w(TAG, "failed parsing " + e);
         } catch (IOException e) {
-            Slog.w(TAG, "failed parsing " + file, e);
+            Slog.w(TAG, "failed parsing " + e);
         } catch (IndexOutOfBoundsException e) {
-            Slog.w(TAG, "failed parsing " + file, e);
-        }
-        try {
-            if (stream != null) {
-                stream.close();
-            }
-        } catch (IOException e) {
-            // Ignore
+            Slog.w(TAG, "failed parsing " + e);
         }
 
         if (success) {
@@ -1416,6 +1369,8 @@
             }
         } else {
             // failed reading, clean up
+            Slog.w(TAG, "Failed to read state, clearing widgets and hosts.");
+
             mAppWidgetIds.clear();
             mHosts.clear();
             final int N = mInstalledProviders.size();
@@ -1425,14 +1380,8 @@
         }
     }
 
-    File savedStateTempFile() {
-        return new File("/data/system/" + SETTINGS_TMP_FILENAME);
-        //return new File(mContext.getFilesDir(), SETTINGS_FILENAME);
-    }
-
-    File savedStateRealFile() {
-        return new File("/data/system/" + SETTINGS_FILENAME);
-        //return new File(mContext.getFilesDir(), SETTINGS_TMP_FILENAME);
+    AtomicFile savedStateFile() {
+        return new AtomicFile(new File("/data/system/" + SETTINGS_FILENAME));
     }
 
     BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
diff --git a/services/java/com/android/server/BackupManagerService.java b/services/java/com/android/server/BackupManagerService.java
index f9f5458..4ef8837 100644
--- a/services/java/com/android/server/BackupManagerService.java
+++ b/services/java/com/android/server/BackupManagerService.java
@@ -62,14 +62,15 @@
 import android.os.PowerManager;
 import android.os.Process;
 import android.os.RemoteException;
+import android.os.ServiceManager;
 import android.os.SystemClock;
 import android.os.WorkSource;
+import android.os.storage.IMountService;
 import android.provider.Settings;
 import android.util.EventLog;
 import android.util.Log;
 import android.util.Slog;
 import android.util.SparseArray;
-import android.util.SparseIntArray;
 import android.util.StringBuilderPrinter;
 
 import com.android.internal.backup.BackupConstants;
@@ -187,6 +188,7 @@
     private IActivityManager mActivityManager;
     private PowerManager mPowerManager;
     private AlarmManager mAlarmManager;
+    private IMountService mMountService;
     IBackupManager mBackupManagerBinder;
 
     boolean mEnabled;   // access to this is synchronized on 'this'
@@ -660,6 +662,7 @@
 
         mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
         mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
+        mMountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));
 
         mBackupManagerBinder = asInterface(asBinder());
 
@@ -1037,6 +1040,40 @@
 
     // Backup password management
     boolean passwordMatchesSaved(String candidatePw, int rounds) {
+        // First, on an encrypted device we require matching the device pw
+        final boolean isEncrypted;
+        try {
+            isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
+            if (isEncrypted) {
+                if (DEBUG) {
+                    Slog.i(TAG, "Device encrypted; verifying against device data pw");
+                }
+                // 0 means the password validated
+                // -2 means device not encrypted
+                // Any other result is either password failure or an error condition,
+                // so we refuse the match
+                final int result = mMountService.verifyEncryptionPassword(candidatePw);
+                if (result == 0) {
+                    if (MORE_DEBUG) Slog.d(TAG, "Pw verifies");
+                    return true;
+                } else if (result != -2) {
+                    if (MORE_DEBUG) Slog.d(TAG, "Pw mismatch");
+                    return false;
+                } else {
+                    // ...else the device is supposedly not encrypted.  HOWEVER, the
+                    // query about the encryption state said that the device *is*
+                    // encrypted, so ... we may have a problem.  Log it and refuse
+                    // the backup.
+                    Slog.e(TAG, "verified encryption state mismatch against query; no match allowed");
+                    return false;
+                }
+            }
+        } catch (Exception e) {
+            // Something went wrong talking to the mount service.  This is very bad;
+            // assume that we fail password validation.
+            return false;
+        }
+
         if (mPasswordHash == null) {
             // no current password case -- require that 'currentPw' be null or empty
             if (candidatePw == null || "".equals(candidatePw)) {
@@ -1114,7 +1151,15 @@
     public boolean hasBackupPassword() {
         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
                 "hasBackupPassword");
-        return (mPasswordHash != null && mPasswordHash.length() > 0);
+
+        try {
+            return (mMountService.getEncryptionState() != IMountService.ENCRYPTION_STATE_NONE)
+                || (mPasswordHash != null && mPasswordHash.length() > 0);
+        } catch (Exception e) {
+            // If we can't talk to the mount service we have a serious problem; fail
+            // "secure" i.e. assuming that we require a password
+            return true;
+        }
     }
 
     // Maintain persistent state around whether need to do an initialize operation.
@@ -5007,7 +5052,17 @@
 
                         params.observer = observer;
                         params.curPassword = curPassword;
-                        params.encryptPassword = encPpassword;
+
+                        boolean isEncrypted;
+                        try {
+                            isEncrypted = (mMountService.getEncryptionState() != MountService.ENCRYPTION_STATE_NONE);
+                            if (isEncrypted) Slog.w(TAG, "Device is encrypted; forcing enc password");
+                        } catch (RemoteException e) {
+                            // couldn't contact the mount service; fail "safe" and assume encryption
+                            Slog.e(TAG, "Unable to contact mount service!");
+                            isEncrypted = true;
+                        }
+                        params.encryptPassword = (isEncrypted) ? curPassword : encPpassword;
 
                         if (DEBUG) Slog.d(TAG, "Sending conf message with verb " + verb);
                         mWakelock.acquire();
diff --git a/services/java/com/android/server/MountService.java b/services/java/com/android/server/MountService.java
index 582f0ed..5425813 100644
--- a/services/java/com/android/server/MountService.java
+++ b/services/java/com/android/server/MountService.java
@@ -1897,6 +1897,53 @@
         }
     }
 
+    /**
+     * Validate a user-supplied password string with cryptfs
+     */
+    @Override
+    public int verifyEncryptionPassword(String password) throws RemoteException {
+        // Only the system process is permitted to validate passwords
+        if (Binder.getCallingUid() != android.os.Process.SYSTEM_UID) {
+            throw new SecurityException("no permission to access the crypt keeper");
+        }
+
+        mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER,
+            "no permission to access the crypt keeper");
+
+        if (TextUtils.isEmpty(password)) {
+            throw new IllegalArgumentException("password cannot be empty");
+        }
+
+        waitForReady();
+
+        if (DEBUG_EVENTS) {
+            Slog.i(TAG, "validating encryption password...");
+        }
+
+        try {
+            ArrayList<String> response = mConnector.doCommand("cryptfs verifypw " + password);
+            String[] tokens = response.get(0).split(" ");
+
+            if (tokens == null || tokens.length != 2) {
+                String msg = "Unexpected result from cryptfs verifypw: {";
+                if (tokens == null) msg += "null";
+                else for (int i = 0; i < tokens.length; i++) {
+                    if (i != 0) msg += ',';
+                    msg += tokens[i];
+                }
+                msg += '}';
+                Slog.e(TAG, msg);
+                return -1;
+            }
+
+            Slog.i(TAG, "cryptfs verifypw => " + tokens[1]);
+            return Integer.parseInt(tokens[1]);
+        } catch (NativeDaemonConnectorException e) {
+            // Encryption failed
+            return e.getCode();
+        }
+    }
+
     public Parcelable[] getVolumeList() {
         synchronized(mVolumes) {
             int size = mVolumes.size();
diff --git a/services/java/com/android/server/NativeDaemonConnector.java b/services/java/com/android/server/NativeDaemonConnector.java
index 43d938c..28013bd 100644
--- a/services/java/com/android/server/NativeDaemonConnector.java
+++ b/services/java/com/android/server/NativeDaemonConnector.java
@@ -207,6 +207,13 @@
      */
     private void sendCommandLocked(String command, String argument)
             throws NativeDaemonConnectorException {
+        if (command != null && command.indexOf('\0') >= 0) {
+            throw new IllegalArgumentException("unexpected command: " + command);
+        }
+        if (argument != null && argument.indexOf('\0') >= 0) {
+            throw new IllegalArgumentException("unexpected argument: " + argument);
+        }
+
         if (LOCAL_LOGD) Slog.d(TAG, String.format("SND -> {%s} {%s}", command, argument));
         if (mOutputStream == null) {
             Slog.e(TAG, "No connection to daemon", new IllegalStateException());
diff --git a/services/java/com/android/server/NetworkManagementService.java b/services/java/com/android/server/NetworkManagementService.java
index bcb1aa2..4e4fe4a 100644
--- a/services/java/com/android/server/NetworkManagementService.java
+++ b/services/java/com/android/server/NetworkManagementService.java
@@ -16,6 +16,8 @@
 
 package com.android.server;
 
+import static android.Manifest.permission.ACCESS_NETWORK_STATE;
+import static android.Manifest.permission.CHANGE_NETWORK_STATE;
 import static android.Manifest.permission.DUMP;
 import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
 import static android.net.NetworkStats.SET_DEFAULT;
@@ -355,6 +357,7 @@
     }
 
     public InterfaceConfiguration getInterfaceConfig(String iface) throws IllegalStateException {
+        mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
         String rsp;
         try {
             rsp = mConnector.doCommand("interface getcfg " + iface).get(0);
@@ -409,6 +412,7 @@
 
     public void setInterfaceConfig(
             String iface, InterfaceConfiguration cfg) throws IllegalStateException {
+        mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
         LinkAddress linkAddr = cfg.addr;
         if (linkAddr == null || linkAddr.getAddress() == null) {
             throw new IllegalStateException("Null LinkAddress given");
@@ -426,6 +430,7 @@
     }
 
     public void setInterfaceDown(String iface) throws IllegalStateException {
+        mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
         try {
             InterfaceConfiguration ifcg = getInterfaceConfig(iface);
             ifcg.interfaceFlags = ifcg.interfaceFlags.replace("up", "down");
@@ -437,6 +442,7 @@
     }
 
     public void setInterfaceUp(String iface) throws IllegalStateException {
+        mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
         try {
             InterfaceConfiguration ifcg = getInterfaceConfig(iface);
             ifcg.interfaceFlags = ifcg.interfaceFlags.replace("down", "up");
@@ -449,6 +455,7 @@
 
     public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable)
             throws IllegalStateException {
+        mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
         String cmd = String.format("interface ipv6privacyextensions %s %s", iface,
                 enable ? "enable" : "disable");
         try {
@@ -464,7 +471,8 @@
     /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
        IPv6 addresses on interface down, but we need to do full clean up here */
     public void clearInterfaceAddresses(String iface) throws IllegalStateException {
-         String cmd = String.format("interface clearaddrs %s", iface);
+        mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
+        String cmd = String.format("interface clearaddrs %s", iface);
         try {
             mConnector.doCommand(cmd);
         } catch (NativeDaemonConnectorException e) {
@@ -496,10 +504,12 @@
     }
 
     public void addRoute(String interfaceName, RouteInfo route) {
+        mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
         modifyRoute(interfaceName, ADD, route);
     }
 
     public void removeRoute(String interfaceName, RouteInfo route) {
+        mContext.enforceCallingOrSelfPermission(CHANGE_NETWORK_STATE, TAG);
         modifyRoute(interfaceName, REMOVE, route);
     }
 
@@ -583,6 +593,7 @@
     }
 
     public RouteInfo[] getRoutes(String interfaceName) {
+        mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
         ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();
 
         // v4 routes listed as:
diff --git a/services/java/com/android/server/PowerManagerService.java b/services/java/com/android/server/PowerManagerService.java
index 1941c6a..994201b 100644
--- a/services/java/com/android/server/PowerManagerService.java
+++ b/services/java/com/android/server/PowerManagerService.java
@@ -1698,11 +1698,6 @@
                     // make sure button and key backlights are off too
                     mButtonLight.turnOff();
                     mKeyboardLight.turnOff();
-                    // clear current value so we will update based on the new conditions
-                    // when the sensor is reenabled.
-                    mLightSensorValue = -1;
-                    // reset our highest light sensor value when the screen turns off
-                    mHighestLightSensorValue = -1;
                 }
             }
         }
@@ -2472,6 +2467,7 @@
         synchronized (mLocks) {
             mIsDocked = (state != Intent.EXTRA_DOCK_STATE_UNDOCKED);
             if (mIsDocked) {
+                // allow brightness to decrease when docked
                 mHighestLightSensorValue = -1;
             }
             if ((mPowerState & SCREEN_ON_BIT) != 0) {
@@ -3047,11 +3043,21 @@
             long identity = Binder.clearCallingIdentity();
             try {
                 if (enable) {
+                    // reset our highest value when reenabling
+                    mHighestLightSensorValue = -1;
+                    // force recompute of backlight values
+                    if (mLightSensorValue >= 0) {
+                        int value = (int)mLightSensorValue;
+                        mLightSensorValue = -1;
+                        handleLightSensorValue(value);
+                    }
                     mSensorManager.registerListener(mLightListener, mLightSensor,
                             SensorManager.SENSOR_DELAY_NORMAL);
                 } else {
                     mSensorManager.unregisterListener(mLightListener);
                     mHandler.removeCallbacks(mAutoBrightnessTask);
+                    mLightSensorPendingDecrease = false;
+                    mLightSensorPendingIncrease = false;
                 }
             } finally {
                 Binder.restoreCallingIdentity(identity);
@@ -3103,43 +3109,45 @@
         }
     };
 
+    private void handleLightSensorValue(int value) {
+        long milliseconds = SystemClock.elapsedRealtime();
+        if (mLightSensorValue == -1 ||
+                milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
+            // process the value immediately if screen has just turned on
+            mHandler.removeCallbacks(mAutoBrightnessTask);
+            mLightSensorPendingDecrease = false;
+            mLightSensorPendingIncrease = false;
+            lightSensorChangedLocked(value);
+        } else {
+            if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
+                    (value < mLightSensorValue && mLightSensorPendingIncrease) ||
+                    (value == mLightSensorValue) ||
+                    (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
+                // delay processing to debounce the sensor
+                mHandler.removeCallbacks(mAutoBrightnessTask);
+                mLightSensorPendingDecrease = (value < mLightSensorValue);
+                mLightSensorPendingIncrease = (value > mLightSensorValue);
+                if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
+                    mLightSensorPendingValue = value;
+                    mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
+                }
+            } else {
+                mLightSensorPendingValue = value;
+            }
+        }
+    }
+
     SensorEventListener mLightListener = new SensorEventListener() {
         public void onSensorChanged(SensorEvent event) {
+            if (mDebugLightSensor) {
+                Slog.d(TAG, "onSensorChanged: light value: " + event.values[0]);
+            }
             synchronized (mLocks) {
                 // ignore light sensor while screen is turning off
                 if (isScreenTurningOffLocked()) {
                     return;
                 }
-
-                int value = (int)event.values[0];
-                long milliseconds = SystemClock.elapsedRealtime();
-                if (mDebugLightSensor) {
-                    Slog.d(TAG, "onSensorChanged: light value: " + value);
-                }
-                if (mLightSensorValue == -1 ||
-                        milliseconds < mLastScreenOnTime + mLightSensorWarmupTime) {
-                    // process the value immediately if screen has just turned on
-                    mHandler.removeCallbacks(mAutoBrightnessTask);
-                    mLightSensorPendingDecrease = false;
-                    mLightSensorPendingIncrease = false;
-                    lightSensorChangedLocked(value);
-                } else {
-                    if ((value > mLightSensorValue && mLightSensorPendingDecrease) ||
-                            (value < mLightSensorValue && mLightSensorPendingIncrease) ||
-                            (value == mLightSensorValue) ||
-                            (!mLightSensorPendingDecrease && !mLightSensorPendingIncrease)) {
-                        // delay processing to debounce the sensor
-                        mHandler.removeCallbacks(mAutoBrightnessTask);
-                        mLightSensorPendingDecrease = (value < mLightSensorValue);
-                        mLightSensorPendingIncrease = (value > mLightSensorValue);
-                        if (mLightSensorPendingDecrease || mLightSensorPendingIncrease) {
-                            mLightSensorPendingValue = value;
-                            mHandler.postDelayed(mAutoBrightnessTask, LIGHT_SENSOR_DELAY);
-                        }
-                    } else {
-                        mLightSensorPendingValue = value;
-                    }
-                }
+                handleLightSensorValue((int)event.values[0]);
             }
         }
 
diff --git a/services/java/com/android/server/TextServicesManagerService.java b/services/java/com/android/server/TextServicesManagerService.java
index ef48b9e..788ecda 100644
--- a/services/java/com/android/server/TextServicesManagerService.java
+++ b/services/java/com/android/server/TextServicesManagerService.java
@@ -43,10 +43,13 @@
 import android.view.textservice.SpellCheckerInfo;
 import android.view.textservice.SpellCheckerSubtype;
 
+import java.io.FileDescriptor;
 import java.io.IOException;
+import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
 public class TextServicesManagerService extends ITextServicesManager.Stub {
     private static final String TAG = TextServicesManagerService.class.getSimpleName();
@@ -480,6 +483,66 @@
         }
     }
 
+    @Override
+    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
+                != PackageManager.PERMISSION_GRANTED) {
+
+            pw.println("Permission Denial: can't dump TextServicesManagerService from from pid="
+                    + Binder.getCallingPid()
+                    + ", uid=" + Binder.getCallingUid());
+            return;
+        }
+
+        synchronized(mSpellCheckerMap) {
+            pw.println("Current Text Services Manager state:");
+            pw.println("  Spell Checker Map:");
+            for (Map.Entry<String, SpellCheckerInfo> ent : mSpellCheckerMap.entrySet()) {
+                pw.print("    "); pw.print(ent.getKey()); pw.println(":");
+                SpellCheckerInfo info = ent.getValue();
+                pw.print("      "); pw.print("id="); pw.println(info.getId());
+                pw.print("      "); pw.print("comp=");
+                        pw.println(info.getComponent().toShortString());
+                int NS = info.getSubtypeCount();
+                for (int i=0; i<NS; i++) {
+                    SpellCheckerSubtype st = info.getSubtypeAt(i);
+                    pw.print("      "); pw.print("Subtype #"); pw.print(i); pw.println(":");
+                    pw.print("        "); pw.print("locale="); pw.println(st.getLocale());
+                    pw.print("        "); pw.print("extraValue=");
+                            pw.println(st.getExtraValue());
+                }
+            }
+            pw.println("");
+            pw.println("  Spell Checker Bind Groups:");
+            for (Map.Entry<String, SpellCheckerBindGroup> ent
+                    : mSpellCheckerBindGroups.entrySet()) {
+                SpellCheckerBindGroup grp = ent.getValue();
+                pw.print("    "); pw.print(ent.getKey()); pw.print(" ");
+                        pw.print(grp); pw.println(":");
+                pw.print("      "); pw.print("mInternalConnection=");
+                        pw.println(grp.mInternalConnection);
+                pw.print("      "); pw.print("mSpellChecker=");
+                        pw.println(grp.mSpellChecker);
+                pw.print("      "); pw.print("mBound="); pw.print(grp.mBound);
+                        pw.print(" mConnected="); pw.println(grp.mConnected);
+                int NL = grp.mListeners.size();
+                for (int i=0; i<NL; i++) {
+                    InternalDeathRecipient listener = grp.mListeners.get(i);
+                    pw.print("      "); pw.print("Listener #"); pw.print(i); pw.println(":");
+                    pw.print("        "); pw.print("mTsListener=");
+                            pw.println(listener.mTsListener);
+                    pw.print("        "); pw.print("mScListener=");
+                            pw.println(listener.mScListener);
+                    pw.print("        "); pw.print("mGroup=");
+                            pw.println(listener.mGroup);
+                    pw.print("        "); pw.print("mScLocale=");
+                            pw.print(listener.mScLocale);
+                            pw.print(" mUid="); pw.println(listener.mUid);
+                }
+            }
+        }
+    }
+
     // SpellCheckerBindGroup contains active text service session listeners.
     // If there are no listeners anymore, the SpellCheckerBindGroup instance will be removed from
     // mSpellCheckerBindGroups
@@ -488,6 +551,7 @@
         private final InternalServiceConnection mInternalConnection;
         private final ArrayList<InternalDeathRecipient> mListeners =
                 new ArrayList<InternalDeathRecipient>();
+        public boolean mBound;
         public ISpellCheckerService mSpellChecker;
         public boolean mConnected;
 
@@ -495,6 +559,7 @@
                 ITextServicesSessionListener listener, String locale,
                 ISpellCheckerSessionListener scListener, int uid, Bundle bundle) {
             mInternalConnection = connection;
+            mBound = true;
             mConnected = false;
             addListener(listener, locale, scListener, uid, bundle);
         }
@@ -580,15 +645,18 @@
             if (DBG) {
                 Slog.d(TAG, "cleanLocked");
             }
-            if (mListeners.isEmpty()) {
+            // If there are no more active listeners, clean up.  Only do this
+            // once.
+            if (mBound && mListeners.isEmpty()) {
+                mBound = false;
                 final String sciId = mInternalConnection.mSciId;
-                if (mSpellCheckerBindGroups.containsKey(sciId)) {
+                SpellCheckerBindGroup cur = mSpellCheckerBindGroups.get(sciId);
+                if (cur == this) {
                     if (DBG) {
                         Slog.d(TAG, "Remove bind group.");
                     }
                     mSpellCheckerBindGroups.remove(sciId);
                 }
-                // Unbind service when there is no active clients.
                 mContext.unbindService(mInternalConnection);
             }
         }
@@ -623,7 +691,7 @@
                 }
                 ISpellCheckerService spellChecker = ISpellCheckerService.Stub.asInterface(service);
                 final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
-                if (group != null) {
+                if (this == group.mInternalConnection) {
                     group.onServiceConnected(spellChecker);
                 }
             }
@@ -631,7 +699,12 @@
 
         @Override
         public void onServiceDisconnected(ComponentName name) {
-            mSpellCheckerBindGroups.remove(mSciId);
+            synchronized(mSpellCheckerMap) {
+                final SpellCheckerBindGroup group = mSpellCheckerBindGroups.get(mSciId);
+                if (this == group.mInternalConnection) {
+                    mSpellCheckerBindGroups.remove(mSciId);
+                }
+            }
         }
     }
 
diff --git a/services/java/com/android/server/WifiService.java b/services/java/com/android/server/WifiService.java
index 660681b..5bfe6f8 100644
--- a/services/java/com/android/server/WifiService.java
+++ b/services/java/com/android/server/WifiService.java
@@ -1402,7 +1402,7 @@
         long ident = Binder.clearCallingIdentity();
         try {
             if (hadLock) {
-                noteAcquireWifiLock(wifiLock);
+                noteReleaseWifiLock(wifiLock);
                 switch(wifiLock.mMode) {
                     case WifiManager.WIFI_MODE_FULL:
                         ++mFullLocksReleased;
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index d038d76..55fb371 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -3427,8 +3427,10 @@
                     ac.removePackage(name);
                 }
             }
-            mMainStack.resumeTopActivityLocked(null);
-            mMainStack.scheduleIdleLocked();
+            if (mBooted) {
+                mMainStack.resumeTopActivityLocked(null);
+                mMainStack.scheduleIdleLocked();
+            }
         }
         
         return didSomething;
diff --git a/services/java/com/android/server/am/ActivityStack.java b/services/java/com/android/server/am/ActivityStack.java
index b9d3d76..1aed7fe0 100644
--- a/services/java/com/android/server/am/ActivityStack.java
+++ b/services/java/com/android/server/am/ActivityStack.java
@@ -2067,7 +2067,7 @@
      * task starting at a specified index.
      */
     private final void performClearTaskAtIndexLocked(int taskId, int i) {
-        while (i < (mHistory.size()-1)) {
+        while (i < mHistory.size()) {
             ActivityRecord r = mHistory.get(i);
             if (r.task.taskId != taskId) {
                 // Whoops hit the end.
diff --git a/services/java/com/android/server/am/AppErrorDialog.java b/services/java/com/android/server/am/AppErrorDialog.java
index a769c05..57e11cf 100644
--- a/services/java/com/android/server/am/AppErrorDialog.java
+++ b/services/java/com/android/server/am/AppErrorDialog.java
@@ -24,6 +24,7 @@
 import android.os.Handler;
 import android.os.Message;
 import android.util.Slog;
+import android.view.WindowManager;
 
 class AppErrorDialog extends BaseErrorDialog {
     private final static String TAG = "AppErrorDialog";
@@ -73,6 +74,9 @@
         setTitle(res.getText(com.android.internal.R.string.aerr_title));
         getWindow().addFlags(FLAG_SYSTEM_ERROR);
         getWindow().setTitle("Application Error: " + app.info.processName);
+        if (app.persistent) {
+            getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
+        }
 
         // After the timeout, pretend the user clicked the quit button
         mHandler.sendMessageDelayed(
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index 0a9ef3d..68f0e66 100644
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -167,6 +167,7 @@
     static final boolean DEBUG_DRAG = false;
     static final boolean DEBUG_SCREEN_ON = false;
     static final boolean DEBUG_SCREENSHOT = false;
+    static final boolean DEBUG_BOOT = false;
     static final boolean SHOW_SURFACE_ALLOC = false;
     static final boolean SHOW_TRANSACTIONS = false;
     static final boolean SHOW_LIGHT_TRANSACTIONS = false || SHOW_TRANSACTIONS;
@@ -4728,6 +4729,14 @@
 
     public void enableScreenAfterBoot() {
         synchronized(mWindowMap) {
+            if (DEBUG_BOOT) {
+                RuntimeException here = new RuntimeException("here");
+                here.fillInStackTrace();
+                Slog.i(TAG, "enableScreenAfterBoot: mDisplayEnabled=" + mDisplayEnabled
+                        + " mForceDisplayEnabled=" + mForceDisplayEnabled
+                        + " mShowingBootMessages=" + mShowingBootMessages
+                        + " mSystemBooted=" + mSystemBooted, here);
+            }
             if (mSystemBooted) {
                 return;
             }
@@ -4745,6 +4754,14 @@
     }
 
     void enableScreenIfNeededLocked() {
+        if (DEBUG_BOOT) {
+            RuntimeException here = new RuntimeException("here");
+            here.fillInStackTrace();
+            Slog.i(TAG, "enableScreenIfNeededLocked: mDisplayEnabled=" + mDisplayEnabled
+                    + " mForceDisplayEnabled=" + mForceDisplayEnabled
+                    + " mShowingBootMessages=" + mShowingBootMessages
+                    + " mSystemBooted=" + mSystemBooted, here);
+        }
         if (mDisplayEnabled) {
             return;
         }
@@ -4767,6 +4784,14 @@
 
     public void performEnableScreen() {
         synchronized(mWindowMap) {
+            if (DEBUG_BOOT) {
+                RuntimeException here = new RuntimeException("here");
+                here.fillInStackTrace();
+                Slog.i(TAG, "performEnableScreen: mDisplayEnabled=" + mDisplayEnabled
+                        + " mForceDisplayEnabled=" + mForceDisplayEnabled
+                        + " mShowingBootMessages=" + mShowingBootMessages
+                        + " mSystemBooted=" + mSystemBooted, here);
+            }
             if (mDisplayEnabled) {
                 return;
             }
@@ -4780,10 +4805,22 @@
                 boolean haveBootMsg = false;
                 boolean haveApp = false;
                 boolean haveWallpaper = false;
-                boolean haveKeyguard = false;
+                boolean haveKeyguard = true;
                 final int N = mWindows.size();
                 for (int i=0; i<N; i++) {
                     WindowState w = mWindows.get(i);
+                    if (w.mAttrs.type == WindowManager.LayoutParams.TYPE_KEYGUARD) {
+                        // Only if there is a keyguard attached to the window manager
+                        // will we consider ourselves as having a keyguard.  If it
+                        // isn't attached, we don't know if it wants to be shown or
+                        // hidden.  If it is attached, we will say we have a keyguard
+                        // if the window doesn't want to be visible, because in that
+                        // case it explicitly doesn't want to be shown so we should
+                        // not delay turning the screen on for it.
+                        boolean vis = w.mViewVisibility == View.VISIBLE
+                                && w.mPolicyVisibility;
+                        haveKeyguard = !vis;
+                    }
                     if (w.isVisibleLw() && !w.mObscured && !w.isDrawnLw()) {
                         return;
                     }
@@ -4800,7 +4837,7 @@
                     }
                 }
 
-                if (DEBUG_SCREEN_ON) {
+                if (DEBUG_SCREEN_ON || DEBUG_BOOT) {
                     Slog.i(TAG, "******** booted=" + mSystemBooted + " msg=" + mShowingBootMessages
                             + " haveBoot=" + haveBootMsg + " haveApp=" + haveApp
                             + " haveWall=" + haveWallpaper + " haveKeyguard=" + haveKeyguard);
@@ -4821,7 +4858,7 @@
             }
 
             mDisplayEnabled = true;
-            if (DEBUG_SCREEN_ON) Slog.i(TAG, "******************** ENABLING SCREEN!");
+            if (DEBUG_SCREEN_ON || DEBUG_BOOT) Slog.i(TAG, "******************** ENABLING SCREEN!");
             if (false) {
                 StringWriter sw = new StringWriter();
                 PrintWriter pw = new PrintWriter(sw);
@@ -4852,6 +4889,14 @@
     public void showBootMessage(final CharSequence msg, final boolean always) {
         boolean first = false;
         synchronized(mWindowMap) {
+            if (DEBUG_BOOT) {
+                RuntimeException here = new RuntimeException("here");
+                here.fillInStackTrace();
+                Slog.i(TAG, "showBootMessage: msg=" + msg + " always=" + always
+                        + " mAllowBootMessages=" + mAllowBootMessages
+                        + " mShowingBootMessages=" + mShowingBootMessages
+                        + " mSystemBooted=" + mSystemBooted, here);
+            }
             if (!mAllowBootMessages) {
                 return;
             }
@@ -4873,6 +4918,14 @@
     }
 
     public void hideBootMessagesLocked() {
+        if (DEBUG_BOOT) {
+            RuntimeException here = new RuntimeException("here");
+            here.fillInStackTrace();
+            Slog.i(TAG, "hideBootMessagesLocked: mDisplayEnabled=" + mDisplayEnabled
+                    + " mForceDisplayEnabled=" + mForceDisplayEnabled
+                    + " mShowingBootMessages=" + mShowingBootMessages
+                    + " mSystemBooted=" + mSystemBooted, here);
+        }
         if (mShowingBootMessages) {
             mShowingBootMessages = false;
             mPolicy.hideBootMessages();
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index feb2c52..b695903 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -368,18 +368,6 @@
                 mCurrentScalingMode);
 
         if (!isFixedSize()) {
-            // we're being resized and there is a freeze display request,
-            // acquire a freeze lock, so that the screen stays put
-            // until we've redrawn at the new size; this is to avoid
-            // glitches upon orientation changes.
-            if (mFlinger->hasFreezeRequest()) {
-                // if the surface is hidden, don't try to acquire the
-                // freeze lock, since hidden surfaces may never redraw
-                if (!(front.flags & ISurfaceComposer::eLayerHidden)) {
-                    mFreezeLock = mFlinger->getFreezeLock();
-                }
-            }
-
             // this will make sure LayerBase::doTransaction doesn't update
             // the drawing state's size
             Layer::State& editDraw(mDrawingState);
@@ -393,14 +381,6 @@
                 temp.requested_h);
     }
 
-    if (temp.sequence != front.sequence) {
-        if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) {
-            // this surface is now hidden, so it shouldn't hold a freeze lock
-            // (it may never redraw, which is fine if it is hidden)
-            mFreezeLock.clear();
-        }
-    }
-        
     return LayerBase::doTransaction(flags);
 }
 
@@ -474,7 +454,7 @@
         glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
         glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 
-        // update the layer size and release freeze-lock
+        // update the layer size if needed
         const Layer::State& front(drawingState());
 
         // FIXME: mPostedDirtyRegion = dirty & bounds
@@ -511,9 +491,6 @@
 
                 // recompute visible region
                 recomputeVisibleRegions = true;
-
-                // we now have the correct size, unfreeze the screen
-                mFreezeLock.clear();
             }
 
             LOGD_IF(DEBUG_RESIZE,
@@ -546,11 +523,6 @@
         dirtyRegion.andSelf(visibleRegionScreen);
         outDirtyRegion.orSelf(dirtyRegion);
     }
-    if (visibleRegionScreen.isEmpty()) {
-        // an invisible layer should not hold a freeze-lock
-        // (because it may never be updated and therefore never release it)
-        mFreezeLock.clear();
-    }
 }
 
 void Layer::dump(String8& result, char* buffer, size_t SIZE) const
@@ -568,9 +540,9 @@
     snprintf(buffer, SIZE,
             "      "
             "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
-            " freezeLock=%p, transform-hint=0x%02x, queued-frames=%d\n",
+            " transform-hint=0x%02x, queued-frames=%d\n",
             mFormat, w0, h0, s0,f0,
-            getFreezeLock().get(), getTransformHint(), mQueuedFrames);
+            getTransformHint(), mQueuedFrames);
 
     result.append(buffer);
 
diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h
index 82e3521..2b9471b 100644
--- a/services/surfaceflinger/Layer.h
+++ b/services/surfaceflinger/Layer.h
@@ -39,7 +39,6 @@
 
 // ---------------------------------------------------------------------------
 
-class FreezeLock;
 class Client;
 class GLExtensions;
 
@@ -80,7 +79,6 @@
     virtual wp<IBinder> getSurfaceTextureBinder() const;
 
     // only for debugging
-    inline const sp<FreezeLock>&  getFreezeLock() const { return mFreezeLock; }
     inline const sp<GraphicBuffer>& getActiveBuffer() const { return mActiveBuffer; }
 
 protected:
@@ -124,9 +122,6 @@
     bool mProtectedByApp; // application requires protected path to external sink
     Region mPostedDirtyRegion;
 
-    // page-flip thread and transaction thread (currently main thread)
-    sp<FreezeLock>  mFreezeLock;
-
     // binder thread, transaction thread
     mutable Mutex mLock;
 };
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 1441a54..7a8952a 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -79,15 +79,12 @@
 SurfaceFlinger::SurfaceFlinger()
     :   BnSurfaceComposer(), Thread(false),
         mTransactionFlags(0),
-        mResizeTransationPending(false),
+        mTransationPending(false),
         mLayersRemoved(false),
         mBootTime(systemTime()),
         mVisibleRegionsDirty(false),
         mHwWorkListDirty(false),
-        mFreezeDisplay(false),
         mElectronBeamAnimationMode(0),
-        mFreezeCount(0),
-        mFreezeDisplayTime(0),
         mDebugRegion(0),
         mDebugBackground(0),
         mDebugDDMS(0),
@@ -190,11 +187,6 @@
 {
     // the window manager died on us. prepare its eulogy.
 
-    // unfreeze the screen in case it was... frozen
-    mFreezeDisplayTime = 0;
-    mFreezeCount = 0;
-    mFreezeDisplay = false;
-
     // reset screen orientation
     setOrientation(0, eOrientationDefault, 0);
 
@@ -322,33 +314,7 @@
 {
     while (true) {
         nsecs_t timeout = -1;
-        const nsecs_t freezeDisplayTimeout = ms2ns(5000);
-        if (UNLIKELY(isFrozen())) {
-            // wait 5 seconds
-            const nsecs_t now = systemTime();
-            if (mFreezeDisplayTime == 0) {
-                mFreezeDisplayTime = now;
-            }
-            nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
-            timeout = waitTime>0 ? waitTime : 0;
-        }
-
         sp<MessageBase> msg = mEventQueue.waitMessage(timeout);
-
-        // see if we timed out
-        if (isFrozen()) {
-            const nsecs_t now = systemTime();
-            nsecs_t frozenTime = (now - mFreezeDisplayTime);
-            if (frozenTime >= freezeDisplayTimeout) {
-                // we timed out and are still frozen
-                LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
-                        mFreezeDisplay, mFreezeCount);
-                mFreezeDisplayTime = 0;
-                mFreezeCount = 0;
-                mFreezeDisplay = false;
-            }
-        }
-
         if (msg != 0) {
             switch (msg->what) {
                 case MessageQueue::INVALIDATE:
@@ -451,7 +417,7 @@
     }
 
     const DisplayHardware& hw(graphicPlane(0).displayHardware());
-    if (LIKELY(hw.canDraw() && !isFrozen())) {
+    if (LIKELY(hw.canDraw())) {
         // repaint the framebuffer (if needed)
 
         const int index = hw.getCurrentBufferIndex();
@@ -478,15 +444,13 @@
 
 void SurfaceFlinger::postFramebuffer()
 {
-    if (!mSwapRegion.isEmpty()) {
-        const DisplayHardware& hw(graphicPlane(0).displayHardware());
-        const nsecs_t now = systemTime();
-        mDebugInSwapBuffers = now;
-        hw.flip(mSwapRegion);
-        mLastSwapBufferTime = systemTime() - now;
-        mDebugInSwapBuffers = 0;
-        mSwapRegion.clear();
-    }
+    const DisplayHardware& hw(graphicPlane(0).displayHardware());
+    const nsecs_t now = systemTime();
+    mDebugInSwapBuffers = now;
+    hw.flip(mSwapRegion);
+    mLastSwapBufferTime = systemTime() - now;
+    mDebugInSwapBuffers = 0;
+    mSwapRegion.clear();
 }
 
 void SurfaceFlinger::handleConsoleEvents()
@@ -582,13 +546,6 @@
             mDirtyRegion.set(hw.bounds());
         }
 
-        if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
-            // freezing or unfreezing the display -> trigger animation if needed
-            mFreezeDisplay = mCurrentState.freezeDisplay;
-            if (mFreezeDisplay)
-                 mFreezeDisplayTime = 0;
-        }
-
         if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
             // layers have been added
             mVisibleRegionsDirty = true;
@@ -614,11 +571,6 @@
     commitTransaction();
 }
 
-sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
-{
-    return new FreezeLock(const_cast<SurfaceFlinger *>(this));
-}
-
 void SurfaceFlinger::computeVisibleRegions(
     const LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
 {
@@ -748,7 +700,7 @@
 void SurfaceFlinger::commitTransaction()
 {
     mDrawingState = mCurrentState;
-    mResizeTransationPending = false;
+    mTransationPending = false;
     mTransactionCV.broadcast();
 }
 
@@ -1235,15 +1187,14 @@
 
 
 void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& state,
-        int orientation) {
+        int orientation, uint32_t flags) {
     Mutex::Autolock _l(mStateLock);
 
-    uint32_t flags = 0;
+    uint32_t transactionFlags = 0;
     if (mCurrentState.orientation != orientation) {
         if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
             mCurrentState.orientation = orientation;
-            flags |= eTransactionNeeded;
-            mResizeTransationPending = true;
+            transactionFlags |= eTransactionNeeded;
         } else if (orientation != eOrientationUnchanged) {
             LOGW("setTransactionState: ignoring unrecognized orientation: %d",
                     orientation);
@@ -1254,56 +1205,29 @@
     for (size_t i=0 ; i<count ; i++) {
         const ComposerState& s(state[i]);
         sp<Client> client( static_cast<Client *>(s.client.get()) );
-        flags |= setClientStateLocked(client, s.state);
+        transactionFlags |= setClientStateLocked(client, s.state);
     }
-    if (flags) {
-        setTransactionFlags(flags);
+    if (transactionFlags) {
+        setTransactionFlags(transactionFlags);
     }
 
-    signalEvent();
-
-    // if there is a transaction with a resize, wait for it to
-    // take effect before returning.
-    while (mResizeTransationPending) {
+    // if this is a synchronous transaction, wait for it to take effect before
+    // returning.
+    if (flags & eSynchronous) {
+        mTransationPending = true;
+    }
+    while (mTransationPending) {
         status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
         if (CC_UNLIKELY(err != NO_ERROR)) {
             // just in case something goes wrong in SF, return to the
             // called after a few seconds.
             LOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
-            mResizeTransationPending = false;
+            mTransationPending = false;
             break;
         }
     }
 }
 
-status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
-{
-    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
-        return BAD_VALUE;
-
-    Mutex::Autolock _l(mStateLock);
-    mCurrentState.freezeDisplay = 1;
-    setTransactionFlags(eTransactionNeeded);
-
-    // flags is intended to communicate some sort of animation behavior
-    // (for instance fading)
-    return NO_ERROR;
-}
-
-status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
-{
-    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
-        return BAD_VALUE;
-
-    Mutex::Autolock _l(mStateLock);
-    mCurrentState.freezeDisplay = 0;
-    setTransactionFlags(eTransactionNeeded);
-
-    // flags is intended to communicate some sort of animation behavior
-    // (for instance fading)
-    return NO_ERROR;
-}
-
 int SurfaceFlinger::setOrientation(DisplayID dpy,
         int orientation, uint32_t flags)
 {
@@ -1489,7 +1413,6 @@
         if (what & eSizeChanged) {
             if (layer->setSize(s.w, s.h)) {
                 flags |= eTraversalNeeded;
-                mResizeTransationPending = true;
             }
         }
         if (what & eAlphaChanged) {
@@ -1609,8 +1532,7 @@
         mWormholeRegion.dump(result, "WormholeRegion");
         const DisplayHardware& hw(graphicPlane(0).displayHardware());
         snprintf(buffer, SIZE,
-                "  display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
-                mFreezeDisplay?"yes":"no", mFreezeCount,
+                "  orientation=%d, canDraw=%d\n",
                 mCurrentState.orientation, hw.canDraw());
         result.append(buffer);
         snprintf(buffer, SIZE,
@@ -1663,8 +1585,6 @@
         case CREATE_CONNECTION:
         case SET_TRANSACTION_STATE:
         case SET_ORIENTATION:
-        case FREEZE_DISPLAY:
-        case UNFREEZE_DISPLAY:
         case BOOT_FINISHED:
         case TURN_ELECTRON_BEAM_OFF:
         case TURN_ELECTRON_BEAM_ON:
@@ -1736,10 +1656,6 @@
                 GraphicLog::getInstance().setEnabled(enabled);
                 return NO_ERROR;
             }
-            case 1007: // set mFreezeCount
-                mFreezeCount = data.readInt32();
-                mFreezeDisplayTime = 0;
-                return NO_ERROR;
             case 1008:  // toggle use of hw composer
                 n = data.readInt32();
                 mDebugDisableHWC = n ? 1 : 0;
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 0e642c1..eabcc9d 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -46,7 +46,6 @@
 
 class Client;
 class DisplayHardware;
-class FreezeLock;
 class Layer;
 class LayerDim;
 struct surface_flinger_cblk_t;
@@ -168,9 +167,7 @@
     virtual sp<IMemoryHeap>             getCblk() const;
     virtual void                        bootFinished();
     virtual void                        setTransactionState(const Vector<ComposerState>& state,
-                                                            int orientation);
-    virtual status_t                    freezeDisplay(DisplayID dpy, uint32_t flags);
-    virtual status_t                    unfreezeDisplay(DisplayID dpy, uint32_t flags);
+                                                            int orientation, uint32_t flags);
     virtual int                         setOrientation(DisplayID dpy, int orientation, uint32_t flags);
     virtual bool                        authenticateSurfaceTexture(const sp<ISurfaceTexture>& surface) const;
 
@@ -244,12 +241,10 @@
     struct State {
         State() {
             orientation = ISurfaceComposer::eOrientationDefault;
-            freezeDisplay = 0;
         }
         LayerVector     layersSortedByZ;
         uint8_t         orientation;
         uint8_t         orientationFlags;
-        uint8_t         freezeDisplay;
     };
 
     virtual bool        threadLoop();
@@ -308,20 +303,6 @@
             status_t renderScreenToTextureLocked(DisplayID dpy,
                     GLuint* textureName, GLfloat* uOut, GLfloat* vOut);
 
-            friend class FreezeLock;
-            sp<FreezeLock> getFreezeLock() const;
-            inline void incFreezeCount() {
-                if (mFreezeCount == 0)
-                    mFreezeDisplayTime = 0;
-                mFreezeCount++;
-            }
-            inline void decFreezeCount() { if (mFreezeCount > 0) mFreezeCount--; }
-            inline bool hasFreezeRequest() const { return mFreezeDisplay; }
-            inline bool isFrozen() const { 
-                return (mFreezeDisplay || mFreezeCount>0) && mBootFinished;
-            }
-
-            
             void        debugFlashRegions();
             void        debugShowFPS() const;
             void        drawWormhole() const;
@@ -341,7 +322,7 @@
     volatile    int32_t                 mTransactionFlags;
                 Condition               mTransactionCV;
                 SortedVector< sp<LayerBase> > mLayerPurgatory;
-                bool                    mResizeTransationPending;
+                bool                    mTransationPending;
 
                 // protected by mStateLock (but we could use another lock)
                 GraphicPlane                mGraphicPlanes[1];
@@ -364,10 +345,7 @@
                 Region                      mWormholeRegion;
                 bool                        mVisibleRegionsDirty;
                 bool                        mHwWorkListDirty;
-                bool                        mFreezeDisplay;
                 int32_t                     mElectronBeamAnimationMode;
-                int32_t                     mFreezeCount;
-                nsecs_t                     mFreezeDisplayTime;
                 Vector< sp<LayerBase> >     mVisibleLayersSortedByZ;
 
 
@@ -403,20 +381,6 @@
 };
 
 // ---------------------------------------------------------------------------
-
-class FreezeLock : public LightRefBase<FreezeLock> {
-    SurfaceFlinger* mFlinger;
-public:
-    FreezeLock(SurfaceFlinger* flinger)
-        : mFlinger(flinger) {
-        mFlinger->incFreezeCount();
-    }
-    ~FreezeLock() {
-        mFlinger->decFreezeCount();
-    }
-};
-
-// ---------------------------------------------------------------------------
 }; // namespace android
 
 #endif // ANDROID_SURFACE_FLINGER_H
diff --git a/services/surfaceflinger/tests/Android.mk b/services/surfaceflinger/tests/Android.mk
index 5053e7d..b655648 100644
--- a/services/surfaceflinger/tests/Android.mk
+++ b/services/surfaceflinger/tests/Android.mk
@@ -1 +1,40 @@
-include $(call all-subdir-makefiles)
+# Build the unit tests,
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := SurfaceFlinger_test
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := \
+    Transaction_test.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+	libEGL \
+	libGLESv2 \
+	libandroid \
+	libbinder \
+	libcutils \
+	libgui \
+	libstlport \
+	libui \
+	libutils \
+
+LOCAL_C_INCLUDES := \
+    bionic \
+    bionic/libstdc++/include \
+    external/gtest/include \
+    external/stlport/stlport \
+
+# Build the binary to $(TARGET_OUT_DATA_NATIVE_TESTS)/$(LOCAL_MODULE)
+# to integrate with auto-test framework.
+include $(BUILD_NATIVE_TEST)
+
+# Include subdirectory makefiles
+# ============================================================
+
+# If we're building with ONE_SHOT_MAKEFILE (mm, mmm), then what the framework
+# team really wants is to build the stuff defined by this makefile.
+ifeq (,$(ONE_SHOT_MAKEFILE))
+include $(call first-makefiles-under,$(LOCAL_PATH))
+endif
diff --git a/services/surfaceflinger/tests/Transaction_test.cpp b/services/surfaceflinger/tests/Transaction_test.cpp
new file mode 100644
index 0000000..afafd8a
--- /dev/null
+++ b/services/surfaceflinger/tests/Transaction_test.cpp
@@ -0,0 +1,236 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include <binder/IMemory.h>
+#include <surfaceflinger/ISurfaceComposer.h>
+#include <surfaceflinger/Surface.h>
+#include <surfaceflinger/SurfaceComposerClient.h>
+#include <utils/String8.h>
+
+namespace android {
+
+// Fill an RGBA_8888 formatted surface with a single color.
+static void fillSurfaceRGBA8(const sp<SurfaceControl>& sc,
+        uint8_t r, uint8_t g, uint8_t b) {
+    Surface::SurfaceInfo info;
+    sp<Surface> s = sc->getSurface();
+    ASSERT_TRUE(s != NULL);
+    ASSERT_EQ(NO_ERROR, s->lock(&info));
+    uint8_t* img = reinterpret_cast<uint8_t*>(info.bits);
+    for (uint32_t y = 0; y < info.h; y++) {
+        for (uint32_t x = 0; x < info.w; x++) {
+            uint8_t* pixel = img + (4 * (y*info.s + x));
+            pixel[0] = r;
+            pixel[1] = g;
+            pixel[2] = b;
+            pixel[3] = 255;
+        }
+    }
+    ASSERT_EQ(NO_ERROR, s->unlockAndPost());
+}
+
+// A ScreenCapture is a screenshot from SurfaceFlinger that can be used to check
+// individual pixel values for testing purposes.
+class ScreenCapture : public RefBase {
+public:
+    static void captureScreen(sp<ScreenCapture>* sc) {
+        sp<IMemoryHeap> heap;
+        uint32_t w=0, h=0;
+        PixelFormat fmt=0;
+        sp<ISurfaceComposer> sf(ComposerService::getComposerService());
+        ASSERT_EQ(NO_ERROR, sf->captureScreen(0, &heap, &w, &h, &fmt, 0, 0,
+                0, INT_MAX));
+        ASSERT_TRUE(heap != NULL);
+        ASSERT_EQ(PIXEL_FORMAT_RGBA_8888, fmt);
+        *sc = new ScreenCapture(w, h, heap);
+    }
+
+    void checkPixel(uint32_t x, uint32_t y, uint8_t r, uint8_t g, uint8_t b) {
+        const uint8_t* img = reinterpret_cast<const uint8_t*>(mHeap->base());
+        const uint8_t* pixel = img + (4 * (y*mWidth + x));
+        if (r != pixel[0] || g != pixel[1] || b != pixel[2]) {
+            String8 err(String8::format("pixel @ (%3d, %3d): "
+                    "expected [%3d, %3d, %3d], got [%3d, %3d, %3d]",
+                    x, y, r, g, b, pixel[0], pixel[1], pixel[2]));
+            EXPECT_EQ(String8(), err);
+        }
+    }
+
+private:
+    ScreenCapture(uint32_t w, uint32_t h, const sp<IMemoryHeap>& heap) :
+        mWidth(w),
+        mHeight(h),
+        mHeap(heap)
+    {}
+
+    const uint32_t mWidth;
+    const uint32_t mHeight;
+    sp<IMemoryHeap> mHeap;
+};
+
+class LayerUpdateTest : public ::testing::Test {
+protected:
+    virtual void SetUp() {
+        mComposerClient = new SurfaceComposerClient;
+        ASSERT_EQ(NO_ERROR, mComposerClient->initCheck());
+
+        ssize_t displayWidth = mComposerClient->getDisplayWidth(0);
+        ssize_t displayHeight = mComposerClient->getDisplayHeight(0);
+
+        // Background surface
+        mBGSurfaceControl = mComposerClient->createSurface(
+                String8("BG Test Surface"), 0, displayWidth, displayHeight,
+                PIXEL_FORMAT_RGBA_8888, 0);
+        ASSERT_TRUE(mBGSurfaceControl != NULL);
+        ASSERT_TRUE(mBGSurfaceControl->isValid());
+        fillSurfaceRGBA8(mBGSurfaceControl, 63, 63, 195);
+
+        // Foreground surface
+        mFGSurfaceControl = mComposerClient->createSurface(
+                String8("FG Test Surface"), 0, 64, 64, PIXEL_FORMAT_RGBA_8888, 0);
+        ASSERT_TRUE(mFGSurfaceControl != NULL);
+        ASSERT_TRUE(mFGSurfaceControl->isValid());
+
+        fillSurfaceRGBA8(mFGSurfaceControl, 195, 63, 63);
+
+        // Synchronization surface
+        mSyncSurfaceControl = mComposerClient->createSurface(
+                String8("Sync Test Surface"), 0, 1, 1, PIXEL_FORMAT_RGBA_8888, 0);
+        ASSERT_TRUE(mSyncSurfaceControl != NULL);
+        ASSERT_TRUE(mSyncSurfaceControl->isValid());
+
+        fillSurfaceRGBA8(mSyncSurfaceControl, 31, 31, 31);
+
+        SurfaceComposerClient::openGlobalTransaction();
+
+        ASSERT_EQ(NO_ERROR, mBGSurfaceControl->setLayer(INT_MAX-2));
+        ASSERT_EQ(NO_ERROR, mBGSurfaceControl->show());
+
+        ASSERT_EQ(NO_ERROR, mFGSurfaceControl->setLayer(INT_MAX-1));
+        ASSERT_EQ(NO_ERROR, mFGSurfaceControl->setPosition(64, 64));
+        ASSERT_EQ(NO_ERROR, mFGSurfaceControl->show());
+
+        ASSERT_EQ(NO_ERROR, mSyncSurfaceControl->setLayer(INT_MAX-1));
+        ASSERT_EQ(NO_ERROR, mSyncSurfaceControl->setPosition(displayWidth-2,
+                displayHeight-2));
+        ASSERT_EQ(NO_ERROR, mSyncSurfaceControl->show());
+
+        SurfaceComposerClient::closeGlobalTransaction(true);
+    }
+
+    virtual void TearDown() {
+        mComposerClient->dispose();
+        mBGSurfaceControl = 0;
+        mFGSurfaceControl = 0;
+        mSyncSurfaceControl = 0;
+        mComposerClient = 0;
+    }
+
+    void waitForPostedBuffers() {
+        // Since the sync surface is in synchronous mode (i.e. double buffered)
+        // posting three buffers to it should ensure that at least two
+        // SurfaceFlinger::handlePageFlip calls have been made, which should
+        // guaranteed that a buffer posted to another Surface has been retired.
+        fillSurfaceRGBA8(mSyncSurfaceControl, 31, 31, 31);
+        fillSurfaceRGBA8(mSyncSurfaceControl, 31, 31, 31);
+        fillSurfaceRGBA8(mSyncSurfaceControl, 31, 31, 31);
+    }
+
+    sp<SurfaceComposerClient> mComposerClient;
+    sp<SurfaceControl> mBGSurfaceControl;
+    sp<SurfaceControl> mFGSurfaceControl;
+
+    // This surface is used to ensure that the buffers posted to
+    // mFGSurfaceControl have been picked up by SurfaceFlinger.
+    sp<SurfaceControl> mSyncSurfaceControl;
+};
+
+TEST_F(LayerUpdateTest, LayerMoveWorks) {
+    sp<ScreenCapture> sc;
+    {
+        SCOPED_TRACE("before move");
+        ScreenCapture::captureScreen(&sc);
+        sc->checkPixel(  0,  12,  63,  63, 195);
+        sc->checkPixel( 75,  75, 195,  63,  63);
+        sc->checkPixel(145, 145,  63,  63, 195);
+    }
+
+    SurfaceComposerClient::openGlobalTransaction();
+    ASSERT_EQ(NO_ERROR, mFGSurfaceControl->setPosition(128, 128));
+    SurfaceComposerClient::closeGlobalTransaction(true);
+    {
+        // This should reflect the new position, but not the new color.
+        SCOPED_TRACE("after move, before redraw");
+        ScreenCapture::captureScreen(&sc);
+        sc->checkPixel( 24,  24,  63,  63, 195);
+        sc->checkPixel( 75,  75,  63,  63, 195);
+        sc->checkPixel(145, 145, 195,  63,  63);
+    }
+
+    fillSurfaceRGBA8(mFGSurfaceControl, 63, 195, 63);
+    waitForPostedBuffers();
+    {
+        // This should reflect the new position and the new color.
+        SCOPED_TRACE("after redraw");
+        ScreenCapture::captureScreen(&sc);
+        sc->checkPixel( 24,  24,  63,  63, 195);
+        sc->checkPixel( 75,  75,  63,  63, 195);
+        sc->checkPixel(145, 145,  63, 195,  63);
+    }
+}
+
+TEST_F(LayerUpdateTest, LayerResizeWorks) {
+    sp<ScreenCapture> sc;
+    {
+        SCOPED_TRACE("before resize");
+        ScreenCapture::captureScreen(&sc);
+        sc->checkPixel(  0,  12,  63,  63, 195);
+        sc->checkPixel( 75,  75, 195,  63,  63);
+        sc->checkPixel(145, 145,  63,  63, 195);
+    }
+
+    LOGD("resizing");
+    SurfaceComposerClient::openGlobalTransaction();
+    ASSERT_EQ(NO_ERROR, mFGSurfaceControl->setSize(128, 128));
+    SurfaceComposerClient::closeGlobalTransaction(true);
+    LOGD("resized");
+    {
+        // This should not reflect the new size or color because SurfaceFlinger
+        // has not yet received a buffer of the correct size.
+        SCOPED_TRACE("after resize, before redraw");
+        ScreenCapture::captureScreen(&sc);
+        sc->checkPixel(  0,  12,  63,  63, 195);
+        sc->checkPixel( 75,  75, 195,  63,  63);
+        sc->checkPixel(145, 145,  63,  63, 195);
+    }
+
+    LOGD("drawing");
+    fillSurfaceRGBA8(mFGSurfaceControl, 63, 195, 63);
+    waitForPostedBuffers();
+    LOGD("drawn");
+    {
+        // This should reflect the new size and the new color.
+        SCOPED_TRACE("after redraw");
+        ScreenCapture::captureScreen(&sc);
+        sc->checkPixel( 24,  24,  63,  63, 195);
+        sc->checkPixel( 75,  75,  63, 195,  63);
+        sc->checkPixel(145, 145,  63, 195,  63);
+    }
+}
+
+}
diff --git a/telephony/java/com/android/internal/telephony/IccProvider.java b/telephony/java/com/android/internal/telephony/IccProvider.java
index 3471ec2..a66e19d 100644
--- a/telephony/java/com/android/internal/telephony/IccProvider.java
+++ b/telephony/java/com/android/internal/telephony/IccProvider.java
@@ -19,166 +19,20 @@
 import android.content.ContentProvider;
 import android.content.UriMatcher;
 import android.content.ContentValues;
-import android.database.AbstractCursor;
 import android.database.Cursor;
-import android.database.CursorWindow;
+import android.database.MatrixCursor;
 import android.net.Uri;
-import android.os.SystemProperties;
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.text.TextUtils;
 import android.util.Log;
 
-import java.util.ArrayList;
 import java.util.List;
 
 import com.android.internal.telephony.IccConstants;
 import com.android.internal.telephony.AdnRecord;
 import com.android.internal.telephony.IIccPhoneBook;
 
-/**
- * XXX old code -- should be replaced with MatrixCursor.
- * @deprecated This is has been replaced by MatrixCursor.
-*/
-class ArrayListCursor extends AbstractCursor {
-    private String[] mColumnNames;
-    private ArrayList<Object>[] mRows;
-
-    @SuppressWarnings({"unchecked"})
-    public ArrayListCursor(String[] columnNames, ArrayList<ArrayList> rows) {
-        int colCount = columnNames.length;
-        boolean foundID = false;
-        // Add an _id column if not in columnNames
-        for (int i = 0; i < colCount; ++i) {
-            if (columnNames[i].compareToIgnoreCase("_id") == 0) {
-                mColumnNames = columnNames;
-                foundID = true;
-                break;
-            }
-        }
-
-        if (!foundID) {
-            mColumnNames = new String[colCount + 1];
-            System.arraycopy(columnNames, 0, mColumnNames, 0, columnNames.length);
-            mColumnNames[colCount] = "_id";
-        }
-
-        int rowCount = rows.size();
-        mRows = new ArrayList[rowCount];
-
-        for (int i = 0; i < rowCount; ++i) {
-            mRows[i] = rows.get(i);
-            if (!foundID) {
-                mRows[i].add(i);
-            }
-        }
-    }
-
-    @Override
-    public void fillWindow(int position, CursorWindow window) {
-        if (position < 0 || position > getCount()) {
-            return;
-        }
-
-        window.acquireReference();
-        try {
-            int oldpos = mPos;
-            mPos = position - 1;
-            window.clear();
-            window.setStartPosition(position);
-            int columnNum = getColumnCount();
-            window.setNumColumns(columnNum);
-            while (moveToNext() && window.allocRow()) {
-                for (int i = 0; i < columnNum; i++) {
-                    final Object data = mRows[mPos].get(i);
-                    if (data != null) {
-                        if (data instanceof byte[]) {
-                            byte[] field = (byte[]) data;
-                            if (!window.putBlob(field, mPos, i)) {
-                                window.freeLastRow();
-                                break;
-                            }
-                        } else {
-                            String field = data.toString();
-                            if (!window.putString(field, mPos, i)) {
-                                window.freeLastRow();
-                                break;
-                            }
-                        }
-                    } else {
-                        if (!window.putNull(mPos, i)) {
-                            window.freeLastRow();
-                            break;
-                        }
-                    }
-                }
-            }
-
-            mPos = oldpos;
-        } catch (IllegalStateException e){
-            // simply ignore it
-        } finally {
-            window.releaseReference();
-        }
-    }
-
-    @Override
-    public int getCount() {
-        return mRows.length;
-    }
-
-    @Override
-    public String[] getColumnNames() {
-        return mColumnNames;
-    }
-
-    @Override
-    public byte[] getBlob(int columnIndex) {
-        return (byte[]) mRows[mPos].get(columnIndex);
-    }
-
-    @Override
-    public String getString(int columnIndex) {
-        Object cell = mRows[mPos].get(columnIndex);
-        return (cell == null) ? null : cell.toString();
-    }
-
-    @Override
-    public short getShort(int columnIndex) {
-        Number num = (Number) mRows[mPos].get(columnIndex);
-        return num.shortValue();
-    }
-
-    @Override
-    public int getInt(int columnIndex) {
-        Number num = (Number) mRows[mPos].get(columnIndex);
-        return num.intValue();
-    }
-
-    @Override
-    public long getLong(int columnIndex) {
-        Number num = (Number) mRows[mPos].get(columnIndex);
-        return num.longValue();
-    }
-
-    @Override
-    public float getFloat(int columnIndex) {
-        Number num = (Number) mRows[mPos].get(columnIndex);
-        return num.floatValue();
-    }
-
-    @Override
-    public double getDouble(int columnIndex) {
-        Number num = (Number) mRows[mPos].get(columnIndex);
-        return num.doubleValue();
-    }
-
-    @Override
-    public boolean isNull(int columnIndex) {
-        return mRows[mPos].get(columnIndex) == null;
-    }
-}
-
 
 /**
  * {@hide}
@@ -191,7 +45,8 @@
     private static final String[] ADDRESS_BOOK_COLUMN_NAMES = new String[] {
         "name",
         "number",
-        "emails"
+        "emails",
+        "_id"
     };
 
     private static final int ADN = 1;
@@ -213,70 +68,27 @@
     }
 
 
-    private boolean mSimulator;
-
     @Override
     public boolean onCreate() {
-        String device = SystemProperties.get("ro.product.device");
-        if (!TextUtils.isEmpty(device)) {
-            mSimulator = false;
-        } else {
-            // simulator
-            mSimulator = true;
-        }
-
         return true;
     }
 
     @Override
     public Cursor query(Uri url, String[] projection, String selection,
             String[] selectionArgs, String sort) {
-        ArrayList<ArrayList> results;
+        switch (URL_MATCHER.match(url)) {
+            case ADN:
+                return loadFromEf(IccConstants.EF_ADN);
 
-        if (!mSimulator) {
-            switch (URL_MATCHER.match(url)) {
-                case ADN:
-                    results = loadFromEf(IccConstants.EF_ADN);
-                    break;
+            case FDN:
+                return loadFromEf(IccConstants.EF_FDN);
 
-                case FDN:
-                    results = loadFromEf(IccConstants.EF_FDN);
-                    break;
+            case SDN:
+                return loadFromEf(IccConstants.EF_SDN);
 
-                case SDN:
-                    results = loadFromEf(IccConstants.EF_SDN);
-                    break;
-
-                default:
-                    throw new IllegalArgumentException("Unknown URL " + url);
-            }
-        } else {
-            // Fake up some data for the simulator
-            results = new ArrayList<ArrayList>(4);
-            ArrayList<String> contact;
-
-            contact = new ArrayList<String>();
-            contact.add("Ron Stevens/H");
-            contact.add("512-555-5038");
-            results.add(contact);
-
-            contact = new ArrayList<String>();
-            contact.add("Ron Stevens/M");
-            contact.add("512-555-8305");
-            results.add(contact);
-
-            contact = new ArrayList<String>();
-            contact.add("Melissa Owens");
-            contact.add("512-555-8305");
-            results.add(contact);
-
-            contact = new ArrayList<String>();
-            contact.add("Directory Assistence");
-            contact.add("411");
-            results.add(contact);
+            default:
+                throw new IllegalArgumentException("Unknown URL " + url);
         }
-
-        return new ArrayListCursor(ADDRESS_BOOK_COLUMN_NAMES, results);
     }
 
     @Override
@@ -473,12 +285,10 @@
         return 1;
     }
 
-    private ArrayList<ArrayList> loadFromEf(int efType) {
-        ArrayList<ArrayList> results = new ArrayList<ArrayList>();
-        List<AdnRecord> adnRecords = null;
-
+    private MatrixCursor loadFromEf(int efType) {
         if (DBG) log("loadFromEf: efType=" + efType);
 
+        List<AdnRecord> adnRecords = null;
         try {
             IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(
                     ServiceManager.getService("simphonebook"));
@@ -490,21 +300,21 @@
         } catch (SecurityException ex) {
             if (DBG) log(ex.toString());
         }
+
         if (adnRecords != null) {
             // Load the results
-
-            int N = adnRecords.size();
+            final int N = adnRecords.size();
+            final MatrixCursor cursor = new MatrixCursor(ADDRESS_BOOK_COLUMN_NAMES, N);
             if (DBG) log("adnRecords.size=" + N);
             for (int i = 0; i < N ; i++) {
-                loadRecord(adnRecords.get(i), results);
+                loadRecord(adnRecords.get(i), cursor, i);
             }
+            return cursor;
         } else {
             // No results to load
             Log.w(TAG, "Cannot load ADN records");
-            results.clear();
+            return new MatrixCursor(ADDRESS_BOOK_COLUMN_NAMES);
         }
-        if (DBG) log("loadFromEf: return results");
-        return results;
     }
 
     private boolean
@@ -584,35 +394,33 @@
     }
 
     /**
-     * Loads an AdnRecord into an ArrayList. Must be called with mLock held.
+     * Loads an AdnRecord into a MatrixCursor. Must be called with mLock held.
      *
      * @param record the ADN record to load from
-     * @param results the array list to put the results in
+     * @param cursor the cursor to receive the results
      */
-    private void loadRecord(AdnRecord record,
-            ArrayList<ArrayList> results) {
+    private void loadRecord(AdnRecord record, MatrixCursor cursor, int id) {
         if (!record.isEmpty()) {
-            ArrayList<String> contact = new ArrayList<String>();
+            Object[] contact = new Object[4];
             String alphaTag = record.getAlphaTag();
             String number = record.getNumber();
-            String[] emails = record.getEmails();
 
             if (DBG) log("loadRecord: " + alphaTag + ", " + number + ",");
-            contact.add(alphaTag);
-            contact.add(number);
-            StringBuilder emailString = new StringBuilder();
+            contact[0] = alphaTag;
+            contact[1] = number;
 
+            String[] emails = record.getEmails();
             if (emails != null) {
+                StringBuilder emailString = new StringBuilder();
                 for (String email: emails) {
                     if (DBG) log("Adding email:" + email);
                     emailString.append(email);
                     emailString.append(",");
                 }
-                contact.add(emailString.toString());
-            } else {
-                contact.add(null);
+                contact[2] = emailString.toString();
             }
-            results.add(contact);
+            contact[3] = id;
+            cursor.addRow(contact);
         }
     }
 
diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java b/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java
index 8f5a2eb..3d6cd68 100755
--- a/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java
@@ -726,7 +726,7 @@
                 isPrlLoaded = false;
             }
             if (!isPrlLoaded) {
-                newSS.setCdmaRoamingIndicator(EriInfo.ROAMING_INDICATOR_FLASH);
+                newSS.setCdmaRoamingIndicator(EriInfo.ROAMING_INDICATOR_OFF);
             } else if (!isSidsAllZeros()) {
                 if (!namMatch && !mIsInPrl) {
                     // Use default
diff --git a/tests/RenderScriptTests/ComputePerf/Android.mk b/tests/RenderScriptTests/ComputePerf/Android.mk
new file mode 100644
index 0000000..1d67d29
--- /dev/null
+++ b/tests/RenderScriptTests/ComputePerf/Android.mk
@@ -0,0 +1,27 @@
+#
+# Copyright (C) 2011 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src) \
+                   $(call all-renderscript-files-under, src)
+
+LOCAL_PACKAGE_NAME := RsComputePerf
+
+include $(BUILD_PACKAGE)
diff --git a/tests/RenderScriptTests/ComputePerf/AndroidManifest.xml b/tests/RenderScriptTests/ComputePerf/AndroidManifest.xml
new file mode 100644
index 0000000..a9193b5
--- /dev/null
+++ b/tests/RenderScriptTests/ComputePerf/AndroidManifest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.example.android.rs.computeperf">
+
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    
+    <uses-sdk android:minSdkVersion="14" />
+    <application android:label="Compute Perf">
+        <activity android:name="ComputePerf">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+</manifest>
diff --git a/tests/RenderScriptTests/ComputePerf/res/layout/main.xml b/tests/RenderScriptTests/ComputePerf/res/layout/main.xml
new file mode 100644
index 0000000..61cd24d
--- /dev/null
+++ b/tests/RenderScriptTests/ComputePerf/res/layout/main.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent">
+
+    <ImageView
+        android:id="@+id/displayin"
+        android:layout_width="320dip"
+        android:layout_height="266dip" />
+
+    <ImageView
+        android:id="@+id/displayout"
+        android:layout_width="320dip"
+        android:layout_height="266dip" />
+
+</LinearLayout>
diff --git a/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/ComputePerf.java b/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/ComputePerf.java
new file mode 100644
index 0000000..d0e089b
--- /dev/null
+++ b/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/ComputePerf.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.android.rs.computeperf;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.graphics.BitmapFactory;
+import android.graphics.Bitmap;
+import android.renderscript.RenderScript;
+import android.renderscript.Allocation;
+import android.widget.ImageView;
+
+public class ComputePerf extends Activity {
+
+    private LaunchTest mLT;
+    private RenderScript mRS;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.main);
+
+        mRS = RenderScript.create(this);
+        mLT = new LaunchTest(mRS, getResources());
+        mLT.run();
+        mLT.run();
+    }
+
+}
diff --git a/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/LaunchTest.java b/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/LaunchTest.java
new file mode 100644
index 0000000..0c29ce1
--- /dev/null
+++ b/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/LaunchTest.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.example.android.rs.computeperf;
+
+import android.content.res.Resources;
+import android.renderscript.*;
+
+public class LaunchTest implements Runnable {
+    private RenderScript mRS;
+    private Allocation mAllocationX;
+    private Allocation mAllocationXY;
+    private ScriptC_launchtestxlw mScript_xlw;
+    private ScriptC_launchtestxyw mScript_xyw;
+
+    LaunchTest(RenderScript rs, Resources res) {
+        mRS = rs;
+        mScript_xlw = new ScriptC_launchtestxlw(mRS, res, R.raw.launchtestxlw);
+        mScript_xyw = new ScriptC_launchtestxyw(mRS, res, R.raw.launchtestxyw);
+        final int dim = mScript_xlw.get_dim();
+
+        mAllocationX = Allocation.createSized(rs, Element.U8(rs), dim);
+        Type.Builder tb = new Type.Builder(rs, Element.U8(rs));
+        tb.setX(dim);
+        tb.setY(dim);
+        mAllocationXY = Allocation.createTyped(rs, tb.create());
+        mScript_xlw.bind_buf(mAllocationXY);
+    }
+
+    public void run() {
+        long t = java.lang.System.currentTimeMillis();
+        mScript_xlw.forEach_root(mAllocationX);
+        mRS.finish();
+        t = java.lang.System.currentTimeMillis() - t;
+        android.util.Log.v("ComputePerf", "xlw launch test  ms " + t);
+
+        t = java.lang.System.currentTimeMillis();
+        mScript_xyw.forEach_root(mAllocationXY);
+        mRS.finish();
+        t = java.lang.System.currentTimeMillis() - t;
+        android.util.Log.v("ComputePerf", "xyw launch test  ms " + t);
+    }
+
+}
diff --git a/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/launchtestxlw.rs b/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/launchtestxlw.rs
new file mode 100644
index 0000000..7b81dfe
--- /dev/null
+++ b/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/launchtestxlw.rs
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma version(1)
+#pragma rs java_package_name(com.example.android.rs.computeperf)
+
+const int dim = 2048;
+uint8_t *buf;
+
+void root(uchar *v_out, uint32_t x) {
+    uint8_t *p = buf;
+    p += x * dim;
+    for (int i=0; i<dim; i++) {
+        p[i] = 1;
+    }
+}
+
diff --git a/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/launchtestxyw.rs b/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/launchtestxyw.rs
new file mode 100644
index 0000000..7f7aa95
--- /dev/null
+++ b/tests/RenderScriptTests/ComputePerf/src/com/example/android/rs/computeperf/launchtestxyw.rs
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma version(1)
+#pragma rs java_package_name(com.example.android.rs.computeperf)
+
+void root(uchar *v_out, uint32_t x, uint32_t y) {
+    *v_out = 0;
+}
+
diff --git a/tests/RenderScriptTests/tests/src/com/android/rs/test/RSTestCore.java b/tests/RenderScriptTests/tests/src/com/android/rs/test/RSTestCore.java
index c038478..4466e59 100644
--- a/tests/RenderScriptTests/tests/src/com/android/rs/test/RSTestCore.java
+++ b/tests/RenderScriptTests/tests/src/com/android/rs/test/RSTestCore.java
@@ -64,6 +64,9 @@
 
         unitTests = new ArrayList<UnitTest>();
 
+        unitTests.add(new UT_sampler(this, mRes, mCtx));
+        unitTests.add(new UT_program_store(this, mRes, mCtx));
+        unitTests.add(new UT_program_raster(this, mRes, mCtx));
         unitTests.add(new UT_primitives(this, mRes, mCtx));
         unitTests.add(new UT_vector(this, mRes, mCtx));
         unitTests.add(new UT_rsdebug(this, mRes, mCtx));
diff --git a/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_program_raster.java b/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_program_raster.java
new file mode 100644
index 0000000..1fbf97a
--- /dev/null
+++ b/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_program_raster.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.rs.test;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.renderscript.*;
+import android.renderscript.ProgramRaster;
+import android.renderscript.ProgramRaster.CullMode;
+
+public class UT_program_raster extends UnitTest {
+    private Resources mRes;
+
+    protected UT_program_raster(RSTestCore rstc, Resources res, Context ctx) {
+        super(rstc, "ProgramRaster", ctx);
+        mRes = res;
+    }
+
+    private ProgramRaster.Builder getDefaultBuilder(RenderScript RS) {
+        ProgramRaster.Builder b = new ProgramRaster.Builder(RS);
+        b.setCullMode(CullMode.BACK);
+        b.setPointSpriteEnabled(false);
+        return b;
+    }
+
+    private void initializeGlobals(RenderScript RS, ScriptC_program_raster s) {
+        ProgramRaster.Builder b = getDefaultBuilder(RS);
+        s.set_pointSpriteEnabled(b.setPointSpriteEnabled(true).create());
+        b = getDefaultBuilder(RS);
+        s.set_cullMode(b.setCullMode(CullMode.FRONT).create());
+        return;
+    }
+
+    public void run() {
+        RenderScript pRS = RenderScript.create(mCtx);
+        ScriptC_program_raster s = new ScriptC_program_raster(pRS, mRes, R.raw.program_raster);
+        pRS.setMessageHandler(mRsMessage);
+        initializeGlobals(pRS, s);
+        s.invoke_program_raster_test();
+        pRS.finish();
+        waitForMessage();
+        pRS.destroy();
+    }
+}
diff --git a/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_program_store.java b/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_program_store.java
new file mode 100644
index 0000000..e06112c
--- /dev/null
+++ b/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_program_store.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.rs.test;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.renderscript.*;
+import android.renderscript.ProgramStore.BlendDstFunc;
+import android.renderscript.ProgramStore.BlendSrcFunc;
+import android.renderscript.ProgramStore.Builder;
+import android.renderscript.ProgramStore.DepthFunc;
+
+public class UT_program_store extends UnitTest {
+    private Resources mRes;
+
+    protected UT_program_store(RSTestCore rstc, Resources res, Context ctx) {
+        super(rstc, "ProgramStore", ctx);
+        mRes = res;
+    }
+
+    private ProgramStore.Builder getDefaultBuilder(RenderScript RS) {
+        ProgramStore.Builder b = new ProgramStore.Builder(RS);
+        b.setBlendFunc(ProgramStore.BlendSrcFunc.ZERO, ProgramStore.BlendDstFunc.ZERO);
+        b.setColorMaskEnabled(false, false, false, false);
+        b.setDepthFunc(ProgramStore.DepthFunc.ALWAYS);
+        b.setDepthMaskEnabled(false);
+        b.setDitherEnabled(false);
+        return b;
+    }
+
+    private void initializeGlobals(RenderScript RS, ScriptC_program_store s) {
+        ProgramStore.Builder b = getDefaultBuilder(RS);
+        s.set_ditherEnable(b.setDitherEnabled(true).create());
+
+        b = getDefaultBuilder(RS);
+        s.set_colorRWriteEnable(b.setColorMaskEnabled(true,  false, false, false).create());
+
+        b = getDefaultBuilder(RS);
+        s.set_colorGWriteEnable(b.setColorMaskEnabled(false, true,  false, false).create());
+
+        b = getDefaultBuilder(RS);
+        s.set_colorBWriteEnable(b.setColorMaskEnabled(false, false, true,  false).create());
+
+        b = getDefaultBuilder(RS);
+        s.set_colorAWriteEnable(b.setColorMaskEnabled(false, false, false, true).create());
+
+        b = getDefaultBuilder(RS);
+        s.set_blendSrc(b.setBlendFunc(ProgramStore.BlendSrcFunc.DST_COLOR,
+                                      ProgramStore.BlendDstFunc.ZERO).create());
+
+        b = getDefaultBuilder(RS);
+        s.set_blendDst(b.setBlendFunc(ProgramStore.BlendSrcFunc.ZERO,
+                                      ProgramStore.BlendDstFunc.DST_ALPHA).create());
+
+        b = getDefaultBuilder(RS);
+        s.set_depthWriteEnable(b.setDepthMaskEnabled(true).create());
+
+        b = getDefaultBuilder(RS);
+        s.set_depthFunc(b.setDepthFunc(ProgramStore.DepthFunc.GREATER).create());
+        return;
+    }
+
+    public void run() {
+        RenderScript pRS = RenderScript.create(mCtx);
+        ScriptC_program_store s = new ScriptC_program_store(pRS, mRes, R.raw.program_store);
+        pRS.setMessageHandler(mRsMessage);
+        initializeGlobals(pRS, s);
+        s.invoke_program_store_test();
+        pRS.finish();
+        waitForMessage();
+        pRS.destroy();
+    }
+}
diff --git a/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_sampler.java b/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_sampler.java
new file mode 100644
index 0000000..b0ccf9d
--- /dev/null
+++ b/tests/RenderScriptTests/tests/src/com/android/rs/test/UT_sampler.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.rs.test;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.renderscript.*;
+import android.renderscript.Sampler;
+import android.renderscript.Sampler.Value;
+
+public class UT_sampler extends UnitTest {
+    private Resources mRes;
+
+    protected UT_sampler(RSTestCore rstc, Resources res, Context ctx) {
+        super(rstc, "Sampler", ctx);
+        mRes = res;
+    }
+
+    private Sampler.Builder getDefaultBuilder(RenderScript RS) {
+        Sampler.Builder b = new Sampler.Builder(RS);
+        b.setMinification(Value.NEAREST);
+        b.setMagnification(Value.NEAREST);
+        b.setWrapS(Value.CLAMP);
+        b.setWrapT(Value.CLAMP);
+        b.setAnisotropy(1.0f);
+        return b;
+    }
+
+    private void initializeGlobals(RenderScript RS, ScriptC_sampler s) {
+        Sampler.Builder b = getDefaultBuilder(RS);
+        b.setMinification(Value.LINEAR_MIP_LINEAR);
+        s.set_minification(b.create());
+
+        b = getDefaultBuilder(RS);
+        b.setMagnification(Value.LINEAR);
+        s.set_magnification(b.create());
+
+        b = getDefaultBuilder(RS);
+        b.setWrapS(Value.WRAP);
+        s.set_wrapS(b.create());
+
+        b = getDefaultBuilder(RS);
+        b.setWrapT(Value.WRAP);
+        s.set_wrapT(b.create());
+
+        b = getDefaultBuilder(RS);
+        b.setAnisotropy(8.0f);
+        s.set_anisotropy(b.create());
+        return;
+    }
+
+    public void run() {
+        RenderScript pRS = RenderScript.create(mCtx);
+        ScriptC_sampler s = new ScriptC_sampler(pRS, mRes, R.raw.sampler);
+        pRS.setMessageHandler(mRsMessage);
+        initializeGlobals(pRS, s);
+        s.invoke_sampler_test();
+        pRS.finish();
+        waitForMessage();
+        pRS.destroy();
+    }
+}
diff --git a/tests/RenderScriptTests/tests/src/com/android/rs/test/program_raster.rs b/tests/RenderScriptTests/tests/src/com/android/rs/test/program_raster.rs
new file mode 100644
index 0000000..11b8c30
--- /dev/null
+++ b/tests/RenderScriptTests/tests/src/com/android/rs/test/program_raster.rs
@@ -0,0 +1,37 @@
+#include "shared.rsh"
+#include "rs_graphics.rsh"
+
+rs_program_raster pointSpriteEnabled;
+rs_program_raster cullMode;
+
+static bool test_program_raster_getters() {
+    bool failed = false;
+
+    _RS_ASSERT(rsgProgramRasterGetPointSpriteEnabled(pointSpriteEnabled) == true);
+    _RS_ASSERT(rsgProgramRasterGetCullMode(pointSpriteEnabled) == RS_CULL_BACK);
+
+    _RS_ASSERT(rsgProgramRasterGetPointSpriteEnabled(cullMode) == false);
+    _RS_ASSERT(rsgProgramRasterGetCullMode(cullMode) == RS_CULL_FRONT);
+
+    if (failed) {
+        rsDebug("test_program_raster_getters FAILED", 0);
+    }
+    else {
+        rsDebug("test_program_raster_getters PASSED", 0);
+    }
+
+    return failed;
+}
+
+void program_raster_test() {
+    bool failed = false;
+    failed |= test_program_raster_getters();
+
+    if (failed) {
+        rsSendToClientBlocking(RS_MSG_TEST_FAILED);
+    }
+    else {
+        rsSendToClientBlocking(RS_MSG_TEST_PASSED);
+    }
+}
+
diff --git a/tests/RenderScriptTests/tests/src/com/android/rs/test/program_store.rs b/tests/RenderScriptTests/tests/src/com/android/rs/test/program_store.rs
new file mode 100644
index 0000000..3cd8a20
--- /dev/null
+++ b/tests/RenderScriptTests/tests/src/com/android/rs/test/program_store.rs
@@ -0,0 +1,128 @@
+#include "shared.rsh"
+#include "rs_graphics.rsh"
+
+rs_program_store ditherEnable;
+rs_program_store colorRWriteEnable;
+rs_program_store colorGWriteEnable;
+rs_program_store colorBWriteEnable;
+rs_program_store colorAWriteEnable;
+rs_program_store blendSrc;
+rs_program_store blendDst;
+rs_program_store depthWriteEnable;
+rs_program_store depthFunc;
+
+static bool test_program_store_getters() {
+    bool failed = false;
+
+    _RS_ASSERT(rsgProgramStoreGetDepthFunc(depthFunc) == RS_DEPTH_FUNC_GREATER);
+    _RS_ASSERT(rsgProgramStoreGetDepthMask(depthFunc) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskR(depthFunc) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskG(depthFunc) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskB(depthFunc) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskA(depthFunc) == false);
+    _RS_ASSERT(rsgProgramStoreGetDitherEnabled(depthFunc) == false);
+    _RS_ASSERT(rsgProgramStoreGetBlendSrcFunc(depthFunc) == RS_BLEND_SRC_ZERO);
+    _RS_ASSERT(rsgProgramStoreGetBlendDstFunc(depthFunc) == RS_BLEND_DST_ZERO);
+
+    _RS_ASSERT(rsgProgramStoreGetDepthFunc(depthWriteEnable) == RS_DEPTH_FUNC_ALWAYS);
+    _RS_ASSERT(rsgProgramStoreGetDepthMask(depthWriteEnable) == true);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskR(depthWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskG(depthWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskB(depthWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskA(depthWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetDitherEnabled(depthWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetBlendSrcFunc(depthWriteEnable) == RS_BLEND_SRC_ZERO);
+    _RS_ASSERT(rsgProgramStoreGetBlendDstFunc(depthWriteEnable) == RS_BLEND_DST_ZERO);
+
+    _RS_ASSERT(rsgProgramStoreGetDepthFunc(colorRWriteEnable) == RS_DEPTH_FUNC_ALWAYS);
+    _RS_ASSERT(rsgProgramStoreGetDepthMask(colorRWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskR(colorRWriteEnable) == true);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskG(colorRWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskB(colorRWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskA(colorRWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetDitherEnabled(colorRWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetBlendSrcFunc(colorRWriteEnable) == RS_BLEND_SRC_ZERO);
+    _RS_ASSERT(rsgProgramStoreGetBlendDstFunc(colorRWriteEnable) == RS_BLEND_DST_ZERO);
+
+    _RS_ASSERT(rsgProgramStoreGetDepthFunc(colorGWriteEnable) == RS_DEPTH_FUNC_ALWAYS);
+    _RS_ASSERT(rsgProgramStoreGetDepthMask(colorGWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskR(colorGWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskG(colorGWriteEnable) == true);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskB(colorGWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskA(colorGWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetDitherEnabled(colorGWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetBlendSrcFunc(colorGWriteEnable) == RS_BLEND_SRC_ZERO);
+    _RS_ASSERT(rsgProgramStoreGetBlendDstFunc(colorGWriteEnable) == RS_BLEND_DST_ZERO);
+
+    _RS_ASSERT(rsgProgramStoreGetDepthFunc(colorBWriteEnable) == RS_DEPTH_FUNC_ALWAYS);
+    _RS_ASSERT(rsgProgramStoreGetDepthMask(colorBWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskR(colorBWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskG(colorBWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskB(colorBWriteEnable) == true);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskA(colorBWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetDitherEnabled(colorBWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetBlendSrcFunc(colorBWriteEnable) == RS_BLEND_SRC_ZERO);
+    _RS_ASSERT(rsgProgramStoreGetBlendDstFunc(colorBWriteEnable) == RS_BLEND_DST_ZERO);
+
+    _RS_ASSERT(rsgProgramStoreGetDepthFunc(colorAWriteEnable) == RS_DEPTH_FUNC_ALWAYS);
+    _RS_ASSERT(rsgProgramStoreGetDepthMask(colorAWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskR(colorAWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskG(colorAWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskB(colorAWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskA(colorAWriteEnable) == true);
+    _RS_ASSERT(rsgProgramStoreGetDitherEnabled(colorAWriteEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetBlendSrcFunc(colorAWriteEnable) == RS_BLEND_SRC_ZERO);
+    _RS_ASSERT(rsgProgramStoreGetBlendDstFunc(colorAWriteEnable) == RS_BLEND_DST_ZERO);
+
+    _RS_ASSERT(rsgProgramStoreGetDepthFunc(ditherEnable) == RS_DEPTH_FUNC_ALWAYS);
+    _RS_ASSERT(rsgProgramStoreGetDepthMask(ditherEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskR(ditherEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskG(ditherEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskB(ditherEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskA(ditherEnable) == false);
+    _RS_ASSERT(rsgProgramStoreGetDitherEnabled(ditherEnable) == true);
+    _RS_ASSERT(rsgProgramStoreGetBlendSrcFunc(ditherEnable) == RS_BLEND_SRC_ZERO);
+    _RS_ASSERT(rsgProgramStoreGetBlendDstFunc(ditherEnable) == RS_BLEND_DST_ZERO);
+
+    _RS_ASSERT(rsgProgramStoreGetDepthFunc(blendSrc) == RS_DEPTH_FUNC_ALWAYS);
+    _RS_ASSERT(rsgProgramStoreGetDepthMask(blendSrc) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskR(blendSrc) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskG(blendSrc) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskB(blendSrc) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskA(blendSrc) == false);
+    _RS_ASSERT(rsgProgramStoreGetDitherEnabled(blendSrc) == false);
+    _RS_ASSERT(rsgProgramStoreGetBlendSrcFunc(blendSrc) == RS_BLEND_SRC_DST_COLOR);
+    _RS_ASSERT(rsgProgramStoreGetBlendDstFunc(blendSrc) == RS_BLEND_DST_ZERO);
+
+    _RS_ASSERT(rsgProgramStoreGetDepthFunc(blendDst) == RS_DEPTH_FUNC_ALWAYS);
+    _RS_ASSERT(rsgProgramStoreGetDepthMask(blendDst) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskR(blendDst) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskG(blendDst) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskB(blendDst) == false);
+    _RS_ASSERT(rsgProgramStoreGetColorMaskA(blendDst) == false);
+    _RS_ASSERT(rsgProgramStoreGetDitherEnabled(blendDst) == false);
+    _RS_ASSERT(rsgProgramStoreGetBlendSrcFunc(blendDst) == RS_BLEND_SRC_ZERO);
+    _RS_ASSERT(rsgProgramStoreGetBlendDstFunc(blendDst) == RS_BLEND_DST_DST_ALPHA);
+
+    if (failed) {
+        rsDebug("test_program_store_getters FAILED", 0);
+    }
+    else {
+        rsDebug("test_program_store_getters PASSED", 0);
+    }
+
+    return failed;
+}
+
+void program_store_test() {
+    bool failed = false;
+    failed |= test_program_store_getters();
+
+    if (failed) {
+        rsSendToClientBlocking(RS_MSG_TEST_FAILED);
+    }
+    else {
+        rsSendToClientBlocking(RS_MSG_TEST_PASSED);
+    }
+}
+
diff --git a/tests/RenderScriptTests/tests/src/com/android/rs/test/sampler.rs b/tests/RenderScriptTests/tests/src/com/android/rs/test/sampler.rs
new file mode 100644
index 0000000..ac9a549
--- /dev/null
+++ b/tests/RenderScriptTests/tests/src/com/android/rs/test/sampler.rs
@@ -0,0 +1,63 @@
+#include "shared.rsh"
+#include "rs_graphics.rsh"
+rs_sampler minification;
+rs_sampler magnification;
+rs_sampler wrapS;
+rs_sampler wrapT;
+rs_sampler anisotropy;
+
+static bool test_sampler_getters() {
+    bool failed = false;
+
+    _RS_ASSERT(rsgSamplerGetMagnification(minification) == RS_SAMPLER_NEAREST);
+    _RS_ASSERT(rsgSamplerGetMinification(minification) == RS_SAMPLER_LINEAR_MIP_LINEAR);
+    _RS_ASSERT(rsgSamplerGetWrapS(minification) == RS_SAMPLER_CLAMP);
+    _RS_ASSERT(rsgSamplerGetWrapT(minification) == RS_SAMPLER_CLAMP);
+    _RS_ASSERT(rsgSamplerGetAnisotropy(minification) == 1.0f);
+
+    _RS_ASSERT(rsgSamplerGetMagnification(magnification) == RS_SAMPLER_LINEAR);
+    _RS_ASSERT(rsgSamplerGetMinification(magnification) == RS_SAMPLER_NEAREST);
+    _RS_ASSERT(rsgSamplerGetWrapS(magnification) == RS_SAMPLER_CLAMP);
+    _RS_ASSERT(rsgSamplerGetWrapT(magnification) == RS_SAMPLER_CLAMP);
+    _RS_ASSERT(rsgSamplerGetAnisotropy(magnification) == 1.0f);
+
+    _RS_ASSERT(rsgSamplerGetMagnification(wrapS) == RS_SAMPLER_NEAREST);
+    _RS_ASSERT(rsgSamplerGetMinification(wrapS) == RS_SAMPLER_NEAREST);
+    _RS_ASSERT(rsgSamplerGetWrapS(wrapS) == RS_SAMPLER_WRAP);
+    _RS_ASSERT(rsgSamplerGetWrapT(wrapS) == RS_SAMPLER_CLAMP);
+    _RS_ASSERT(rsgSamplerGetAnisotropy(wrapS) == 1.0f);
+
+    _RS_ASSERT(rsgSamplerGetMagnification(wrapT) == RS_SAMPLER_NEAREST);
+    _RS_ASSERT(rsgSamplerGetMinification(wrapT) == RS_SAMPLER_NEAREST);
+    _RS_ASSERT(rsgSamplerGetWrapS(wrapT) == RS_SAMPLER_CLAMP);
+    _RS_ASSERT(rsgSamplerGetWrapT(wrapT) == RS_SAMPLER_WRAP);
+    _RS_ASSERT(rsgSamplerGetAnisotropy(wrapT) == 1.0f);
+
+    _RS_ASSERT(rsgSamplerGetMagnification(anisotropy) == RS_SAMPLER_NEAREST);
+    _RS_ASSERT(rsgSamplerGetMinification(anisotropy) == RS_SAMPLER_NEAREST);
+    _RS_ASSERT(rsgSamplerGetWrapS(anisotropy) == RS_SAMPLER_CLAMP);
+    _RS_ASSERT(rsgSamplerGetWrapT(anisotropy) == RS_SAMPLER_CLAMP);
+    _RS_ASSERT(rsgSamplerGetAnisotropy(anisotropy) == 8.0f);
+
+    if (failed) {
+        rsDebug("test_sampler_getters FAILED", 0);
+    }
+    else {
+        rsDebug("test_sampler_getters PASSED", 0);
+    }
+
+    return failed;
+}
+
+void sampler_test() {
+    bool failed = false;
+    failed |= test_sampler_getters();
+
+    if (failed) {
+        rsSendToClientBlocking(RS_MSG_TEST_FAILED);
+    }
+    else {
+        rsSendToClientBlocking(RS_MSG_TEST_PASSED);
+    }
+}
+
diff --git a/tests/StatusBar/src/com/android/statusbartest/StatusBarTest.java b/tests/StatusBar/src/com/android/statusbartest/StatusBarTest.java
index 7c94c2d..94ad620 100644
--- a/tests/StatusBar/src/com/android/statusbartest/StatusBarTest.java
+++ b/tests/StatusBar/src/com/android/statusbartest/StatusBarTest.java
@@ -114,9 +114,9 @@
 //                v.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
 //            }
 //        },
-        new Test("systemUiVisibility: STATUS_BAR_DISABLE_NAVIGATION") {
+        new Test("systemUiVisibility: STATUS_BAR_DISABLE_HOME") {
             public void run() {
-                mListView.setSystemUiVisibility(View.STATUS_BAR_DISABLE_NAVIGATION);
+                mListView.setSystemUiVisibility(View.STATUS_BAR_DISABLE_HOME);
             }
         },
         new Test("Double Remove") {
@@ -227,16 +227,21 @@
                     }, 3000);
             }
         },
-        new Test("Disable Navigation") {
+        new Test("Disable Home (StatusBarManager)") {
             public void run() {
-                mStatusBarManager.disable(StatusBarManager.DISABLE_NAVIGATION);
+                mStatusBarManager.disable(StatusBarManager.DISABLE_HOME);
             }
         },
-        new Test("Disable Back") {
+        new Test("Disable Back (StatusBarManager)") {
             public void run() {
                 mStatusBarManager.disable(StatusBarManager.DISABLE_BACK);
             }
         },
+        new Test("Disable Recent (StatusBarManager)") {
+            public void run() {
+                mStatusBarManager.disable(StatusBarManager.DISABLE_RECENT);
+            }
+        },
         new Test("Disable Clock") {
             public void run() {
                 mStatusBarManager.disable(StatusBarManager.DISABLE_CLOCK);
diff --git a/tools/aapt/AaptAssets.cpp b/tools/aapt/AaptAssets.cpp
index d66cdf0..3d6537a 100644
--- a/tools/aapt/AaptAssets.cpp
+++ b/tools/aapt/AaptAssets.cpp
@@ -3,6 +3,7 @@
 //
 
 #include "AaptAssets.h"
+#include "ResourceFilter.h"
 #include "Main.h"
 
 #include <utils/misc.h>
@@ -16,6 +17,8 @@
 static const char* kWildcardName = "any";
 static const char* kAssetDir = "assets";
 static const char* kResourceDir = "res";
+static const char* kValuesDir = "values";
+static const char* kMipmapDir = "mipmap";
 static const char* kInvalidChars = "/\\:";
 static const size_t kMaxAssetFileName = 100;
 
@@ -257,9 +260,69 @@
     return 1;
 }
 
+uint32_t
+AaptGroupEntry::getConfigValueForAxis(const ResTable_config& config, int axis)
+{
+    switch (axis) {
+        case AXIS_MCC:
+            return config.mcc;
+        case AXIS_MNC:
+            return config.mnc;
+        case AXIS_LANGUAGE:
+            return (((uint32_t)config.country[1]) << 24) | (((uint32_t)config.country[0]) << 16)
+                | (((uint32_t)config.language[1]) << 8) | (config.language[0]);
+        case AXIS_SCREENLAYOUTSIZE:
+            return config.screenLayout&ResTable_config::MASK_SCREENSIZE;
+        case AXIS_ORIENTATION:
+            return config.orientation;
+        case AXIS_UIMODETYPE:
+            return (config.uiMode&ResTable_config::MASK_UI_MODE_TYPE);
+        case AXIS_UIMODENIGHT:
+            return (config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT);
+        case AXIS_DENSITY:
+            return config.density;
+        case AXIS_TOUCHSCREEN:
+            return config.touchscreen;
+        case AXIS_KEYSHIDDEN:
+            return config.inputFlags;
+        case AXIS_KEYBOARD:
+            return config.keyboard;
+        case AXIS_NAVIGATION:
+            return config.navigation;
+        case AXIS_SCREENSIZE:
+            return config.screenSize;
+        case AXIS_SMALLESTSCREENWIDTHDP:
+            return config.smallestScreenWidthDp;
+        case AXIS_SCREENWIDTHDP:
+            return config.screenWidthDp;
+        case AXIS_SCREENHEIGHTDP:
+            return config.screenHeightDp;
+        case AXIS_VERSION:
+            return config.version;
+    }
+    return 0;
+}
+
+bool
+AaptGroupEntry::configSameExcept(const ResTable_config& config,
+        const ResTable_config& otherConfig, int axis)
+{
+    for (int i=AXIS_START; i<=AXIS_END; i++) {
+        if (i == axis) {
+            continue;
+        }
+        if (getConfigValueForAxis(config, i) != getConfigValueForAxis(otherConfig, i)) {
+            return false;
+        }
+    }
+    return true;
+}
+
 bool
 AaptGroupEntry::initFromDirName(const char* dir, String8* resType)
 {
+    mParamsChanged = true;
+
     Vector<String8> parts;
 
     String8 mcc, mnc, loc, layoutsize, layoutlong, orient, den;
@@ -629,79 +692,117 @@
 {
     String8 s = resType;
     if (this->mcc != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += mcc;
     }
     if (this->mnc != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += mnc;
     }
     if (this->locale != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += locale;
     }
     if (this->smallestScreenWidthDp != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += smallestScreenWidthDp;
     }
     if (this->screenWidthDp != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += screenWidthDp;
     }
     if (this->screenHeightDp != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += screenHeightDp;
     }
     if (this->screenLayoutSize != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += screenLayoutSize;
     }
     if (this->screenLayoutLong != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += screenLayoutLong;
     }
     if (this->orientation != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += orientation;
     }
     if (this->uiModeType != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += uiModeType;
     }
     if (this->uiModeNight != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += uiModeNight;
     }
     if (this->density != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += density;
     }
     if (this->touchscreen != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += touchscreen;
     }
     if (this->keysHidden != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += keysHidden;
     }
     if (this->keyboard != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += keyboard;
     }
     if (this->navHidden != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += navHidden;
     }
     if (this->navigation != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += navigation;
     }
     if (this->screenSize != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += screenSize;
     }
     if (this->version != "") {
-        s += "-";
+        if (s.length() > 0) {
+            s += "-";
+        }
         s += version;
     }
 
@@ -1286,9 +1387,14 @@
     return v;
 }
 
-ResTable_config AaptGroupEntry::toParams() const
+const ResTable_config& AaptGroupEntry::toParams() const
 {
-    ResTable_config params;
+    if (!mParamsChanged) {
+        return mParams;
+    }
+
+    mParamsChanged = false;
+    ResTable_config& params(mParams);
     memset(&params, 0, sizeof(params));
     getMccName(mcc.string(), &params);
     getMncName(mnc.string(), &params);
@@ -1403,8 +1509,7 @@
 String8 AaptFile::getPrintableSource() const
 {
     if (hasData()) {
-        String8 name(mGroupEntry.locale.string());
-        name.appendPath(mGroupEntry.vendor.string());
+        String8 name(mGroupEntry.toDirName(String8()));
         name.appendPath(mPath);
         name.append(" #generated");
         return name;
@@ -1424,6 +1529,13 @@
         return NO_ERROR;
     }
 
+#if 0
+    printf("Error adding file %s: group %s already exists in leaf=%s path=%s\n",
+            file->getSourceFile().string(),
+            file->getGroupEntry().toDirName(String8()).string(),
+            mLeaf.string(), mPath.string());
+#endif
+
     SourcePos(file->getSourceFile(), -1).error("Duplicate file.\n%s: Original is here.",
                                                getPrintableSource().string());
     return UNKNOWN_ERROR;
@@ -1434,20 +1546,23 @@
 	mFiles.removeItemsAt(index);
 }
 
-void AaptGroup::print() const
+void AaptGroup::print(const String8& prefix) const
 {
-    printf("  %s\n", getPath().string());
+    printf("%s%s\n", prefix.string(), getPath().string());
     const size_t N=mFiles.size();
     size_t i;
     for (i=0; i<N; i++) {
         sp<AaptFile> file = mFiles.valueAt(i);
         const AaptGroupEntry& e = file->getGroupEntry();
         if (file->hasData()) {
-            printf("      Gen: (%s) %d bytes\n", e.toString().string(),
+            printf("%s  Gen: (%s) %d bytes\n", prefix.string(), e.toDirName(String8()).string(),
                     (int)file->getSize());
         } else {
-            printf("      Src: %s\n", file->getPrintableSource().string());
+            printf("%s  Src: (%s) %s\n", prefix.string(), e.toDirName(String8()).string(),
+                    file->getPrintableSource().string());
         }
+        //printf("%s  File Group Entry: %s\n", prefix.string(),
+        //        file->getGroupEntry().toDirName(String8()).string());
     }
 }
 
@@ -1514,38 +1629,6 @@
     mDirs.removeItem(name);
 }
 
-status_t AaptDir::renameFile(const sp<AaptFile>& file, const String8& newName)
-{
-	sp<AaptGroup> origGroup;
-
-	// Find and remove the given file with shear, brute force!
-	const size_t NG = mFiles.size();
-	size_t i;
-	for (i=0; origGroup == NULL && i<NG; i++) {
-		sp<AaptGroup> g = mFiles.valueAt(i);
-		const size_t NF = g->getFiles().size();
-		for (size_t j=0; j<NF; j++) {
-			if (g->getFiles().valueAt(j) == file) {
-				origGroup = g;
-				g->removeFile(j);
-				if (NF == 1) {
-					mFiles.removeItemsAt(i);
-				}
-				break;
-			}
-		}
-	}
-
-	//printf("Renaming %s to %s\n", file->getPath().getPathName(), newName.string());
-
-	// Place the file under its new name.
-	if (origGroup != NULL) {
-		return addLeafFile(newName, file);
-	}
-
-	return NO_ERROR;
-}
-
 status_t AaptDir::addLeafFile(const String8& leafName, const sp<AaptFile>& file)
 {
     sp<AaptGroup> group;
@@ -1710,17 +1793,17 @@
     return NO_ERROR;
 }
 
-void AaptDir::print() const
+void AaptDir::print(const String8& prefix) const
 {
     const size_t ND=getDirs().size();
     size_t i;
     for (i=0; i<ND; i++) {
-        getDirs().valueAt(i)->print();
+        getDirs().valueAt(i)->print(prefix);
     }
 
     const size_t NF=getFiles().size();
     for (i=0; i<NF; i++) {
-        getFiles().valueAt(i)->print();
+        getFiles().valueAt(i)->print(prefix);
     }
 }
 
@@ -1744,6 +1827,24 @@
 // =========================================================================
 // =========================================================================
 
+AaptAssets::AaptAssets()
+    : AaptDir(String8(), String8()),
+      mChanged(false), mHaveIncludedAssets(false), mRes(NULL)
+{
+}
+
+const SortedVector<AaptGroupEntry>& AaptAssets::getGroupEntries() const {
+    if (mChanged) {
+    }
+    return mGroupEntries;
+}
+
+status_t AaptAssets::addFile(const String8& name, const sp<AaptGroup>& file)
+{
+    mChanged = true;
+    return AaptDir::addFile(name, file);
+}
+
 sp<AaptFile> AaptAssets::addFile(
         const String8& filePath, const AaptGroupEntry& entry,
         const String8& srcDir, sp<AaptGroup>* outGroup,
@@ -1945,6 +2046,11 @@
         goto bail;
     }
 
+    count = filter(bundle);
+    if (count != NO_ERROR) {
+        totalCount = count;
+        goto bail;
+    }
 
 bail:
     return totalCount;
@@ -2002,9 +2108,9 @@
             continue;
         }
 
-        if (bundle->getMaxResVersion() != NULL && group.version.length() != 0) {
+        if (bundle->getMaxResVersion() != NULL && group.getVersionString().length() != 0) {
             int maxResInt = atoi(bundle->getMaxResVersion());
-            const char *verString = group.version.string();
+            const char *verString = group.getVersionString().string();
             int dirVersionInt = atoi(verString + 1); // skip 'v' in version name
             if (dirVersionInt > maxResInt) {
               fprintf(stderr, "max res %d, skipping %s\n", maxResInt, entry->d_name);
@@ -2015,7 +2121,7 @@
         FileType type = getFileType(subdirName.string());
 
         if (type == kFileTypeDirectory) {
-            sp<AaptDir> dir = makeDir(String8(entry->d_name));
+            sp<AaptDir> dir = makeDir(resType);
             ssize_t res = dir->slurpFullTree(bundle, subdirName, group,
                                                 resType, mFullResPaths);
             if (res < 0) {
@@ -2027,7 +2133,13 @@
                 count += res;
             }
 
-            mDirs.add(dir);
+            // Only add this directory if we don't already have a resource dir
+            // for the current type.  This ensures that we only add the dir once
+            // for all configs.
+            sp<AaptDir> rdir = resDir(resType);
+            if (rdir == NULL) {
+                mResDirs.add(dir);
+            }
         } else {
             if (bundle->getVerbose()) {
                 fprintf(stderr, "   (ignoring file '%s')\n", subdirName.string());
@@ -2136,6 +2248,142 @@
     return count;
 }
 
+status_t AaptAssets::filter(Bundle* bundle)
+{
+    ResourceFilter reqFilter;
+    status_t err = reqFilter.parse(bundle->getConfigurations());
+    if (err != NO_ERROR) {
+        return err;
+    }
+
+    ResourceFilter prefFilter;
+    err = prefFilter.parse(bundle->getPreferredConfigurations());
+    if (err != NO_ERROR) {
+        return err;
+    }
+
+    if (reqFilter.isEmpty() && prefFilter.isEmpty()) {
+        return NO_ERROR;
+    }
+
+    if (bundle->getVerbose()) {
+        if (!reqFilter.isEmpty()) {
+            printf("Applying required filter: %s\n",
+                    bundle->getConfigurations());
+        }
+        if (!prefFilter.isEmpty()) {
+            printf("Applying preferred filter: %s\n",
+                    bundle->getPreferredConfigurations());
+        }
+    }
+
+    const Vector<sp<AaptDir> >& resdirs = mResDirs;
+    const size_t ND = resdirs.size();
+    for (size_t i=0; i<ND; i++) {
+        const sp<AaptDir>& dir = resdirs.itemAt(i);
+        if (dir->getLeaf() == kValuesDir) {
+            // The "value" dir is special since a single file defines
+            // multiple resources, so we can not do filtering on the
+            // files themselves.
+            continue;
+        }
+        if (dir->getLeaf() == kMipmapDir) {
+            // We also skip the "mipmap" directory, since the point of this
+            // is to include all densities without stripping.  If you put
+            // other configurations in here as well they won't be stripped
+            // either...  So don't do that.  Seriously.  What is wrong with you?
+            continue;
+        }
+
+        const size_t NG = dir->getFiles().size();
+        for (size_t j=0; j<NG; j++) {
+            sp<AaptGroup> grp = dir->getFiles().valueAt(j);
+
+            // First remove any configurations we know we don't need.
+            for (size_t k=0; k<grp->getFiles().size(); k++) {
+                sp<AaptFile> file = grp->getFiles().valueAt(k);
+                if (k == 0 && grp->getFiles().size() == 1) {
+                    // If this is the only file left, we need to keep it.
+                    // Otherwise the resource IDs we are using will be inconsistent
+                    // with what we get when not stripping.  Sucky, but at least
+                    // for now we can rely on the back-end doing another filtering
+                    // pass to take this out and leave us with this resource name
+                    // containing no entries.
+                    continue;
+                }
+                if (file->getPath().getPathExtension() == ".xml") {
+                    // We can't remove .xml files at this point, because when
+                    // we parse them they may add identifier resources, so
+                    // removing them can cause our resource identifiers to
+                    // become inconsistent.
+                    continue;
+                }
+                const ResTable_config& config(file->getGroupEntry().toParams());
+                if (!reqFilter.match(config)) {
+                    if (bundle->getVerbose()) {
+                        printf("Pruning unneeded resource: %s\n",
+                                file->getPrintableSource().string());
+                    }
+                    grp->removeFile(k);
+                    k--;
+                }
+            }
+
+            // Quick check: no preferred filters, nothing more to do.
+            if (prefFilter.isEmpty()) {
+                continue;
+            }
+
+            // Now deal with preferred configurations.
+            for (int axis=AXIS_START; axis<=AXIS_END; axis++) {
+                for (size_t k=0; k<grp->getFiles().size(); k++) {
+                    sp<AaptFile> file = grp->getFiles().valueAt(k);
+                    if (k == 0 && grp->getFiles().size() == 1) {
+                        // If this is the only file left, we need to keep it.
+                        // Otherwise the resource IDs we are using will be inconsistent
+                        // with what we get when not stripping.  Sucky, but at least
+                        // for now we can rely on the back-end doing another filtering
+                        // pass to take this out and leave us with this resource name
+                        // containing no entries.
+                        continue;
+                    }
+                    if (file->getPath().getPathExtension() == ".xml") {
+                        // We can't remove .xml files at this point, because when
+                        // we parse them they may add identifier resources, so
+                        // removing them can cause our resource identifiers to
+                        // become inconsistent.
+                        continue;
+                    }
+                    const ResTable_config& config(file->getGroupEntry().toParams());
+                    if (!prefFilter.match(axis, config)) {
+                        // This is a resource we would prefer not to have.  Check
+                        // to see if have a similar variation that we would like
+                        // to have and, if so, we can drop it.
+                        for (size_t m=0; m<grp->getFiles().size(); m++) {
+                            if (m == k) continue;
+                            sp<AaptFile> mfile = grp->getFiles().valueAt(m);
+                            const ResTable_config& mconfig(mfile->getGroupEntry().toParams());
+                            if (AaptGroupEntry::configSameExcept(config, mconfig, axis)) {
+                                if (prefFilter.match(axis, mconfig)) {
+                                    if (bundle->getVerbose()) {
+                                        printf("Pruning unneeded resource: %s\n",
+                                                file->getPrintableSource().string());
+                                    }
+                                    grp->removeFile(k);
+                                    k--;
+                                    break;
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    return NO_ERROR;
+}
+
 sp<AaptSymbols> AaptAssets::getSymbolsFor(const String8& name)
 {
     sp<AaptSymbols> sym = mSymbols.valueFor(name);
@@ -2179,26 +2427,39 @@
     return mIncludedAssets.getResources(false);
 }
 
-void AaptAssets::print() const
+void AaptAssets::print(const String8& prefix) const
 {
-    printf("Locale/Vendor pairs:\n");
+    String8 innerPrefix(prefix);
+    innerPrefix.append("  ");
+    String8 innerInnerPrefix(innerPrefix);
+    innerInnerPrefix.append("  ");
+    printf("%sConfigurations:\n", prefix.string());
     const size_t N=mGroupEntries.size();
     for (size_t i=0; i<N; i++) {
-        printf("   %s/%s\n",
-               mGroupEntries.itemAt(i).locale.string(),
-               mGroupEntries.itemAt(i).vendor.string());
+        String8 cname = mGroupEntries.itemAt(i).toDirName(String8());
+        printf("%s %s\n", prefix.string(),
+                cname != "" ? cname.string() : "(default)");
     }
 
-    printf("\nFiles:\n");
-    AaptDir::print();
+    printf("\n%sFiles:\n", prefix.string());
+    AaptDir::print(innerPrefix);
+
+    printf("\n%sResource Dirs:\n", prefix.string());
+    const Vector<sp<AaptDir> >& resdirs = mResDirs;
+    const size_t NR = resdirs.size();
+    for (size_t i=0; i<NR; i++) {
+        const sp<AaptDir>& d = resdirs.itemAt(i);
+        printf("%s  Type %s\n", prefix.string(), d->getLeaf().string());
+        d->print(innerInnerPrefix);
+    }
 }
 
-sp<AaptDir> AaptAssets::resDir(const String8& name)
+sp<AaptDir> AaptAssets::resDir(const String8& name) const
 {
-    const Vector<sp<AaptDir> >& dirs = mDirs;
-    const size_t N = dirs.size();
+    const Vector<sp<AaptDir> >& resdirs = mResDirs;
+    const size_t N = resdirs.size();
     for (size_t i=0; i<N; i++) {
-        const sp<AaptDir>& d = dirs.itemAt(i);
+        const sp<AaptDir>& d = resdirs.itemAt(i);
         if (d->getLeaf() == name) {
             return d;
         }
diff --git a/tools/aapt/AaptAssets.h b/tools/aapt/AaptAssets.h
index 82dfd71..d5345b2 100644
--- a/tools/aapt/AaptAssets.h
+++ b/tools/aapt/AaptAssets.h
@@ -24,6 +24,8 @@
 
 bool valid_symbol_name(const String8& str);
 
+class AaptAssets;
+
 enum {
     AXIS_NONE = 0,
     AXIS_MCC = 1,
@@ -45,7 +47,10 @@
     AXIS_SMALLESTSCREENWIDTHDP,
     AXIS_SCREENWIDTHDP,
     AXIS_SCREENHEIGHTDP,
-    AXIS_VERSION
+    AXIS_VERSION,
+
+    AXIS_START = AXIS_MCC,
+    AXIS_END = AXIS_VERSION,
 };
 
 enum {
@@ -56,6 +61,7 @@
     SDK_MR1 = 7,
     SDK_FROYO = 8,
     SDK_HONEYCOMB_MR2 = 13,
+    SDK_ICE_CREAM_SANDWICH = 14,
 };
 
 /**
@@ -65,35 +71,19 @@
 struct AaptGroupEntry
 {
 public:
-    AaptGroupEntry() { }
+    AaptGroupEntry() : mParamsChanged(true) { }
     AaptGroupEntry(const String8& _locale, const String8& _vendor)
-        : locale(_locale), vendor(_vendor) { }
-
-    String8 mcc;
-    String8 mnc;
-    String8 locale;
-    String8 vendor;
-    String8 smallestScreenWidthDp;
-    String8 screenWidthDp;
-    String8 screenHeightDp;
-    String8 screenLayoutSize;
-    String8 screenLayoutLong;
-    String8 orientation;
-    String8 uiModeType;
-    String8 uiModeNight;
-    String8 density;
-    String8 touchscreen;
-    String8 keysHidden;
-    String8 keyboard;
-    String8 navHidden;
-    String8 navigation;
-    String8 screenSize;
-    String8 version;
+        : locale(_locale), vendor(_vendor), mParamsChanged(true) { }
 
     bool initFromDirName(const char* dir, String8* resType);
 
     static status_t parseNamePart(const String8& part, int* axis, uint32_t* value);
-    
+
+    static uint32_t getConfigValueForAxis(const ResTable_config& config, int axis);
+
+    static bool configSameExcept(const ResTable_config& config,
+            const ResTable_config& otherConfig, int axis);
+
     static bool getMccName(const char* name, ResTable_config* out = NULL);
     static bool getMncName(const char* name, ResTable_config* out = NULL);
     static bool getLocaleName(const char* name, ResTable_config* out = NULL);
@@ -116,7 +106,7 @@
 
     int compare(const AaptGroupEntry& o) const;
 
-    ResTable_config toParams() const;
+    const ResTable_config& toParams() const;
 
     inline bool operator<(const AaptGroupEntry& o) const { return compare(o) < 0; }
     inline bool operator<=(const AaptGroupEntry& o) const { return compare(o) <= 0; }
@@ -127,6 +117,33 @@
 
     String8 toString() const;
     String8 toDirName(const String8& resType) const;
+
+    const String8& getVersionString() const { return version; }
+
+private:
+    String8 mcc;
+    String8 mnc;
+    String8 locale;
+    String8 vendor;
+    String8 smallestScreenWidthDp;
+    String8 screenWidthDp;
+    String8 screenHeightDp;
+    String8 screenLayoutSize;
+    String8 screenLayoutLong;
+    String8 orientation;
+    String8 uiModeType;
+    String8 uiModeNight;
+    String8 density;
+    String8 touchscreen;
+    String8 keysHidden;
+    String8 keyboard;
+    String8 navHidden;
+    String8 navigation;
+    String8 screenSize;
+    String8 version;
+
+    mutable bool mParamsChanged;
+    mutable ResTable_config mParams;
 };
 
 inline int compare_type(const AaptGroupEntry& lhs, const AaptGroupEntry& rhs)
@@ -225,7 +242,7 @@
     status_t addFile(const sp<AaptFile>& file);
     void removeFile(size_t index);
 
-    void print() const;
+    void print(const String8& prefix) const;
 
     String8 getPrintableSource() const;
 
@@ -237,7 +254,7 @@
 };
 
 /**
- * A single directory of assets, which can contain for files and other
+ * A single directory of assets, which can contain files and other
  * sub-directories.
  */
 class AaptDir : public RefBase
@@ -254,25 +271,11 @@
     const DefaultKeyedVector<String8, sp<AaptGroup> >& getFiles() const { return mFiles; }
     const DefaultKeyedVector<String8, sp<AaptDir> >& getDirs() const { return mDirs; }
 
-    status_t addFile(const String8& name, const sp<AaptGroup>& file);
-    status_t addDir(const String8& name, const sp<AaptDir>& dir);
-
-    sp<AaptDir> makeDir(const String8& name);
+    virtual status_t addFile(const String8& name, const sp<AaptGroup>& file);
 
     void removeFile(const String8& name);
     void removeDir(const String8& name);
 
-    status_t renameFile(const sp<AaptFile>& file, const String8& newName);
-
-    status_t addLeafFile(const String8& leafName,
-                         const sp<AaptFile>& file);
-
-    virtual ssize_t slurpFullTree(Bundle* bundle,
-                                  const String8& srcDir,
-                                  const AaptGroupEntry& kind,
-                                  const String8& resType,
-                                  sp<FilePathStore>& fullResPaths);
-
     /*
      * Perform some sanity checks on the names of files and directories here.
      * In particular:
@@ -292,11 +295,23 @@
      */
     status_t validate() const;
 
-    void print() const;
+    void print(const String8& prefix) const;
 
     String8 getPrintableSource() const;
 
 private:
+    friend class AaptAssets;
+
+    status_t addDir(const String8& name, const sp<AaptDir>& dir);
+    sp<AaptDir> makeDir(const String8& name);
+    status_t addLeafFile(const String8& leafName,
+                         const sp<AaptFile>& file);
+    virtual ssize_t slurpFullTree(Bundle* bundle,
+                                  const String8& srcDir,
+                                  const AaptGroupEntry& kind,
+                                  const String8& resType,
+                                  sp<FilePathStore>& fullResPaths);
+
     String8 mLeaf;
     String8 mPath;
 
@@ -501,13 +516,15 @@
 class AaptAssets : public AaptDir
 {
 public:
-    AaptAssets() : AaptDir(String8(), String8()), mHaveIncludedAssets(false), mRes(NULL) { }
+    AaptAssets();
     virtual ~AaptAssets() { delete mRes; }
 
     const String8& getPackage() const { return mPackage; }
     void setPackage(const String8& package) { mPackage = package; mSymbolsPrivatePackage = package; }
 
-    const SortedVector<AaptGroupEntry>& getGroupEntries() const { return mGroupEntries; }
+    const SortedVector<AaptGroupEntry>& getGroupEntries() const;
+
+    virtual status_t addFile(const String8& name, const sp<AaptGroup>& file);
 
     sp<AaptFile> addFile(const String8& filePath,
                          const AaptGroupEntry& entry,
@@ -524,15 +541,6 @@
     
     ssize_t slurpFromArgs(Bundle* bundle);
 
-    virtual ssize_t slurpFullTree(Bundle* bundle,
-                                  const String8& srcDir,
-                                  const AaptGroupEntry& kind,
-                                  const String8& resType,
-                                  sp<FilePathStore>& fullResPaths);
-
-    ssize_t slurpResourceTree(Bundle* bundle, const String8& srcDir);
-    ssize_t slurpResourceZip(Bundle* bundle, const char* filename);
-
     sp<AaptSymbols> getSymbolsFor(const String8& name);
 
     const DefaultKeyedVector<String8, sp<AaptSymbols> >& getSymbols() const { return mSymbols; }
@@ -544,10 +552,10 @@
     status_t addIncludedResources(const sp<AaptFile>& file);
     const ResTable& getIncludedResources() const;
 
-    void print() const;
+    void print(const String8& prefix) const;
 
-    inline const Vector<sp<AaptDir> >& resDirs() { return mDirs; }
-    sp<AaptDir> resDir(const String8& name);
+    inline const Vector<sp<AaptDir> >& resDirs() const { return mResDirs; }
+    sp<AaptDir> resDir(const String8& name) const;
 
     inline sp<AaptAssets> getOverlay() { return mOverlay; }
     inline void setOverlay(sp<AaptAssets>& overlay) { mOverlay = overlay; }
@@ -565,12 +573,25 @@
         setFullAssetPaths(sp<FilePathStore>& res) { mFullAssetPaths = res; }
 
 private:
+    virtual ssize_t slurpFullTree(Bundle* bundle,
+                                  const String8& srcDir,
+                                  const AaptGroupEntry& kind,
+                                  const String8& resType,
+                                  sp<FilePathStore>& fullResPaths);
+
+    ssize_t slurpResourceTree(Bundle* bundle, const String8& srcDir);
+    ssize_t slurpResourceZip(Bundle* bundle, const char* filename);
+
+    status_t filter(Bundle* bundle);
+
     String8 mPackage;
     SortedVector<AaptGroupEntry> mGroupEntries;
     DefaultKeyedVector<String8, sp<AaptSymbols> > mSymbols;
     String8 mSymbolsPrivatePackage;
 
-    Vector<sp<AaptDir> > mDirs;
+    Vector<sp<AaptDir> > mResDirs;
+
+    bool mChanged;
 
     bool mHaveIncludedAssets;
     AssetManager mIncludedAssets;
diff --git a/tools/aapt/Android.mk b/tools/aapt/Android.mk
index e507fb9..a3e5d9a 100644
--- a/tools/aapt/Android.mk
+++ b/tools/aapt/Android.mk
@@ -19,6 +19,7 @@
 	Package.cpp \
 	StringPool.cpp \
 	XMLNode.cpp \
+	ResourceFilter.cpp \
 	ResourceTable.cpp \
 	Images.cpp \
 	Resource.cpp \
diff --git a/tools/aapt/Bundle.h b/tools/aapt/Bundle.h
index 539c312..2d1060b 100644
--- a/tools/aapt/Bundle.h
+++ b/tools/aapt/Bundle.h
@@ -122,6 +122,8 @@
     void setRClassDir(const char* dir) { mRClassDir = dir; }
     const char* getConfigurations() const { return mConfigurations.size() > 0 ? mConfigurations.string() : NULL; }
     void addConfigurations(const char* val) { if (mConfigurations.size() > 0) { mConfigurations.append(","); mConfigurations.append(val); } else { mConfigurations = val; } }
+    const char* getPreferredConfigurations() const { return mPreferredConfigurations.size() > 0 ? mPreferredConfigurations.string() : NULL; }
+    void addPreferredConfigurations(const char* val) { if (mPreferredConfigurations.size() > 0) { mPreferredConfigurations.append(","); mPreferredConfigurations.append(val); } else { mPreferredConfigurations = val; } }
     const char* getResourceIntermediatesDir() const { return mResourceIntermediatesDir; }
     void setResourceIntermediatesDir(const char* dir) { mResourceIntermediatesDir = dir; }
     const android::Vector<const char*>& getPackageIncludes() const { return mPackageIncludes; }
@@ -244,6 +246,7 @@
     const char* mRClassDir;
     const char* mResourceIntermediatesDir;
     android::String8 mConfigurations;
+    android::String8 mPreferredConfigurations;
     android::Vector<const char*> mPackageIncludes;
     android::Vector<const char*> mJarFiles;
     android::Vector<const char*> mNoCompressExtensions;
diff --git a/tools/aapt/Command.cpp b/tools/aapt/Command.cpp
index 413a2dc..637c27d 100644
--- a/tools/aapt/Command.cpp
+++ b/tools/aapt/Command.cpp
@@ -5,6 +5,7 @@
 //
 #include "Main.h"
 #include "Bundle.h"
+#include "ResourceFilter.h"
 #include "ResourceTable.h"
 #include "XMLNode.h"
 
@@ -1572,7 +1573,7 @@
     }
 
     if (bundle->getVerbose()) {
-        assets->print();
+        assets->print(String8());
     }
 
     // If they asked for any fileAs that need to be compiled, do so.
diff --git a/tools/aapt/Images.cpp b/tools/aapt/Images.cpp
index 311ceea..ffbe875 100644
--- a/tools/aapt/Images.cpp
+++ b/tools/aapt/Images.cpp
@@ -980,6 +980,10 @@
 
     String8 printableName(file->getPrintableSource());
 
+    if (bundle->getVerbose()) {
+        printf("Processing image: %s\n", printableName.string());
+    }
+
     png_structp read_ptr = NULL;
     png_infop read_info = NULL;
     FILE* fp;
@@ -1094,6 +1098,10 @@
 
     status_t error = UNKNOWN_ERROR;
 
+    if (bundle->getVerbose()) {
+        printf("Processing image to cache: %s => %s\n", source.string(), dest.string());
+    }
+
     // Get a file handler to read from
     fp = fopen(source.string(),"rb");
     if (fp == NULL) {
diff --git a/tools/aapt/Main.cpp b/tools/aapt/Main.cpp
index 5135787..50c828d 100644
--- a/tools/aapt/Main.cpp
+++ b/tools/aapt/Main.cpp
@@ -65,9 +65,10 @@
         "        [--max-res-version VAL] \\\n"
         "        [-I base-package [-I base-package ...]] \\\n"
         "        [-A asset-source-dir]  [-G class-list-file] [-P public-definitions-file] \\\n"
-        "        [-S resource-sources [-S resource-sources ...]] "
+        "        [-S resource-sources [-S resource-sources ...]] \\\n"
         "        [-F apk-file] [-J R-file-dir] \\\n"
         "        [--product product1,product2,...] \\\n"
+        "        [-c CONFIGS] [--preferred-configurations CONFIGS] \\\n"
         "        [-o] \\\n"
         "        [raw-files-dir [raw-files-dir] ...]\n"
         "\n"
@@ -154,6 +155,10 @@
         "       generate dependency files in the same directories for R.java and resource package\n"
         "   --auto-add-overlay\n"
         "       Automatically add resources that are only in overlays.\n"
+        "   --preferred-configurations\n"
+        "       Like the -c option for filtering out unneeded configurations, but\n"
+        "       only expresses a preference.  If there is no resource available with\n"
+        "       the preferred configuration then it will not be stripped.\n"
         "   --rename-manifest-package\n"
         "       Rewrite the manifest so that its package name is the package name\n"
         "       given here.  Relative class names (for example .Foo) will be\n"
@@ -509,6 +514,15 @@
                     bundle.setGenDependencies(true);
                 } else if (strcmp(cp, "-utf16") == 0) {
                     bundle.setWantUTF16(true);
+                } else if (strcmp(cp, "-preferred-configurations") == 0) {
+                    argc--;
+                    argv++;
+                    if (!argc) {
+                        fprintf(stderr, "ERROR: No argument supplied for '--preferred-configurations' option\n");
+                        wantUsage = true;
+                        goto bail;
+                    }
+                    bundle.addPreferredConfigurations(argv[0]);
                 } else if (strcmp(cp, "-rename-manifest-package") == 0) {
                     argc--;
                     argv++;
diff --git a/tools/aapt/Package.cpp b/tools/aapt/Package.cpp
index 1e3efde..3930117 100644
--- a/tools/aapt/Package.cpp
+++ b/tools/aapt/Package.cpp
@@ -6,6 +6,7 @@
 #include "Main.h"
 #include "AaptAssets.h"
 #include "ResourceTable.h"
+#include "ResourceFilter.h"
 
 #include <utils/Log.h>
 #include <utils/threads.h>
diff --git a/tools/aapt/Resource.cpp b/tools/aapt/Resource.cpp
index 2e796a2..887fa74 100644
--- a/tools/aapt/Resource.cpp
+++ b/tools/aapt/Resource.cpp
@@ -352,18 +352,27 @@
 
         if (index < 0) {
             sp<ResourceTypeSet> set = new ResourceTypeSet();
+            NOISY(printf("Creating new resource type set for leaf %s with group %s (%p)\n",
+                    leafName.string(), group->getPath().string(), group.get()));
             set->add(leafName, group);
             resources->add(resType, set);
         } else {
             sp<ResourceTypeSet> set = resources->valueAt(index);
             index = set->indexOfKey(leafName);
             if (index < 0) {
+                NOISY(printf("Adding to resource type set for leaf %s group %s (%p)\n",
+                        leafName.string(), group->getPath().string(), group.get()));
                 set->add(leafName, group);
             } else {
                 sp<AaptGroup> existingGroup = set->valueAt(index);
-                int M = files.size();
-                for (int j=0; j<M; j++) {
-                    existingGroup->addFile(files.valueAt(j));
+                NOISY(printf("Extending to resource type set for leaf %s group %s (%p)\n",
+                        leafName.string(), group->getPath().string(), group.get()));
+                for (size_t j=0; j<files.size(); j++) {
+                    NOISY(printf("Adding file %s in group %s resType %s\n",
+                        files.valueAt(j)->getSourceFile().string(),
+                        files.keyAt(j).toDirName(String8()).string(),
+                        resType.string()));
+                    status_t err = existingGroup->addFile(files.valueAt(j));
                 }
             }
         }
@@ -378,9 +387,12 @@
 
     for (int i=0; i<N; i++) {
         sp<AaptDir> d = dirs.itemAt(i);
+        NOISY(printf("Collecting dir #%d %p: %s, leaf %s\n", i, d.get(), d->getPath().string(),
+                d->getLeaf().string()));
         collect_files(d, resources);
 
         // don't try to include the res dir
+        NOISY(printf("Removing dir leaf %s\n", d->getLeaf().string()));
         ass->removeDir(d->getLeaf());
     }
 }
@@ -570,7 +582,7 @@
                         size_t baseFileIndex =
                                 baseGroup->getFiles().indexOfKey(overlayFiles.
                                 keyAt(overlayGroupIndex));
-                        if(baseFileIndex < UNKNOWN_ERROR) {
+                        if (baseFileIndex < UNKNOWN_ERROR) {
                             if (bundle->getVerbose()) {
                                 printf("found a match (%zd) for overlay file %s, for flavor %s\n",
                                         baseFileIndex,
@@ -580,6 +592,11 @@
                             baseGroup->removeFile(baseFileIndex);
                         } else {
                             // didn't find a match fall through and add it..
+                            if (true || bundle->getVerbose()) {
+                                printf("nothing matches overlay file %s, for flavor %s\n",
+                                        overlayGroup->getLeaf().string(),
+                                        overlayFiles.keyAt(overlayGroupIndex).toString().string());
+                            }
                         }
                         baseGroup->addFile(overlayFiles.valueAt(overlayGroupIndex));
                         assets->addGroupEntry(overlayFiles.keyAt(overlayGroupIndex));
diff --git a/tools/aapt/ResourceFilter.cpp b/tools/aapt/ResourceFilter.cpp
new file mode 100644
index 0000000..8cfd2a5
--- /dev/null
+++ b/tools/aapt/ResourceFilter.cpp
@@ -0,0 +1,112 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+// Build resource files from raw assets.
+//
+
+#include "ResourceFilter.h"
+
+status_t
+ResourceFilter::parse(const char* arg)
+{
+    if (arg == NULL) {
+        return 0;
+    }
+
+    const char* p = arg;
+    const char* q;
+
+    while (true) {
+        q = strchr(p, ',');
+        if (q == NULL) {
+            q = p + strlen(p);
+        }
+
+        String8 part(p, q-p);
+
+        if (part == "zz_ZZ") {
+            mContainsPseudo = true;
+        }
+        int axis;
+        uint32_t value;
+        if (AaptGroupEntry::parseNamePart(part, &axis, &value)) {
+            fprintf(stderr, "Invalid configuration: %s\n", arg);
+            fprintf(stderr, "                       ");
+            for (int i=0; i<p-arg; i++) {
+                fprintf(stderr, " ");
+            }
+            for (int i=0; i<q-p; i++) {
+                fprintf(stderr, "^");
+            }
+            fprintf(stderr, "\n");
+            return 1;
+        }
+
+        ssize_t index = mData.indexOfKey(axis);
+        if (index < 0) {
+            mData.add(axis, SortedVector<uint32_t>());
+        }
+        SortedVector<uint32_t>& sv = mData.editValueFor(axis);
+        sv.add(value);
+        // if it's a locale with a region, also match an unmodified locale of the
+        // same language
+        if (axis == AXIS_LANGUAGE) {
+            if (value & 0xffff0000) {
+                sv.add(value & 0x0000ffff);
+            }
+        }
+        p = q;
+        if (!*p) break;
+        p++;
+    }
+
+    return NO_ERROR;
+}
+
+bool
+ResourceFilter::isEmpty() const
+{
+    return mData.size() == 0;
+}
+
+bool
+ResourceFilter::match(int axis, uint32_t value) const
+{
+    if (value == 0) {
+        // they didn't specify anything so take everything
+        return true;
+    }
+    ssize_t index = mData.indexOfKey(axis);
+    if (index < 0) {
+        // we didn't request anything on this axis so take everything
+        return true;
+    }
+    const SortedVector<uint32_t>& sv = mData.valueAt(index);
+    return sv.indexOf(value) >= 0;
+}
+
+bool
+ResourceFilter::match(int axis, const ResTable_config& config) const
+{
+    return match(axis, AaptGroupEntry::getConfigValueForAxis(config, axis));
+}
+
+bool
+ResourceFilter::match(const ResTable_config& config) const
+{
+    for (int i=AXIS_START; i<=AXIS_END; i++) {
+        if (!match(i, AaptGroupEntry::getConfigValueForAxis(config, i))) {
+            return false;
+        }
+    }
+    return true;
+}
+
+const SortedVector<uint32_t>* ResourceFilter::configsForAxis(int axis) const
+{
+    ssize_t index = mData.indexOfKey(axis);
+    if (index < 0) {
+        return NULL;
+    }
+    return &mData.valueAt(index);
+}
diff --git a/tools/aapt/ResourceFilter.h b/tools/aapt/ResourceFilter.h
new file mode 100644
index 0000000..647b7bb
--- /dev/null
+++ b/tools/aapt/ResourceFilter.h
@@ -0,0 +1,33 @@
+//
+// Copyright 2011 The Android Open Source Project
+//
+// Build resource files from raw assets.
+//
+
+#ifndef RESOURCE_FILTER_H
+#define RESOURCE_FILTER_H
+
+#include "AaptAssets.h"
+
+/**
+ * Implements logic for parsing and handling "-c" and "--preferred-configurations"
+ * options.
+ */
+class ResourceFilter
+{
+public:
+    ResourceFilter() : mData(), mContainsPseudo(false) {}
+    status_t parse(const char* arg);
+    bool isEmpty() const;
+    bool match(int axis, uint32_t value) const;
+    bool match(int axis, const ResTable_config& config) const;
+    bool match(const ResTable_config& config) const;
+    const SortedVector<uint32_t>* configsForAxis(int axis) const;
+    inline bool containsPseudo() const { return mContainsPseudo; }
+
+private:
+    KeyedVector<int,SortedVector<uint32_t> > mData;
+    bool mContainsPseudo;
+};
+
+#endif
diff --git a/tools/aapt/ResourceTable.cpp b/tools/aapt/ResourceTable.cpp
index 99f74c6..fdb39ca 100644
--- a/tools/aapt/ResourceTable.cpp
+++ b/tools/aapt/ResourceTable.cpp
@@ -7,6 +7,7 @@
 #include "ResourceTable.h"
 
 #include "XMLNode.h"
+#include "ResourceFilter.h"
 
 #include <utils/ByteOrder.h>
 #include <utils/ResourceTypes.h>
@@ -2528,135 +2529,6 @@
     return err;
 }
 
-
-status_t
-ResourceFilter::parse(const char* arg)
-{
-    if (arg == NULL) {
-        return 0;
-    }
-
-    const char* p = arg;
-    const char* q;
-
-    while (true) {
-        q = strchr(p, ',');
-        if (q == NULL) {
-            q = p + strlen(p);
-        }
-
-        String8 part(p, q-p);
-
-        if (part == "zz_ZZ") {
-            mContainsPseudo = true;
-        }
-        int axis;
-        uint32_t value;
-        if (AaptGroupEntry::parseNamePart(part, &axis, &value)) {
-            fprintf(stderr, "Invalid configuration: %s\n", arg);
-            fprintf(stderr, "                       ");
-            for (int i=0; i<p-arg; i++) {
-                fprintf(stderr, " ");
-            }
-            for (int i=0; i<q-p; i++) {
-                fprintf(stderr, "^");
-            }
-            fprintf(stderr, "\n");
-            return 1;
-        }
-
-        ssize_t index = mData.indexOfKey(axis);
-        if (index < 0) {
-            mData.add(axis, SortedVector<uint32_t>());
-        }
-        SortedVector<uint32_t>& sv = mData.editValueFor(axis);
-        sv.add(value);
-        // if it's a locale with a region, also match an unmodified locale of the
-        // same language
-        if (axis == AXIS_LANGUAGE) {
-            if (value & 0xffff0000) {
-                sv.add(value & 0x0000ffff);
-            }
-        }
-        p = q;
-        if (!*p) break;
-        p++;
-    }
-
-    return NO_ERROR;
-}
-
-bool
-ResourceFilter::match(int axis, uint32_t value) const
-{
-    if (value == 0) {
-        // they didn't specify anything so take everything
-        return true;
-    }
-    ssize_t index = mData.indexOfKey(axis);
-    if (index < 0) {
-        // we didn't request anything on this axis so take everything
-        return true;
-    }
-    const SortedVector<uint32_t>& sv = mData.valueAt(index);
-    return sv.indexOf(value) >= 0;
-}
-
-bool
-ResourceFilter::match(const ResTable_config& config) const
-{
-    if (config.locale) {
-        uint32_t locale = (config.country[1] << 24) | (config.country[0] << 16)
-                | (config.language[1] << 8) | (config.language[0]);
-        if (!match(AXIS_LANGUAGE, locale)) {
-            return false;
-        }
-    }
-    if (!match(AXIS_ORIENTATION, config.orientation)) {
-        return false;
-    }
-    if (!match(AXIS_UIMODETYPE, (config.uiMode&ResTable_config::MASK_UI_MODE_TYPE))) {
-        return false;
-    }
-    if (!match(AXIS_UIMODENIGHT, (config.uiMode&ResTable_config::MASK_UI_MODE_NIGHT))) {
-        return false;
-    }
-    if (!match(AXIS_DENSITY, config.density)) {
-        return false;
-    }
-    if (!match(AXIS_TOUCHSCREEN, config.touchscreen)) {
-        return false;
-    }
-    if (!match(AXIS_KEYSHIDDEN, config.inputFlags)) {
-        return false;
-    }
-    if (!match(AXIS_KEYBOARD, config.keyboard)) {
-        return false;
-    }
-    if (!match(AXIS_NAVIGATION, config.navigation)) {
-        return false;
-    }
-    if (!match(AXIS_SCREENSIZE, config.screenSize)) {
-        return false;
-    }
-    if (!match(AXIS_SMALLESTSCREENWIDTHDP, config.smallestScreenWidthDp)) {
-        return false;
-    }
-    if (!match(AXIS_SCREENWIDTHDP, config.screenWidthDp)) {
-        return false;
-    }
-    if (!match(AXIS_SCREENHEIGHTDP, config.screenHeightDp)) {
-        return false;
-    }
-    if (!match(AXIS_SCREENLAYOUTSIZE, config.screenLayout&ResTable_config::MASK_SCREENSIZE)) {
-        return false;
-    }
-    if (!match(AXIS_VERSION, config.version)) {
-        return false;
-    }
-    return true;
-}
-
 status_t ResourceTable::flatten(Bundle* bundle, const sp<AaptFile>& dest)
 {
     ResourceFilter filter;
diff --git a/tools/aapt/ResourceTable.h b/tools/aapt/ResourceTable.h
index 80f2192..8123bb3 100644
--- a/tools/aapt/ResourceTable.h
+++ b/tools/aapt/ResourceTable.h
@@ -549,19 +549,4 @@
     map<String16, set<String8> > mLocalizations;
 };
 
-class ResourceFilter
-{
-public:
-    ResourceFilter() : mData(), mContainsPseudo(false) {}
-    status_t parse(const char* arg);
-    bool match(int axis, uint32_t value) const;
-    bool match(const ResTable_config& config) const;
-    inline bool containsPseudo() const { return mContainsPseudo; }
-
-private:
-    KeyedVector<int,SortedVector<uint32_t> > mData;
-    bool mContainsPseudo;
-};
-
-
 #endif