Merge "- Do not use global DrmManagerClient - Release the DrmManagerClient and DecryptHandle in DataSource Fix for bug 3429811"
diff --git a/Android.mk b/Android.mk
index 5c57044..c18b24b 100644
--- a/Android.mk
+++ b/Android.mk
@@ -369,7 +369,7 @@
     -since ./frameworks/base/api/8.xml 8 \
     -since ./frameworks/base/api/9.xml 9 \
     -since ./frameworks/base/api/10.xml 10 \
-    -since ./frameworks/base/api/current.xml Honeycomb \
+    -since ./frameworks/base/api/11.xml 11 \
 		-werror -hide 113 \
 		-overview $(LOCAL_PATH)/core/java/overview.html
 
@@ -402,8 +402,8 @@
                 resources/samples/CubeLiveWallpaper "Cube Live Wallpaper" \
 		-samplecode $(sample_dir)/Home \
 		            resources/samples/Home "Home" \
-                -samplecode $(sample_dir)/Honeycomb-Gallery \
-                            resources/samples/Honeycomb-Gallery "Honeycomb Gallery" \
+                -samplecode $(sample_dir)/HoneycombGallery \
+                            resources/samples/HoneycombGallery "Honeycomb Gallery" \
 		-samplecode $(sample_dir)/JetBoy \
 		            resources/samples/JetBoy "JetBoy" \
 		-samplecode $(sample_dir)/LunarLander \
@@ -445,12 +445,12 @@
   # major[.minor] version for current SDK. (full releases only)
 framework_docs_SDK_VERSION:=3.0
   # release version (ie "Release x")  (full releases only)
-framework_docs_SDK_REL_ID:=Preview
+framework_docs_SDK_REL_ID:=1
 
 framework_docs_LOCAL_DROIDDOC_OPTIONS += \
 		-hdf sdk.version $(framework_docs_SDK_VERSION) \
 		-hdf sdk.rel.id $(framework_docs_SDK_REL_ID) \
-		-hdf sdk.preview true \
+		-hdf sdk.preview 0 \
 
 # ====  the api stubs and current.xml ===========================
 include $(CLEAR_VARS)
diff --git a/api/current.xml b/api/current.xml
index 15463de..bd86302 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -204632,6 +204632,195 @@
 </parameter>
 </method>
 </class>
+<class name="LruCache"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="LruCache"
+ type="android.util.LruCache"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="maxSize" type="int">
+</parameter>
+</constructor>
+<method name="create"
+ return="V"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="protected"
+>
+<parameter name="key" type="K">
+</parameter>
+</method>
+<method name="createCount"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="entryEvicted"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="protected"
+>
+<parameter name="key" type="K">
+</parameter>
+<parameter name="value" type="V">
+</parameter>
+</method>
+<method name="evictAll"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="evictionCount"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="get"
+ return="V"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="key" type="K">
+</parameter>
+</method>
+<method name="hitCount"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="missCount"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="put"
+ return="V"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="key" type="K">
+</parameter>
+<parameter name="value" type="V">
+</parameter>
+</method>
+<method name="putCount"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="size"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="sizeOf"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="protected"
+>
+<parameter name="key" type="K">
+</parameter>
+<parameter name="value" type="V">
+</parameter>
+</method>
+<method name="snapshot"
+ return="java.util.Map&lt;K, V&gt;"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="toString"
+ return="java.lang.String"
+ abstract="false"
+ native="false"
+ synchronized="true"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+</class>
 <class name="MalformedJsonException"
  extends="java.io.IOException"
  abstract="false"
@@ -263805,7 +263994,7 @@
  deprecated="not deprecated"
  visibility="public"
 >
-<parameter name="t" type="T">
+<parameter name="arg0" type="T">
 </parameter>
 </method>
 </interface>
diff --git a/core/java/android/app/INotificationManager.aidl b/core/java/android/app/INotificationManager.aidl
index 4d5238c..2420b84 100644
--- a/core/java/android/app/INotificationManager.aidl
+++ b/core/java/android/app/INotificationManager.aidl
@@ -33,6 +33,7 @@
     void enqueueToast(String pkg, ITransientNotification callback, int duration);
     void cancelToast(String pkg, ITransientNotification callback);
     void enqueueNotificationWithTag(String pkg, String tag, int id, in Notification notification, inout int[] idReceived);
+    void enqueueNotificationWithTagPriority(String pkg, String tag, int id, int priority, in Notification notification, inout int[] idReceived);
     void cancelNotificationWithTag(String pkg, String tag, int id);
 }
 
diff --git a/core/java/android/content/AbstractThreadedSyncAdapter.java b/core/java/android/content/AbstractThreadedSyncAdapter.java
index 90d6472..fcc19a2 100644
--- a/core/java/android/content/AbstractThreadedSyncAdapter.java
+++ b/core/java/android/content/AbstractThreadedSyncAdapter.java
@@ -191,13 +191,12 @@
         public void run() {
             Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
 
-            if (isCanceled()) {
-                return;
-            }
-
             SyncResult syncResult = new SyncResult();
             ContentProviderClient provider = null;
             try {
+                if (isCanceled()) {
+                    return;
+                }
                 provider = mContext.getContentResolver().acquireContentProviderClient(mAuthority);
                 if (provider != null) {
                     AbstractThreadedSyncAdapter.this.onPerformSync(mAccount, mExtras,
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index e8292cc..7676258 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -3085,7 +3085,11 @@
         if (!sCompatibilityModeEnabled) {
             ai.disableCompatibilityMode();
         }
-        ai.enabled = p.mSetEnabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
+        if (p.mSetEnabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
+            ai.enabled = true;
+        } else if (p.mSetEnabled == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
+            ai.enabled = false;
+        }
         return ai;
     }
 
diff --git a/core/java/android/database/sqlite/SQLiteDatabase.java b/core/java/android/database/sqlite/SQLiteDatabase.java
index 8c5483f..965f7dc 100644
--- a/core/java/android/database/sqlite/SQLiteDatabase.java
+++ b/core/java/android/database/sqlite/SQLiteDatabase.java
@@ -48,6 +48,7 @@
 import java.util.Map;
 import java.util.Random;
 import java.util.WeakHashMap;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.ReentrantLock;
 import java.util.regex.Pattern;
 
@@ -198,7 +199,7 @@
     private boolean mTransactionUsingExecSql;
 
     /** Synchronize on this when accessing the database */
-    private final ReentrantLock mLock = new ReentrantLock(true);
+    private final DatabaseReentrantLock mLock = new DatabaseReentrantLock(true);
 
     private long mLockAcquiredWallTime = 0L;
     private long mLockAcquiredThreadTime = 0L;
@@ -414,6 +415,7 @@
     /* package */ void lock() {
         lock(false);
     }
+    private static final long LOCK_WAIT_PERIOD = 30L;
     private void lock(boolean forced) {
         // make sure this method is NOT being called from a 'synchronized' method
         if (Thread.holdsLock(this)) {
@@ -421,7 +423,22 @@
         }
         verifyDbIsOpen();
         if (!forced && !mLockingEnabled) return;
-        mLock.lock();
+        boolean done = false;
+        while (!done) {
+            try {
+                // wait for 30sec to acquire the lock
+                done = mLock.tryLock(LOCK_WAIT_PERIOD, TimeUnit.SECONDS);
+                if (!done) {
+                    // lock not acquired in NSec. print a message and stacktrace saying the lock
+                    // has not been available for 30sec.
+                    Log.w(TAG, "database lock has not been available for " + LOCK_WAIT_PERIOD +
+                            " sec. Current Owner of the lock is " + mLock.getOwnerDescription() +
+                            ". Continuing to wait");
+                }
+            } catch (InterruptedException e) {
+                // ignore the interruption
+            }
+        }
         if (SQLiteDebug.DEBUG_LOCK_TIME_TRACKING) {
             if (mLock.getHoldCount() == 1) {
                 // Use elapsed real-time since the CPU may sleep when waiting for IO
@@ -430,6 +447,20 @@
             }
         }
     }
+    private static class DatabaseReentrantLock extends ReentrantLock {
+        DatabaseReentrantLock(boolean fair) {
+            super(fair);
+        }
+        @Override
+        public Thread getOwner() {
+            return super.getOwner();
+        }
+        public String getOwnerDescription() {
+            Thread t = getOwner();
+            return (t== null) ? "none" : String.valueOf(t.getId());
+        }
+    }
+
     /**
      * Locks the database for exclusive access. The database lock must be held when
      * touch the native sqlite3* object since it is single threaded and uses
diff --git a/core/java/android/nfc/NfcAdapter.java b/core/java/android/nfc/NfcAdapter.java
index d30a0c6..f59d9cf 100644
--- a/core/java/android/nfc/NfcAdapter.java
+++ b/core/java/android/nfc/NfcAdapter.java
@@ -33,10 +33,11 @@
 import android.util.Log;
 
 /**
- * Represents the device's local NFC adapter.
+ * Represents the local NFC adapter.
  * <p>
  * Use the helper {@link #getDefaultAdapter(Context)} to get the default NFC
  * adapter for this Android device.
+ * <p>
  */
 public final class NfcAdapter {
     private static final String TAG = "NFC";
@@ -359,14 +360,13 @@
 
     /**
      * Return true if this NFC Adapter has any features enabled.
-     * <p>
-     * If this method returns false, then applications should request the user
-     * turn on NFC tag discovery in Settings.
-     * <p>
-     * If this method returns false, the NFC hardware is guaranteed not to
-     * perform or respond to any NFC communication.
      *
-     * @return true if this NFC Adapter is enabled to discover new tags
+     * <p>Application may use this as a helper to suggest that the user
+     * should turn on NFC in Settings.
+     * <p>If this method returns false, the NFC hardware is guaranteed not to
+     * generate or respond to any NFC transactions.
+     *
+     * @return true if this NFC Adapter has any features enabled
      */
     public boolean isEnabled() {
         try {
@@ -414,17 +414,24 @@
     }
 
     /**
-     * Enables foreground dispatching to the given Activity. This will force all NFC Intents that
-     * match the given filters to be delivered to the activity bypassing the standard dispatch
-     * mechanism. If no IntentFilters are given all the PendingIntent will be invoked for every
-     * dispatch Intent.
+     * Enable foreground dispatch to the given Activity.
      *
-     * This method must be called from the main thread.
+     * <p>This will give give priority to the foreground activity when
+     * dispatching a discovered {@link Tag} to an application.
+     *
+     * <p>Activities must call {@link #disableForegroundDispatch} in
+     * their {@link Activity#onPause} callback.
+     *
+     * <p>a null set of intent filters will cause the forground activity
+     * to receive all tags.
+     *
+     * <p>This method must be called from the main thread, and
+     * only when the activity is in the foreground (resumed).     *
      *
      * @param activity the Activity to dispatch to
      * @param intent the PendingIntent to start for the dispatch
      * @param filters the IntentFilters to override dispatching for, or null to always dispatch
-     * @throws IllegalStateException
+     * @throws IllegalStateException if the Activity is not currently in the foreground
      */
     public void enableForegroundDispatch(Activity activity, PendingIntent intent,
             IntentFilter[] filters, String[][] techLists) {
@@ -450,13 +457,16 @@
     }
 
     /**
-     * Disables foreground activity dispatching setup with
-     * {@link #enableForegroundDispatch}.
+     * Disable foreground dispatch to the given activity.
      *
-     * <p>This must be called before the Activity returns from
-     * it's <code>onPause()</code> or this method will throw an IllegalStateException.
+     * <p>After calling {@link #enableForegroundDispatch}, an activity
+     * must call this method before its {@link Activity#onPause} callback
+     * completes.
      *
      * <p>This method must be called from the main thread.
+     *
+     * @param activity the Activity to disable dispatch to
+     * @throws IllegalStateException if the Activity has already been paused
      */
     public void disableForegroundDispatch(Activity activity) {
         ActivityThread.currentActivityThread().unregisterOnActivityPausedListener(activity,
@@ -484,13 +494,22 @@
     }
 
     /**
-     * Enable NDEF message push over P2P while this Activity is in the foreground. For this to
-     * function properly the other NFC device being scanned must support the "com.android.npp"
-     * NDEF push protocol.
+     * Enable NDEF message push over P2P while this Activity is in the foreground.
+     *
+     * <p>For this to function properly the other NFC device being scanned must
+     * support the "com.android.npp" NDEF push protocol. Support for this
+     * protocol is currently optional for Android NFC devices.
+     *
+     * <p>This method must be called from the main thread.
      *
      * <p><em>NOTE</em> While foreground NDEF push is active standard tag dispatch is disabled.
      * Only the foreground activity may receive tag discovered dispatches via
      * {@link #enableForegroundDispatch}.
+     *
+     * @param activity the foreground Activity
+     * @param msg a NDEF Message to push over P2P
+     * @throws IllegalStateException if the Activity is not currently in the foreground
+     * @throws OperationNotSupportedException if this Android device does not support NDEF push
      */
     public void enableForegroundNdefPush(Activity activity, NdefMessage msg) {
         if (activity == null || msg == null) {
@@ -510,13 +529,17 @@
     }
 
     /**
-     * Disables foreground NDEF push setup with
-     * {@link #enableForegroundNdefPush}.
+     * Disable NDEF message push over P2P.
      *
-     * <p>This must be called before the Activity returns from
-     * it's <code>onPause()</code> or this method will throw an IllegalStateException.
+     * <p>After calling {@link #enableForegroundNdefPush}, an activity
+     * must call this method before its {@link Activity#onPause} callback
+     * completes.
      *
      * <p>This method must be called from the main thread.
+     *
+     * @param activity the Foreground activity
+     * @throws IllegalStateException if the Activity has already been paused
+     * @throws OperationNotSupportedException if this Android device does not support NDEF push
      */
     public void disableForegroundNdefPush(Activity activity) {
         ActivityThread.currentActivityThread().unregisterOnActivityPausedListener(activity,
diff --git a/core/java/android/nfc/NfcSecureElement.java b/core/java/android/nfc/NfcSecureElement.java
index ea2846e..3b5f39e 100755
--- a/core/java/android/nfc/NfcSecureElement.java
+++ b/core/java/android/nfc/NfcSecureElement.java
@@ -35,8 +35,8 @@
     private static final String TAG = "NfcSecureElement";
 
     private INfcSecureElement mService;
-    
-       
+
+
     /**
      * @hide
      */
@@ -68,7 +68,7 @@
 
 
     public byte [] exchangeAPDU(int handle,byte [] data) throws IOException {
-        
+
 
         // Perform exchange APDU
         try {
@@ -85,7 +85,7 @@
     }
 
     public void closeSecureElementConnection(int handle) throws IOException {
-         
+
         try {
             int status = mService.closeSecureElementConnection(handle);
             // Handle potential errors
@@ -96,14 +96,14 @@
             Log.e(TAG, "RemoteException in closeSecureElement(): ", e);
         }
     }
-    
-    
+
+
     /**
      * Returns target type. constants.
-     * 
+     *
      * @return Secure Element technology type. The possible values are defined in
      * {@link TagTechnology}
-     * 
+     *
      */
     public int[] getSecureElementTechList(int handle) throws IOException {
         try {
@@ -113,16 +113,16 @@
             return null;
         }
     }
-    
+
     /**
      * Returns Secure Element UID.
-     * 
+     *
      * @return Secure Element UID.
      */
     public byte[] getSecureElementUid(int handle) throws IOException {
-        
+
         byte[] uid = null;
-        try {            
+        try {
             uid = mService.getSecureElementUid(handle);
             // Handle potential errors
             if (uid == null) {
diff --git a/core/java/android/nfc/Tag.java b/core/java/android/nfc/Tag.java
index 45a3447..2305fb9 100644
--- a/core/java/android/nfc/Tag.java
+++ b/core/java/android/nfc/Tag.java
@@ -16,6 +16,7 @@
 
 package android.nfc;
 
+import android.content.Context;
 import android.nfc.tech.IsoDep;
 import android.nfc.tech.MifareClassic;
 import android.nfc.tech.MifareUltralight;
@@ -33,27 +34,69 @@
 import java.util.Arrays;
 
 /**
- * Represents a (generic) discovered tag.
+ * Represents an NFC tag that has been discovered.
  * <p>
- * A tag is a passive NFC element, such as NFC Forum Tag's, MIFARE class Tags,
- * Sony FeliCa Tags, etc.
- * <p>
- * Tag's have a type and usually have a UID.
- * <p>
- * {@link Tag} objects are passed to applications via the {@link NfcAdapter#EXTRA_TAG} extra
- * in {@link NfcAdapter#ACTION_TAG_DISCOVERED} intents. A {@link Tag} object is immutable
- * and represents the state of the tag at the time of discovery. It can be
- * directly queried for its UID and Type, or used to create a {@link TagTechnology} using the
- * static <code>get()</code> methods on the varios tech classes.
- * <p>
- * A {@link Tag} can  be used to create a {@link TagTechnology} only while the tag is in
- * range. If it is removed and then returned to range, then the most recent
- * {@link Tag} object (in {@link NfcAdapter#ACTION_TAG_DISCOVERED}) should be used to create a
- * {@link TagTechnology}.
- * <p>This is an immutable data class. All properties are set at Tag discovery
- * time and calls on this class will retrieve those read-only properties, and
- * not cause any further RF activity or block. Note however that arrays passed to and
+ * {@link Tag} is an immutable object that represents the state of a NFC tag at
+ * the time of discovery. It can be used as a handle to {@link TagTechnology} classes
+ * to perform advanced operations, or directly queried for its ID ({@link #getId} and the
+ * set of technologies it contains ({@link #getTechList}). Arrays passed to and
  * returned by this class are *not* cloned, so be careful not to modify them.
+ * <p>
+ * A new tag object is created every time a tag is discovered (comes into range), even
+ * if it is the same physical tag. If a tag is removed and then returned into range, then
+ * only the most recent tag object can be successfully used to create a {@link TagTechnology}.
+ *
+ * <h3>Tag Dispatch</h3>
+ * When a tag is discovered, a {@link Tag} object is created and passed to a
+ * single application via the {@link NfcAdapter#EXTRA_TAG} extra in a
+ * {@link Context#startActivity} {@link android.content.Intent}. A four stage dispatch is used to select the
+ * most appropriate application to handle the tag. The Android OS executes each stage in order,
+ * and completes dispatch as soon as a single matching application is found. If there are multiple
+ * matching applications found at any one stage then the Android Activity Chooser dialog is shown
+ * to allow the user to select the application.
+ * <h4>1. Foreground activity dispatch</h4>
+ * A foreground activity that has called {@link NfcAdapter#enableForegroundDispatch} is
+ * given priority. See the documentation on {#link NfcAdapter#enableForegroundDispatch} for
+ * its usage.
+ * <h4>2. NDEF data dispatch</h4>
+ * If the tag contains NDEF data, then {@link Context#startActivity} is called with
+ * {@link NfcAdapter#ACTION_NDEF_DISCOVERED} and a data URI determined from the
+ * first NDEF Record in the first NDEF Message in the Tag. This allows NDEF tags to be given
+ * priority dispatch to applications that can handle the content.
+ * See {@link NfcAdapter#ACTION_NDEF_DISCOVERED} for more detail. If the tag does not contain
+ * NDEF data, or if no application is registered
+ * for {@link NfcAdapter#ACTION_NDEF_DISCOVERED} with a matching data URI then dispatch moves
+ * to stage 3.
+ * <h4>3. Tag Technology dispatch</h4>
+ * {@link Context#startActivity} is called with {@link NfcAdapter#ACTION_TECH_DISCOVERED} to
+ * dispatch the tag to an application that can handle the technologies present on the tag.
+ * Technologies are defined as sub-classes of {@link TagTechnology}, see the package
+ * {@link android.nfc.tech}. The Android OS looks for an application that can handle one or
+ * more technologies in the tag. See {@link NfcAdapter#ACTION_TECH_DISCOVERED for more detail.
+ * <h4>4. Fall-back dispatch</h4>
+ * If no application has been matched, then {@link Context#startActivity} is called with
+ * {@link NfcAdapter#ACTION_TAG_DISCOVERED}. This is intended as a fall-back mechanism.
+ * See {@link NfcAdapter#ACTION_TAG_DISCOVERED}.
+ *
+ * <p>
+ * <i>The Tag dispatch mechanism was designed to give a high probability of dispatching
+ * a tag to the correct application without showing the user an Application Chooser dialog.
+ * This is important for NFC interactions because they are very transient - if a user has to
+ * move the Android device to choose an application then the connection is broken.</i>
+ *
+ * <h3>NFC Tag Background</h3>
+ * An NFC tag is a passive NFC device, powered by the NFC field of this Android device while
+ * it is in range. Tag's can come in many forms, such as stickers, cards, key fob, or
+ * even embedded in a more sophisticated device.
+ * <p>
+ * Tags can have a wide range of capabilities. Simple tags just offer read/write semantics,
+ * and contain some one time
+ * programmable areas to make read-only. More complex tags offer math operations
+ * and per-sector access control and authentication. The most sophisticated tags
+ * contain operating environments such as Javacard, allowing complex interactions with the
+ * applets executing on the tag. Use {@link TagTechnology} classes to access a broad
+ * range of capabilities available in NFC tags.
+ * <p>
  */
 public final class Tag implements Parcelable {
     /*package*/ final byte[] mId;
@@ -149,21 +192,35 @@
 
     /**
      * Get the Tag Identifier (if it has one).
-     * <p>Tag ID is usually a serial number for the tag.
-     *
-     * @return ID, or null if it does not exist
+     * <p>The tag identifier is a low level serial number, used for anti-collision
+     * and identification.
+     * <p> Most tags have a stable unique identifier
+     * (UID), but some tags will generate a random ID every time they are discovered
+     * (RID), and there are some tags with no ID at all (the byte array will be zero-sized).
+     * <p> The size and format of an ID is specific to the RF technology used by the tag.
+     * <p> This function retrieves the ID as determined at discovery time, and does not
+     * perform any further RF communication or block.
+     * @return ID as byte array, never null
      */
     public byte[] getId() {
         return mId;
     }
 
     /**
-     * Returns technologies present in the tag that this implementation understands,
-     * or a zero length array if there are no supported technologies on this tag.
-     *
-     * The elements of the list are the names of the classes implementing the technology. 
-     *
+     * Get the technologies available in this tag, as fully qualified class names.
+     * <p>
+     * A technology is an implementation of the {@link TagTechnology} interface,
+     * and can be instantiated by calling the static <code>get(Tag)</code>
+     * method on the implementation with this Tag. The {@link TagTechnology}
+     * object can then be used to perform advanced, technology-specific operations on a tag.
+     * <p>
+     * Android defines a mandatory set of technologies that must be correctly
+     * enumerated by all Android NFC devices, and an optional
+     * set of proprietary technologies.
+     * See {@link TagTechnology} for more details.
+     * <p>
      * The ordering of the returned array is undefined and should not be relied upon.
+     * @return an array of fully-qualified {@link TagTechnology} class-names.
      */
     public String[] getTechList() {
         return mTechStringList;
@@ -176,7 +233,7 @@
         }
         return false;
     }
-    
+
     /** @hide */
     public Bundle getTechExtras(int tech) {
         int pos = -1;
@@ -198,6 +255,9 @@
         return mTagService;
     }
 
+    /**
+     * Human-readable description of the tag, for debugging.
+     */
     @Override
     public String toString() {
         StringBuilder sb = new StringBuilder("TAG ")
diff --git a/core/java/android/nfc/tech/IsoDep.java b/core/java/android/nfc/tech/IsoDep.java
index 774982e..2a132f9 100644
--- a/core/java/android/nfc/tech/IsoDep.java
+++ b/core/java/android/nfc/tech/IsoDep.java
@@ -24,18 +24,14 @@
 import java.io.IOException;
 
 /**
- * A low-level connection to a {@link Tag} using the ISO-DEP technology, also known as
- * ISO1443-4.
+ * Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations on a {@link Tag}.
  *
- * <p>You can acquire this kind of connection with {@link #get}.
- * Use this class to send and receive data with {@link #transceive transceive()}.
- *
- * <p>Applications must implement their own protocol stack on top of
- * {@link #transceive transceive()}.
- *
- * <p class="note"><strong>Note:</strong>
- * Use of this class requires the {@link android.Manifest.permission#NFC}
- * permission.
+ * <p>Acquire a {@link IsoDep} object using {@link #get}.
+ * <p>The primary ISO-DEP I/O operation is {@link #transceive}. Applications must
+ * implement their own protocol stack on top of {@link #transceive}.
+ * <p>Tags that enumerate the {@link IsoDep} technology in {@link Tag#getTechList}
+ * will also enumerate
+ * {@link NfcA} or {@link NfcB} (since IsoDep builds on top of either of these).
  */
 public final class IsoDep extends BasicTagTechnology {
     private static final String TAG = "NFC";
@@ -49,10 +45,13 @@
     private byte[] mHistBytes = null;
 
     /**
-     * Returns an instance of this tech for the given tag. If the tag doesn't support
-     * this tech type null is returned.
+     * Get an instance of {@link IsoDep} for the given tag.
+     * <p>Does not cause any RF activity and does not block.
+     * <p>Returns null if {@link IsoDep} was not enumerated in {@link Tag#getTechList}.
+     * This indicates the tag does not support ISO-DEP.
      *
-     * @param tag The tag to get the tech from
+     * @param tag an ISO-DEP compatible tag
+     * @return ISO-DEP object
      */
     public static IsoDep get(Tag tag) {
         if (!tag.hasTech(TagTechnology.ISO_DEP)) return null;
@@ -62,7 +61,7 @@
             return null;
         }
     }
-    
+
     /** @hide */
     public IsoDep(Tag tag)
             throws RemoteException {
@@ -75,13 +74,13 @@
     }
 
     /**
-     * Sets the timeout of an IsoDep transceive transaction in milliseconds.
-     * If the transaction has not completed before the timeout,
-     * any ongoing {@link #transceive} operation will be
-     * aborted and the connection to the tag is lost. This setting is applied
-     * only to the {@link Tag} object linked to this technology and will be
-     * reset when {@link IsoDep#close} is called.
-     * The default transaction timeout is 300 milliseconds.
+     * Set the timeout of {@link #transceive} in milliseconds.
+     * <p>The timeout only applies to ISO-DEP {@link #transceive}, and is
+     * reset to a default value when {@link #close} is called.
+     * <p>Setting a longer timeout may be useful when performing
+     * transactions that require a long processing time on the tag
+     * such as key generation.
+     * @param timeout timeout value in milliseconds
      */
     public void setTimeout(int timeout) {
         try {
@@ -102,29 +101,51 @@
     }
 
     /**
-     * Return the historical bytes if the tag is using {@link NfcA}, null otherwise.
+     * Return the ISO-DEP historical bytes for {@link NfcA} tags.
+     * <p>Does not cause any RF activity and does not block.
+     * <p>The historical bytes can be used to help identify a tag. They are present
+     * only on {@link IsoDep} tags that are based on {@link NfcA} RF technology.
+     * If this tag is not {@link NfcA} then null is returned.
+     * <p>In ISO 14443-4 terminology, the historical bytes are a subset of the RATS
+     * response.
+     *
+     * @return ISO-DEP historical bytes, or null if this is not a {@link NfcA} tag
      */
     public byte[] getHistoricalBytes() {
         return mHistBytes;
     }
 
     /**
-     * Return the hi layer response bytes if the tag is using {@link NfcB}, null otherwise.
+     * Return the higher layer response bytes for {@link NfcB} tags.
+     * <p>Does not cause any RF activity and does not block.
+     * <p>The higher layer response bytes can be used to help identify a tag.
+     * They are present only on {@link IsoDep} tags that are based on {@link NfcB}
+     * RF technology. If this tag is not {@link NfcB} then null is returned.
+     * <p>In ISO 14443-4 terminology, the higher layer bytes are a subset of the
+     * ATTRIB response.
+     *
+     * @return ISO-DEP historical bytes, or null if this is not a {@link NfcB} tag
      */
     public byte[] getHiLayerResponse() {
         return mHiLayerResponse;
     }
 
     /**
-     * Send data to a tag and receive the response.
-     * <p>
-     * This method will block until the response is received. It can be canceled
-     * with {@link #close}.
-     * <p>Requires {@link android.Manifest.permission#NFC} permission.
+     * Send raw ISO-DEP data to the tag and receive the response.
      *
-     * @param data bytes to send
-     * @return bytes received in response
-     * @throws IOException if the target is lost or connection closed
+     * <p>Applications must only send the INF payload, and not the start of frame and
+     * end of frame indicators. Applications do not need to fragment the payload, it
+     * will be automatically fragmented and defragmented by {@link #transceive} if
+     * it exceeds FSD/FSC limits.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param data command bytes to send, must not be null
+     * @return response bytes received, will not be null
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or this operation is canceled
      */
     public byte[] transceive(byte[] data) throws IOException {
         return transceive(data, true);
diff --git a/core/java/android/nfc/tech/MifareClassic.java b/core/java/android/nfc/tech/MifareClassic.java
index d337ead..3d513b7 100644
--- a/core/java/android/nfc/tech/MifareClassic.java
+++ b/core/java/android/nfc/tech/MifareClassic.java
@@ -25,32 +25,61 @@
 import java.nio.ByteOrder;
 
 /**
- * Technology class representing MIFARE Classic tags (also known as MIFARE Standard).
+ * Provides access to MIFARE Classic properties and I/O operations on a {@link Tag}.
  *
- * <p>Support for this technology type is optional. If the NFC stack doesn't support this technology
- * MIFARE Classic tags will still be scanned, but will only show the NfcA technology.
+ * <p>Acquire a {@link MifareClassic} object using {@link #get}.
  *
- * <p>MIFARE Classic tags have sectors that each contain blocks. The block size is constant at
- * 16 bytes, but the number of sectors and the sector size varies by product. MIFARE has encryption
- * built in and each sector has two keys associated with it, as well as ACLs to determine what
- * level acess each key grants. Before operating on a sector you must call either
- * {@link #authenticateSectorWithKeyA(int, byte[])} or
- * {@link #authenticateSectorWithKeyB(int, byte[])} to gain authorization for your request.
+ * <p>MIFARE Classic is also known as MIFARE Standard.
+ * <p>MIFARE Classic tags are divided into sectors, and each sector is sub-divided into
+ * blocks. Block size is always 16 bytes ({@link #BLOCK_SIZE}. Sector size varies.
+ * <ul>
+ * <li>MIFARE Classic Mini are 320 bytes ({@link #SIZE_MINI}), with 5 sectors each of 4 blocks.
+ * <li>MIFARE Classic 1k are 1024 bytes ({@link #SIZE_1K}), with 16 sectors each of 4 blocks.
+ * <li>MIFARE Classic 2k are 2048 bytes ({@link #SIZE_2K}), with 32 sectors each of 4 blocks.
+ * <li>MIFARE Classic 4k} are 4096 bytes ({@link #SIZE_4K}). The first 32 sectors contain 4 blocks
+ * and the last 8 sectors contain 16 blocks.
+ * </ul>
+ *
+ * <p>MIFARE Classic tags require authentication on a per-sector basis before any
+ * other I/O operations on that sector can be performed. There are two keys per sector,
+ * and ACL bits determine what I/O operations are allowed on that sector after
+ * authenticating with a key. {@see #authenticateSectorWithKeyA} and
+ * {@see #authenticateSectorWithKeyB}.
+ *
+ * <p>Three well-known authentication keys are defined in this class:
+ * {@link #KEY_DEFAULT}, {@link #KEY_MIFARE_APPLICATION_DIRECTORY},
+ * {@link #KEY_NFC_FORUM}.
+ * <ul>
+ * <li>{@link #KEY_DEFAULT} is the default factory key for MIFARE Classic.
+ * <li>{@link #KEY_MIFARE_APPLICATION_DIRECTORY} is the well-known key for
+ * MIFARE Classic cards that have been formatted according to the
+ * MIFARE Application Directory (MAD) specification.
+ * <li>{@link #KEY_NFC_FORUM} is the well-known key for MIFARE Classic cards that
+ * have been formatted according to the NFC
+ *
+ * <p>Implementation of this class on a Android NFC device is optional.
+ * If it is not implemented, then
+ * {@link MifareClassic} will never be enumerated in {@link Tag#getTechList}.
+ * If it is enumerated, then all {@link MifareClassic} I/O operations will be supported,
+ * and {@link Ndef#MIFARE_CLASSIC} NDEF tags will also be supported. In either case,
+ * {@link NfcA} will also be enumerated on the tag, because all MIFARE Classic tags are also
+ * {@link NfcA}.
  */
 public final class MifareClassic extends BasicTagTechnology {
     /**
-     * The well-known default MIFARE read key. All keys are set to this at the factory.
-     * Using this key will effectively make the payload in the sector public.
+     * The default factory key.
      */
     public static final byte[] KEY_DEFAULT =
             {(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF};
     /**
-     * The well-known, default MIFARE Application Directory read key.
+     * The well-known key for tags formatted according to the
+     * MIFARE Application Directory (MAD) specification.
      */
     public static final byte[] KEY_MIFARE_APPLICATION_DIRECTORY =
             {(byte)0xA0,(byte)0xA1,(byte)0xA2,(byte)0xA3,(byte)0xA4,(byte)0xA5};
     /**
-     * The well-known, default read key for NDEF data on a MIFARE Classic
+     * The well-known key for tags formatted according to the
+     * NDEF on Mifare Classic specification.
      */
     public static final byte[] KEY_NFC_FORUM =
             {(byte)0xD3,(byte)0xF7,(byte)0xD3,(byte)0xF7,(byte)0xD3,(byte)0xF7};
@@ -64,19 +93,19 @@
     /** A MIFARE Pro tag */
     public static final int TYPE_PRO = 2;
 
-    /** The tag contains 16 sectors, each holding 4 blocks. */
+    /** Tag contains 16 sectors, each with 4 blocks. */
     public static final int SIZE_1K = 1024;
-    /** The tag contains 32 sectors, each holding 4 blocks. */
+    /** Tag contains 32 sectors, each with 4 blocks. */
     public static final int SIZE_2K = 2048;
     /**
-     * The tag contains 40 sectors. The first 32 sectors contain 4 blocks and the last 8 sectors
+     * Tag contains 40 sectors. The first 32 sectors contain 4 blocks and the last 8 sectors
      * contain 16 blocks.
      */
     public static final int SIZE_4K = 4096;
-    /** The tag contains 5 sectors, each holding 4 blocks. */
+    /** Tag contains 5 sectors, each with 4 blocks. */
     public static final int SIZE_MINI = 320;
 
-    /** Size of a Mifare Classic block (in bytes) */
+    /** Size of a MIFARE Classic block (in bytes) */
     public static final int BLOCK_SIZE = 16;
 
     private static final int MAX_BLOCK_COUNT = 256;
@@ -87,10 +116,14 @@
     private int mSize;
 
     /**
-     * Returns an instance of this tech for the given tag. If the tag doesn't support
-     * this tech type null is returned.
+     * Get an instance of {@link MifareClassic} for the given tag.
+     * <p>Does not cause any RF activity and does not block.
+     * <p>Returns null if {@link MifareClassic} was not enumerated in {@link Tag#getTechList}.
+     * This indicates the tag is not MIFARE Classic compatible, or this Android
+     * device does not support MIFARE Classic.
      *
-     * @param tag The tag to get the tech from
+     * @param tag an MIFARE Classic compatible tag
+     * @return MIFARE Classic object
      */
     public static MifareClassic get(Tag tag) {
         if (!tag.hasTech(TagTechnology.MIFARE_CLASSIC)) return null;
@@ -160,17 +193,31 @@
         }
     }
 
-    /** Returns the type of the tag, determined at discovery time */
+    /**
+     * Return the type of this MIFARE Classic compatible tag.
+     * <p>One of {@link #TYPE_UNKNOWN}, {@link #TYPE_CLASSIC}, {@link #TYPE_PLUS} or
+     * {@link #TYPE_PRO}.
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return type
+     */
     public int getType() {
         return mType;
     }
 
-    /** Returns the size of the tag in bytes, determined at discovery time */
+    /**
+     * Return the size of the tag in bytes
+     * <p>One of {@link #SIZE_MINI}, {@link #SIZE_1K}, {@link #SIZE_2K}, {@link #SIZE_4K}.
+     * These constants are equal to their respective size in bytes.
+     * <p>Does not cause any RF activity and does not block.
+     * @return size in bytes
+     */
     public int getSize() {
         return mSize;
     }
 
-    /** Returns true if the tag is emulated, determined at discovery time.
+    /**
+     * Return true if the tag is emulated, determined at discovery time.
      * These are actually smart-cards that emulate a Mifare Classic interface.
      * They can be treated identically to a Mifare Classic tag.
      * @hide
@@ -179,7 +226,11 @@
         return mIsEmulated;
     }
 
-    /** Returns the number of sectors on this tag, determined at discovery time */
+    /**
+     * Return the number of MIFARE Classic sectors.
+     * <p>Does not cause any RF activity and does not block.
+     * @return number of sectors
+     */
     public int getSectorCount() {
         switch (mSize) {
         case SIZE_1K:
@@ -195,12 +246,22 @@
         }
     }
 
-    /** Returns the total block count, determined at discovery time */
+    /**
+     * Return the total number of MIFARE Classic blocks.
+     * <p>Does not cause any RF activity and does not block.
+     * @return total number of blocks
+     */
     public int getBlockCount() {
         return mSize / BLOCK_SIZE;
     }
 
-    /** Returns the block count for the given sector, determined at discovery time */
+    /**
+     * Return the number of blocks in the given sector.
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @param sectorIndex index of sector, starting from 0
+     * @return number of blocks in the sector
+     */
     public int getBlockCountInSector(int sectorIndex) {
         validateSector(sectorIndex);
 
@@ -211,7 +272,13 @@
         }
     }
 
-    /** Return the sector index of a given block */
+    /**
+     * Return the sector that contains a given block.
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @param blockIndex index of block to lookup, starting from 0
+     * @return sector index that contains the block
+     */
     public int blockToSector(int blockIndex) {
         validateBlock(blockIndex);
 
@@ -222,7 +289,13 @@
         }
     }
 
-    /** Return the first block of a given sector */
+    /**
+     * Return the first block of a given sector.
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @param sectorIndex index of sector to lookup, starting from 0
+     * @return block index of first block in sector
+     */
     public int sectorToBlock(int sectorIndex) {
         if (sectorIndex < 32) {
             return sectorIndex * 4;
@@ -231,22 +304,51 @@
         }
     }
 
-    // Methods that require connect()
     /**
-     * Authenticate a sector.
-     * <p>Every sector has an A and B key with different access privileges,
-     * this method attempts to authenticate against the A key.
-     * <p>This requires a that the tag be connected.
+     * Authenticate a sector with key A.
+     *
+     * <p>Successful authentication of a sector with key A enables other
+     * I/O operations on that sector. The set of operations granted by key A
+     * key depends on the ACL bits set in that sector. For more information
+     * see the MIFARE Classic specification on {@see http://www.nxp.com}.
+     *
+     * <p>A failed authentication attempt causes an implicit reconnection to the
+     * tag, so authentication to other sectors will be lost.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param sectorIndex index of sector to authenticate, starting from 0
+     * @param key 6-byte authentication key
+     * @return true on success, false on authentication failure
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
      */
     public boolean authenticateSectorWithKeyA(int sectorIndex, byte[] key) throws IOException {
         return authenticate(sectorIndex, key, true);
     }
 
     /**
-     * Authenticate a sector.
-     * <p>Every sector has an A and B key with different access privileges,
-     * this method attempts to authenticate against the B key.
-     * <p>This requires a that the tag be connected.
+     * Authenticate a sector with key B.
+     *
+     * <p>Successful authentication of a sector with key B enables other
+     * I/O operations on that sector. The set of operations granted by key B
+     * depends on the ACL bits set in that sector. For more information
+     * see the MIFARE Classic specification on {@see http://www.nxp.com}.
+     *
+     * <p>A failed authentication attempt causes an implicit reconnection to the
+     * tag, so authentication to other sectors will be lost.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param sectorIndex index of sector to authenticate, starting from 0
+     * @param key 6-byte authentication key
+     * @return true on success, false on authentication failure
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
      */
     public boolean authenticateSectorWithKeyB(int sectorIndex, byte[] key) throws IOException {
         return authenticate(sectorIndex, key, false);
@@ -291,8 +393,15 @@
 
     /**
      * Read 16-byte block.
-     * <p>This requires a that the tag be connected.
-     * @throws IOException
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param blockIndex index of block to read, starting from 0
+     * @return 16 byte block
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
      */
     public byte[] readBlock(int blockIndex) throws IOException {
         validateBlock(blockIndex);
@@ -304,8 +413,15 @@
 
     /**
      * Write 16-byte block.
-     * <p>This requires a that the tag be connected.
-     * @throws IOException
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param blockIndex index of block to write, starting from 0
+     * @param data 16 bytes of data to write
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
      */
     public void writeBlock(int blockIndex, byte[] data) throws IOException {
         validateBlock(blockIndex);
@@ -323,9 +439,16 @@
     }
 
     /**
-     * Increment a value block, and store the result in temporary memory.
-     * @param blockIndex
-     * @throws IOException
+     * Increment a value block, storing the result in the temporary block on the tag.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param blockIndex index of block to increment, starting from 0
+     * @param value non-negative to increment by
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
      */
     public void increment(int blockIndex, int value) throws IOException {
         validateBlock(blockIndex);
@@ -342,9 +465,16 @@
     }
 
     /**
-     * Decrement a value block, and store the result in temporary memory.
-     * @param blockIndex
-     * @throws IOException
+     * Decrement a value block, storing the result in the temporary block on the tag.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param blockIndex index of block to decrement, starting from 0
+     * @param value non-negative to decrement by
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
      */
     public void decrement(int blockIndex, int value) throws IOException {
         validateBlock(blockIndex);
@@ -361,9 +491,15 @@
     }
 
     /**
-     * Copy from temporary memory to value block.
-     * @param blockIndex
-     * @throws IOException
+     * Copy from the temporary block to a value block.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param blockIndex index of block to copy to
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
      */
     public void transfer(int blockIndex) throws IOException {
         validateBlock(blockIndex);
@@ -375,9 +511,15 @@
     }
 
     /**
-     * Copy from value block to temporary memory.
-     * @param blockIndex
-     * @throws IOException
+     * Copy from a value block to the temporary block.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param blockIndex index of block to copy from
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
      */
     public void restore(int blockIndex) throws IOException {
         validateBlock(blockIndex);
@@ -390,15 +532,16 @@
 
     /**
      * Send raw NfcA data to a tag and receive the response.
-     * <p>
-     * This method will block until the response is received. It can be canceled
-     * with {@link #close}.
-     * <p>Requires {@link android.Manifest.permission#NFC} permission.
-     * <p>This requires a that the tag be connected.
      *
-     * @param data bytes to send
-     * @return bytes received in response
-     * @throws IOException if the target is lost or connection closed
+     * <p>This is equivalent to connecting to this tag via {@link NfcA}
+     * and calling {@link NfcA#transceive}. Note that all MIFARE Classic
+     * tags are based on {@link NfcA} technology.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @see NfcA#transceive
      */
     public byte[] transceive(byte[] data) throws IOException {
         return transceive(data, true);
diff --git a/core/java/android/nfc/tech/MifareUltralight.java b/core/java/android/nfc/tech/MifareUltralight.java
index b514f1c..6c8f725 100644
--- a/core/java/android/nfc/tech/MifareUltralight.java
+++ b/core/java/android/nfc/tech/MifareUltralight.java
@@ -17,6 +17,7 @@
 package android.nfc.tech;
 
 import android.nfc.Tag;
+import android.nfc.TagLostException;
 import android.os.RemoteException;
 
 import java.io.IOException;
@@ -24,14 +25,13 @@
 //TOOD: Ultralight C 3-DES authentication, one-way counter
 
 /**
- * Technology class representing MIFARE Ultralight and MIFARE Ultralight C tags.
+ * Provides access to MIFARE Ultralight properties and I/O operations on a {@link Tag}.
  *
- * <p>Support for this technology type is optional. If the NFC stack doesn't support this technology
- * MIFARE Ultralight class tags will still be scanned, but will only show the NfcA technology.
+ * <p>Acquire a {@link MifareUltralight} object using {@link #get}.
  *
- * <p>MIFARE Ultralight compatible tags have 4 byte pages. The read command
- * returns 4 pages (16 bytes) at a time, for speed. The write command operates
- * on a single page (4 bytes) to minimize EEPROM write cycles.
+ * <p>MIFARE Ultralight compatible tags have 4 byte pages {@link #PAGE_SIZE}.
+ * The primary operations on an Ultralight tag are {@link #readPages} and
+ * {@link #writePage}.
  *
  * <p>The original MIFARE Ultralight consists of a 64 byte EEPROM. The first
  * 4 pages are for the OTP area, manufacturer data, and locking bits. They are
@@ -44,6 +44,13 @@
  * and authentication configuration and are readable. The final 4 pages are for
  * the authentication key and are not readable. For more information see the
  * NXP data sheet MF0ICU2.
+ *
+ * <p>Implementation of this class on a Android NFC device is optional.
+ * If it is not implemented, then
+ * {@link MifareUltralight} will never be enumerated in {@link Tag#getTechList}.
+ * If it is enumerated, then all {@link MifareUltralight} I/O operations will be supported.
+ * In either case, {@link NfcA} will also be enumerated on the tag,
+ * because all MIFARE Ultralight tags are also {@link NfcA} tags.
  */
 public final class MifareUltralight extends BasicTagTechnology {
     /** A MIFARE Ultralight compatible tag of unknown type */
@@ -62,10 +69,15 @@
     private int mType;
 
     /**
-     * Returns an instance of this tech for the given tag. If the tag doesn't support
-     * this tech type null is returned.
+     * Get an instance of {@link MifareUltralight} for the given tag.
+     * <p>Returns null if {@link MifareUltralight} was not enumerated in
+     * {@link Tag#getTechList} - this indicates the tag is not MIFARE
+     * Ultralight compatible, or that this Android
+     * device does not implement MIFARE Ultralight.
+     * <p>Does not cause any RF activity and does not block.
      *
-     * @param tag The tag to get the tech from
+     * @param tag an MIFARE Ultralight compatible tag
+     * @return MIFARE Ultralight object
      */
     public static MifareUltralight get(Tag tag) {
         if (!tag.hasTech(TagTechnology.MIFARE_ULTRALIGHT)) return null;
@@ -93,31 +105,44 @@
         }
     }
 
-    /** Returns the type of the tag.
-     * <p>It is very hard to always accurately classify a MIFARE Ultralight
-     * compatible tag as Ultralight original or Ultralight C. So consider
-     * {@link #getType} a hint. */
+    /**
+     * Return the MIFARE Ultralight type of the tag.
+     * <p>One of {@link #TYPE_ULTRALIGHT} or {@link #TYPE_ULTRALIGHT_C} or
+     * {@link #TYPE_UNKNOWN}.
+     * <p>Depending on how the tag has been formatted, it can be impossible
+     * to accurately classify between original MIFARE Ultralight and
+     * Ultralight C. So treat this method as a hint.
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return the type
+     */
     public int getType() {
         return mType;
     }
 
-    // Methods that require connect()
     /**
      * Read 4 pages (16 bytes).
-     * <p>The MIFARE Ultralight protocol always reads 4 pages at a time.
-     * <p>If the read spans past the last readable block, then the tag will
+     *
+     * <p>The MIFARE Ultralight protocol always reads 4 pages at a time, to
+     * reduce the number of commands required to read an entire tag.
+     * <p>If a read spans past the last readable block, then the tag will
      * return pages that have been wrapped back to the first blocks. MIFARE
      * Ultralight tags have readable blocks 0x00 through 0x0F. So a read to
      * block offset 0x0E would return blocks 0x0E, 0x0F, 0x00, 0x01. MIFARE
      * Ultralight C tags have readable blocks 0x00 through 0x2B. So a read to
      * block 0x2A would return blocks 0x2A, 0x2B, 0x00, 0x01.
-     * <p>This requires that the tag be connected.
      *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param pageOffset index of first page to read, starting from 0
      * @return 4 pages (16 bytes)
-     * @throws IOException
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
      */
     public byte[] readPages(int pageOffset) throws IOException {
-        validatePageOffset(pageOffset);
+        validatePageIndex(pageOffset);
         checkConnected();
 
         byte[] cmd = { 0x30, (byte) pageOffset};
@@ -126,15 +151,21 @@
 
     /**
      * Write 1 page (4 bytes).
-     * <p>The MIFARE Ultralight protocol always writes 1 page at a time.
-     * <p>This requires that the tag be connected.
      *
-     * @param pageOffset The offset of the page to write
-     * @param data The data to write
-     * @throws IOException
+     * <p>The MIFARE Ultralight protocol always writes 1 page at a time, to
+     * minimize EEPROM write cycles.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param pageOffset index of page to write, starting from 0
+     * @param data 4 bytes to write
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
      */
     public void writePage(int pageOffset, byte[] data) throws IOException {
-        validatePageOffset(pageOffset);
+        validatePageIndex(pageOffset);
         checkConnected();
 
         byte[] cmd = new byte[data.length + 2];
@@ -147,28 +178,29 @@
 
     /**
      * Send raw NfcA data to a tag and receive the response.
-     * <p>
-     * This method will block until the response is received. It can be canceled
-     * with {@link #close}.
-     * <p>Requires {@link android.Manifest.permission#NFC} permission.
-     * <p>This requires a that the tag be connected.
      *
-     * @param data bytes to send
-     * @return bytes received in response
-     * @throws IOException if the target is lost or connection closed
+     * <p>This is equivalent to connecting to this tag via {@link NfcA}
+     * and calling {@link NfcA#transceive}. Note that all MIFARE Classic
+     * tags are based on {@link NfcA} technology.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @see NfcA#transceive
      */
     public byte[] transceive(byte[] data) throws IOException {
         return transceive(data, true);
     }
 
-    private static void validatePageOffset(int pageOffset) {
+    private static void validatePageIndex(int pageIndex) {
         // Do not be too strict on upper bounds checking, since some cards
         // may have more addressable memory than they report.
         // Note that issuing a command to an out-of-bounds block is safe - the
         // tag will wrap the read to an addressable area. This validation is a
         // helper to guard against obvious programming mistakes.
-        if (pageOffset < 0 || pageOffset >= MAX_PAGE_COUNT) {
-            throw new IndexOutOfBoundsException("page out of bounds: " + pageOffset);
+        if (pageIndex < 0 || pageIndex >= MAX_PAGE_COUNT) {
+            throw new IndexOutOfBoundsException("page out of bounds: " + pageIndex);
         }
     }
 }
diff --git a/core/java/android/nfc/tech/Ndef.java b/core/java/android/nfc/tech/Ndef.java
index 39ff282..0467473 100644
--- a/core/java/android/nfc/tech/Ndef.java
+++ b/core/java/android/nfc/tech/Ndef.java
@@ -22,6 +22,7 @@
 import android.nfc.NdefMessage;
 import android.nfc.NfcAdapter;
 import android.nfc.Tag;
+import android.nfc.TagLostException;
 import android.os.Bundle;
 import android.os.RemoteException;
 import android.util.Log;
@@ -29,11 +30,41 @@
 import java.io.IOException;
 
 /**
- * A high-level connection to a {@link Tag} using one of the NFC type 1, 2, 3, or 4 technologies
- * to interact with NDEF data. MiFare Classic cards that present NDEF data may also be used
- * via this class. To determine the exact technology being used call {@link #getType()}
+ * Provides access to NDEF content and operations on a {@link Tag}.
  *
- * <p>You can acquire this kind of connection with {@link #get}.
+ * <p>Acquire a {@link Ndef} object using {@link #get}.
+ *
+ * <p>NDEF is an NFC Forum data format. The data formats are implemented in
+ * {@link android.nfc.NdefMessage} and
+ * {@link android.nfc.NdefRecord}. This class provides methods to
+ * retrieve and modify the {@link android.nfc.NdefMessage}
+ * on a tag.
+ *
+ * <p>There are currently four NFC Forum standardized tag types that can be
+ * formatted to contain NDEF data.
+ * <ul>
+ * <li>NFC Forum Type 1 Tag ({@link #NFC_FORUM_TYPE_1}), such as the Innovision Topaz
+ * <li>NFC Forum Type 2 Tag ({@link #NFC_FORUM_TYPE_2}), such as the NXP Mifare Ultralight
+ * <li>NFC Forum Type 3 Tag ({@link #NFC_FORUM_TYPE_3}), such as Sony Felica
+ * <li>NFC Forum Type 4 Tag ({@link #NFC_FORUM_TYPE_4}), such as NXP MIFARE Desfire
+ * </ul>
+ * It is mandatory for all Android devices with NFC to correctly enumerate
+ * {@link Ndef} on NFC Forum Tag Types 1-4, and implement all NDEF operations
+ * as defined in this class.
+ *
+ * <p>Some vendors have there own well defined specifications for storing NDEF data
+ * on tags that do not fall into the above categories. Android devices with NFC
+ * should enumerate and implement {@link Ndef} under these vendor specifications
+ * where possible, but it is not mandatory. {@link #getType} returns a String
+ * describing this specification, for example {@link #MIFARE_CLASSIC} is
+ * <code>com.nxp.ndef.mifareclassic</code>.
+ *
+ * <p>Android devices that support MIFARE Classic must also correctly
+ * implement {@link Ndef} on MIFARE Classic tags formatted to NDEF.
+ *
+ * <p>For guaranteed compatibility across all Android devices with NFC, it is
+ * recommended to use NFC Forum Types 1-4 in new deployments of NFC tags
+ * with NDEF payload. Vendor NDEF formats will not work on all Android devices.
  *
  * <p class="note"><strong>Note:</strong>
  * Use of this class requires the {@link android.Manifest.permission#NFC}
@@ -77,14 +108,15 @@
     /** @hide */
     public static final String UNKNOWN = "android.ndef.unknown";
 
+    /** NFC Forum Tag Type 1 */
     public static final String NFC_FORUM_TYPE_1 = "org.nfcforum.ndef.type1";
-
+    /** NFC Forum Tag Type 2 */
     public static final String NFC_FORUM_TYPE_2 = "org.nfcforum.ndef.type2";
-
+    /** NFC Forum Tag Type 4 */
     public static final String NFC_FORUM_TYPE_3 = "org.nfcforum.ndef.type3";
-
+    /** NFC Forum Tag Type 4 */
     public static final String NFC_FORUM_TYPE_4 = "org.nfcforum.ndef.type4";
-
+    /** NDEF on MIFARE Classic */
     public static final String MIFARE_CLASSIC = "com.nxp.ndef.mifareclassic";
 
     private final int mMaxNdefSize;
@@ -93,11 +125,19 @@
     private final int mNdefType;
 
     /**
-     * Returns an instance of this tech for the given tag. If the tag doesn't support
-     * this tech type null is returned.
+     * Get an instance of {@link Ndef} for the given tag.
      *
-     * @param tag The tag to get the tech from
+     * <p>Returns null if {@link Ndef} was not enumerated in {@link Tag#getTechList}.
+     * This indicates the tag is not NDEF formatted, or that this tag
+     * is NDEF formatted but under a vendor specification that this Android
+     * device does not implement.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @param tag an MIFARE Classic compatible tag
+     * @return MIFARE Classic object
      */
+
     public static Ndef get(Tag tag) {
         if (!tag.hasTech(TagTechnology.NDEF)) return null;
         try {
@@ -126,22 +166,29 @@
     }
 
     /**
-     * Get the primary NDEF message on this tag. This data is read at discovery time
-     * and does not require a connection.
+     * Get the {@link NdefMessage} that was read from the tag at discovery time.
+     *
+     * <p>If the NDEF Message is modified by an I/O operation then it
+     * will not be updated here, this function only returns what was discovered
+     * when the tag entered the field.
+     * <p>Does not cause any RF activity and does not block.
+     * @return NDEF Message read from the tag at discovery time
      */
     public NdefMessage getCachedNdefMessage() {
         return mNdefMsg;
     }
 
     /**
-     * Get NDEF tag type.
+     * Get the NDEF tag type.
+     *
      * <p>Returns one of {@link #NFC_FORUM_TYPE_1}, {@link #NFC_FORUM_TYPE_2},
      * {@link #NFC_FORUM_TYPE_3}, {@link #NFC_FORUM_TYPE_4},
-     * {@link #MIFARE_CLASSIC} or another NDEF tag type that is not yet in the
-     * Android API.
-     * <p>Android devices with NFC support must always correctly enumerate
-     * NFC Forum tag types, and may optionally enumerate
-     * {@link #MIFARE_CLASSIC} since it requires proprietary technology.
+     * {@link #MIFARE_CLASSIC} or another NDEF tag type that has not yet been
+     * formalized in this Android API.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return a string representing the NDEF tag type
      */
     public String getType() {
         switch (mNdefType) {
@@ -161,25 +208,44 @@
     }
 
     /**
-     * Get maximum NDEF message size in bytes
+     * Get the maximum NDEF message size in bytes.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return size in bytes
      */
     public int getMaxSize() {
         return mMaxNdefSize;
     }
 
     /**
-     * Provides a hint on whether writes are likely to succeed.
+     * Determine if the tag is writable.
+     *
+     * <p>NFC Forum tags can be in read-only or read-write states.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
      * <p>Requires {@link android.Manifest.permission#NFC} permission.
-     * @return true if write is likely to succeed
+     *
+     * @return true if the tag is writable
      */
     public boolean isWritable() {
         return (mCardState == NDEF_MODE_READ_WRITE);
     }
 
-    // Methods that require connect()
     /**
-     * Get the primary NDEF message on this tag. This data is read actively
-     * and requires a connection.
+     * Read the current {@link android.nfc.NdefMessage} on this tag.
+     *
+     * <p>This always reads the current NDEF Message stored on the tag.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @return the NDEF Message, never null
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
+     * @throws FormatException if the NDEF Message on the tag is malformed
      */
     public NdefMessage getNdefMessage() throws IOException, FormatException {
         checkConnected();
@@ -212,8 +278,16 @@
     }
 
     /**
-     * Overwrite the primary NDEF message
-     * @throws IOException
+     * Overwrite the {@link NdefMessage} on this tag.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param msg the NDEF Message to write, must not be null
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
+     * @throws FormatException if the NDEF Message to write is malformed
      */
     public void writeNdefMessage(NdefMessage msg) throws IOException, FormatException {
         checkConnected();
@@ -244,8 +318,11 @@
     }
 
     /**
-     * Indicates whether a tag can be made read-only with
-     * {@link #makeReadOnly()}
+     * Indicates whether a tag can be made read-only with {@link #makeReadOnly()}.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return true if it is possible to make this tag read-only
      */
     public boolean canMakeReadOnly() {
         if (mNdefType == TYPE_1 || mNdefType == TYPE_2) {
@@ -256,11 +333,20 @@
     }
 
     /**
-     * Sets the CC field to indicate this tag is read-only
-     * and permanently sets the lock bits to prevent any further NDEF
-     * modifications.
-     * This is a one-way process and can not be reverted!
-     * @throws IOException
+     * Make a tag read-only.
+     *
+     * <p>This sets the CC field to indicate the tag is read-only,
+     * and where possible permanently sets the lock bits to prevent
+     * any further modification of the memory.
+     * <p>This is a one-way process and cannot be reverted!
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @return true on success, false if it is not possible to make this tag read-only
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
      */
     public boolean makeReadOnly() throws IOException {
         checkConnected();
diff --git a/core/java/android/nfc/tech/NdefFormatable.java b/core/java/android/nfc/tech/NdefFormatable.java
index e2828b5..f667b58 100644
--- a/core/java/android/nfc/tech/NdefFormatable.java
+++ b/core/java/android/nfc/tech/NdefFormatable.java
@@ -22,15 +22,24 @@
 import android.nfc.NdefMessage;
 import android.nfc.NfcAdapter;
 import android.nfc.Tag;
+import android.nfc.TagLostException;
 import android.os.RemoteException;
 import android.util.Log;
 
 import java.io.IOException;
 
 /**
- * An interface to a {@link Tag} allowing to format the tag as NDEF.
+ * Provide access to NDEF format operations on a {@link Tag}.
  *
- * <p>You can acquire this kind of connection with {@link #get}.
+ * <p>Acquire a {@link NdefFormatable} object using {@link #get}.
+ *
+ * <p>Android devices with NFC must only enumerate and implement this
+ * class for tags for which it can format to NDEF.
+ *
+ * <p>Unfortunately the procedures to convert unformated tags to NDEF formatted
+ * tags are not specified by NFC Forum, and are not generally well-known. So
+ * there is no mandatory set of tags for which all Android devices with NFC
+ * must support {@link NdefFormatable}.
  *
  * <p class="note"><strong>Note:</strong>
  * Use of this class requires the {@link android.Manifest.permission#NFC}
@@ -40,10 +49,13 @@
     private static final String TAG = "NFC";
 
     /**
-     * Returns an instance of this tech for the given tag. If the tag doesn't support
-     * this tech type null is returned.
+     * Get an instance of {@link NdefFormatable} for the given tag.
+     * <p>Does not cause any RF activity and does not block.
+     * <p>Returns null if {@link NdefFormatable} was not enumerated in {@link Tag#getTechList}.
+     * This indicates the tag is not NDEF formatable by this Android device.
      *
-     * @param tag The tag to get the tech from
+     * @param tag an NDEF formatable tag
+     * @return NDEF formatable object
      */
     public static NdefFormatable get(Tag tag) {
         if (!tag.hasTech(TagTechnology.NDEF_FORMATABLE)) return null;
@@ -63,20 +75,40 @@
     }
 
     /**
-     * Formats a tag as NDEF, if possible. You may supply a first
-     * NdefMessage to be written on the tag.
-     * <p>Either all steps succeed, or an IOException is thrown if any one step
-     * fails.
+     * Format a tag as NDEF, and write a {@link NdefMessage}.
+     *
+     * <p>This is a multi-step process, an IOException is thrown
+     * if any one step fails.
+     * <p>The card is left in a read-write state after this operation.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param firstMessage the NDEF message to write after formatting
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
+     * @throws FormatException if the NDEF Message to write is malformed
      */
     public void format(NdefMessage firstMessage) throws IOException, FormatException {
         format(firstMessage, false);
     }
 
     /**
-     * Formats a tag as NDEF, if possible. You may supply a first
-     * NdefMessage to be written on the tag.
-     * <p>Either all steps succeed, or an IOException is thrown if any one step
-     * fails.
+     * Formats a tag as NDEF, write a {@link NdefMessage}, and make read-only.
+     *
+     * <p>This is a multi-step process, an IOException is thrown
+     * if any one step fails.
+     * <p>The card is left in a read-only state if this method returns successfully.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
+     *
+     * @param firstMessage the NDEF message to write after formatting
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or the operation is canceled
+     * @throws FormatException if the NDEF Message to write is malformed
      */
     public void formatReadOnly(NdefMessage firstMessage) throws IOException, FormatException {
         format(firstMessage, true);
diff --git a/core/java/android/nfc/tech/NfcA.java b/core/java/android/nfc/tech/NfcA.java
index 24badc4..93d8510 100644
--- a/core/java/android/nfc/tech/NfcA.java
+++ b/core/java/android/nfc/tech/NfcA.java
@@ -23,18 +23,11 @@
 import java.io.IOException;
 
 /**
- * A low-level connection to a {@link Tag} using the NFC-A technology, also known as
- * ISO1443-3A.
+ * Provides access to NFC-A (ISO 14443-3A) properties and I/O operations on a {@link Tag}.
  *
- * <p>You can acquire this kind of connection with {@link #get}.
- * Use this class to send and receive data with {@link #transceive transceive()}.
- *
- * <p>Applications must implement their own protocol stack on top of
- * {@link #transceive transceive()}.
- *
- * <p class="note"><strong>Note:</strong>
- * Use of this class requires the {@link android.Manifest.permission#NFC}
- * permission.
+ * <p>Acquire a {@link NfcA} object using {@link #get}.
+ * <p>The primary NFC-A I/O operation is {@link #transceive}. Applications must
+ * implement their own protocol stack on top of {@link #transceive}.
  */
 public final class NfcA extends BasicTagTechnology {
     /** @hide */
@@ -46,10 +39,13 @@
     private byte[] mAtqa;
 
     /**
-     * Returns an instance of this tech for the given tag. If the tag doesn't support
-     * this tech type null is returned.
+     * Get an instance of {@link NfcA} for the given tag.
+     * <p>Returns null if {@link NfcA} was not enumerated in {@link Tag#getTechList}.
+     * This indicates the tag does not support NFC-A.
+     * <p>Does not cause any RF activity and does not block.
      *
-     * @param tag The tag to get the tech from
+     * @param tag an NFC-A compatible tag
+     * @return NFC-A object
      */
     public static NfcA get(Tag tag) {
         if (!tag.hasTech(TagTechnology.NFC_A)) return null;
@@ -69,29 +65,44 @@
     }
 
     /**
-     * Returns the ATQA/SENS_RES bytes discovered at tag discovery.
+     * Return the ATQA/SENS_RES bytes from tag discovery.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return ATQA/SENS_RES bytes
      */
     public byte[] getAtqa() {
         return mAtqa;
     }
 
     /**
-     * Returns the SAK/SEL_RES discovered at tag discovery.
+     * Return the SAK/SEL_RES bytes from tag discovery.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return SAK bytes
      */
     public short getSak() {
         return mSak;
     }
 
     /**
-     * Send data to a tag and receive the response.
-     * <p>
-     * This method will block until the response is received. It can be canceled
-     * with {@link #close}.
-     * <p>Requires {@link android.Manifest.permission#NFC} permission.
+     * Send raw NFC-A commands to the tag and receive the response.
+     *
+     * <p>Applications must not append the EoD (CRC) to the payload,
+     * it will be automatically calculated.
+     * <p>Applications must only send commands that are complete bytes,
+     * for example a SENS_REQ is not possible (these are used to
+     * manage tag polling and initialization).
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
      *
      * @param data bytes to send
      * @return bytes received in response
-     * @throws IOException if the target is lost or connection closed
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or this operation is canceled
      */
     public byte[] transceive(byte[] data) throws IOException {
         return transceive(data, true);
diff --git a/core/java/android/nfc/tech/NfcB.java b/core/java/android/nfc/tech/NfcB.java
index abeef32..29246ee 100644
--- a/core/java/android/nfc/tech/NfcB.java
+++ b/core/java/android/nfc/tech/NfcB.java
@@ -23,18 +23,11 @@
 import java.io.IOException;
 
 /**
- * A low-level connection to a {@link Tag} using the NFC-B technology, also known as
- * ISO1443-3B.
+ * Provides access to NFC-B (ISO 14443-3B) properties and I/O operations on a {@link Tag}.
  *
- * <p>You can acquire this kind of connection with {@link #get}.
- * Use this class to send and receive data with {@link #transceive transceive()}.
- *
- * <p>Applications must implement their own protocol stack on top of
- * {@link #transceive transceive()}.
- *
- * <p class="note"><strong>Note:</strong>
- * Use of this class requires the {@link android.Manifest.permission#NFC}
- * permission.
+ * <p>Acquire a {@link NfcB} object using {@link #get}.
+ * <p>The primary NFC-B I/O operation is {@link #transceive}. Applications must
+ * implement their own protocol stack on top of {@link #transceive}.
  */
 public final class NfcB extends BasicTagTechnology {
     /** @hide */
@@ -46,10 +39,13 @@
     private byte[] mProtInfo;
 
     /**
-     * Returns an instance of this tech for the given tag. If the tag doesn't support
-     * this tech type null is returned.
+     * Get an instance of {@link NfcB} for the given tag.
+     * <p>Returns null if {@link NfcB} was not enumerated in {@link Tag#getTechList}.
+     * This indicates the tag does not support NFC-B.
+     * <p>Does not cause any RF activity and does not block.
      *
-     * @param tag The tag to get the tech from
+     * @param tag an NFC-B compatible tag
+     * @return NFC-B object
      */
     public static NfcB get(Tag tag) {
         if (!tag.hasTech(TagTechnology.NFC_B)) return null;
@@ -69,31 +65,43 @@
     }
 
     /**
-     * Returns the Application Data bytes from the ATQB/SENSB_RES
-     * bytes discovered at tag discovery.
+     * Return the Application Data bytes from ATQB/SENSB_RES at tag discovery.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return Application Data bytes from ATQB/SENSB_RES bytes
      */
     public byte[] getApplicationData() {
         return mAppData;
     }
 
     /**
-     * Returns the Protocol Info bytes from the ATQB/SENSB_RES
-     * bytes discovered at tag discovery.
+     * Return the Protocol Info bytes from ATQB/SENSB_RES at tag discovery.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return Protocol Info bytes from ATQB/SENSB_RES bytes
      */
     public byte[] getProtocolInfo() {
         return mProtInfo;
     }
 
     /**
-     * Send data to a tag and receive the response.
-     * <p>
-     * This method will block until the response is received. It can be canceled
-     * with {@link #close}.
-     * <p>Requires {@link android.Manifest.permission#NFC} permission.
+     * Send raw NFC-B commands to the tag and receive the response.
+     *
+     * <p>Applications must not append the EoD (CRC) to the payload,
+     * it will be automatically calculated.
+     * <p>Applications must not send commands that manage the polling
+     * loop and initialization (SENSB_REQ, SLOT_MARKER etc).
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
      *
      * @param data bytes to send
      * @return bytes received in response
-     * @throws IOException if the target is lost or connection closed
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or this operation is canceled
      */
     public byte[] transceive(byte[] data) throws IOException {
         return transceive(data, true);
diff --git a/core/java/android/nfc/tech/NfcF.java b/core/java/android/nfc/tech/NfcF.java
index f617739..27d1b57 100644
--- a/core/java/android/nfc/tech/NfcF.java
+++ b/core/java/android/nfc/tech/NfcF.java
@@ -23,18 +23,11 @@
 import java.io.IOException;
 
 /**
- * A low-level connection to a {@link Tag} using the NFC-F technology, also known as
- * JIS6319-4.
+ * Provides access to NFC-F (JIS 6319-4) properties and I/O operations on a {@link Tag}.
  *
- * <p>You can acquire this kind of connection with {@link #get}.
- * Use this class to send and receive data with {@link #transceive transceive()}.
- *
- * <p>Applications must implement their own protocol stack on top of
- * {@link #transceive transceive()}.
- *
- * <p class="note"><strong>Note:</strong>
- * Use of this class requires the {@link android.Manifest.permission#NFC}
- * permission.
+ * <p>Acquire a {@link NfcF} object using {@link #get}.
+ * <p>The primary NFC-F I/O operation is {@link #transceive}. Applications must
+ * implement their own protocol stack on top of {@link #transceive}.
  */
 public final class NfcF extends BasicTagTechnology {
     /** @hide */
@@ -46,10 +39,13 @@
     private byte[] mManufacturer = null;
 
     /**
-     * Returns an instance of this tech for the given tag. If the tag doesn't support
-     * this tech type null is returned.
+     * Get an instance of {@link NfcF} for the given tag.
+     * <p>Returns null if {@link NfcF} was not enumerated in {@link Tag#getTechList}.
+     * This indicates the tag does not support NFC-F.
+     * <p>Does not cause any RF activity and does not block.
      *
-     * @param tag The tag to get the tech from
+     * @param tag an NFC-F compatible tag
+     * @return NFC-F object
      */
     public static NfcF get(Tag tag) {
         if (!tag.hasTech(TagTechnology.NFC_F)) return null;
@@ -70,24 +66,42 @@
         }
     }
 
+    /**
+     * Return the System Code bytes from tag discovery.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return System Code bytes
+     */
     public byte[] getSystemCode() {
       return mSystemCode;
     }
 
+    /**
+     * Return the Manufacturer bytes from tag discovery.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return Manufacturer bytes
+     */
     public byte[] getManufacturer() {
       return mManufacturer;
     }
 
     /**
-     * Send data to a tag and receive the response.
-     * <p>
-     * This method will block until the response is received. It can be canceled
-     * with {@link #close}.
-     * <p>Requires {@link android.Manifest.permission#NFC} permission.
+     * Send raw NFC-F commands to the tag and receive the response.
+     *
+     * <p>Applications must not append the SoD (length) or EoD (CRC) to the payload,
+     * it will be automatically calculated.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
      *
      * @param data bytes to send
      * @return bytes received in response
-     * @throws IOException if the target is lost or connection closed
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or this operation is canceled
      */
     public byte[] transceive(byte[] data) throws IOException {
         return transceive(data, true);
diff --git a/core/java/android/nfc/tech/NfcV.java b/core/java/android/nfc/tech/NfcV.java
index 8e1f066..99dc318 100644
--- a/core/java/android/nfc/tech/NfcV.java
+++ b/core/java/android/nfc/tech/NfcV.java
@@ -23,18 +23,11 @@
 import java.io.IOException;
 
 /**
- * A low-level connection to a {@link Tag} using NFC vicinity technology, also known as
- * ISO15693.
+ * Provides access to NFC-V (ISO 15693) properties and I/O operations on a {@link Tag}.
  *
- * <p>You can acquire this kind of connection with {@link #get}.
- * Use this class to send and receive data with {@link #transceive transceive()}.
- *
- * <p>Applications must implement their own protocol stack on top of
- * {@link #transceive transceive()}.
- *
- * <p class="note"><strong>Note:</strong>
- * Use of this class requires the {@link android.Manifest.permission#NFC}
- * permission.
+ * <p>Acquire a {@link NfcV} object using {@link #get}.
+ * <p>The primary NFC-V I/O operation is {@link #transceive}. Applications must
+ * implement their own protocol stack on top of {@link #transceive}.
  */
 public final class NfcV extends BasicTagTechnology {
     /** @hide */
@@ -47,10 +40,13 @@
     private byte mDsfId;
 
     /**
-     * Returns an instance of this tech for the given tag. If the tag doesn't support
-     * this tech type null is returned.
+     * Get an instance of {@link NfcV} for the given tag.
+     * <p>Returns null if {@link NfcV} was not enumerated in {@link Tag#getTechList}.
+     * This indicates the tag does not support NFC-V.
+     * <p>Does not cause any RF activity and does not block.
      *
-     * @param tag The tag to get the tech from
+     * @param tag an NFC-V compatible tag
+     * @return NFC-V object
      */
     public static NfcV get(Tag tag) {
         if (!tag.hasTech(TagTechnology.NFC_V)) return null;
@@ -69,24 +65,43 @@
         mDsfId = extras.getByte(EXTRA_DSFID);
     }
 
+    /**
+     * Return the Response Flag bytes from tag discovery.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return Response Flag bytes
+     */
     public byte getResponseFlags() {
         return mRespFlags;
     }
 
+    /**
+     * Return the DSF ID bytes from tag discovery.
+     *
+     * <p>Does not cause any RF activity and does not block.
+     *
+     * @return DSF ID bytes
+     */
     public byte getDsfId() {
         return mDsfId;
     }
 
     /**
-     * Send data to a tag and receive the response.
-     * <p>
-     * This method will block until the response is received. It can be canceled
-     * with {@link #close}.
-     * <p>Requires {@link android.Manifest.permission#NFC} permission.
+     * Send raw NFC-V commands to the tag and receive the response.
+     *
+     * <p>Applications must not append the CRC to the payload,
+     * it will be automatically calculated. The application does
+     * provide FLAGS, CMD and PARAMETER bytes.
+     *
+     * <p>This is an I/O operation and will block until complete. It must
+     * not be called from the main application thread. A blocked call will be canceled with
+     * {@link IOException} if {@link #close} is called from another thread.
      *
      * @param data bytes to send
      * @return bytes received in response
-     * @throws IOException if the target is lost or connection closed
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or this operation is canceled
      */
     public byte[] transceive(byte[] data) throws IOException {
         return transceive(data, true);
diff --git a/core/java/android/nfc/tech/TagTechnology.java b/core/java/android/nfc/tech/TagTechnology.java
index 50df865..be6ccd0 100644
--- a/core/java/android/nfc/tech/TagTechnology.java
+++ b/core/java/android/nfc/tech/TagTechnology.java
@@ -21,6 +21,61 @@
 import java.io.Closeable;
 import java.io.IOException;
 
+/**
+ * {@link TagTechnology} is an interface to a technology in a {@link Tag}.
+ * <p>
+ * Obtain a {@link TagTechnology} implementation by calling the static method <code>get()</code>
+ * on the implementation class.
+ * <p>
+ * NFC tags are based on a number of independently developed technologies and offer a
+ * wide range of capabilities. The
+ * {@link TagTechnology} implementations provide access to these different
+ * technologies and capabilities. Some sub-classes map to technology
+ * specification (for example {@link NfcA}, {@link IsoDep}, others map to
+ * pseudo-technologies or capabilities (for example {@link Ndef}, {@link NdefFormatable}).
+ * <p>
+ * It is mandatory for all Android NFC devices to provide the following
+ * {@link TagTechnology} implementations.
+ * <ul>
+ * <li>{@link NfcA} (also known as ISO 14443-3A)
+ * <li>{@link NfcB} (also known as ISO 14443-3B)
+ * <li>{@link NfcF} (also known as JIS 6319-4)
+ * <li>{@link NfcV} (also known as ISO 15693)
+ * <li>{@link IsoDep}
+ * <li>{@link Ndef} on NFC Forum Type 1, Type 2, Type 3 or Type 4 compliant tags
+ * </ul>
+ * It is optional for Android NFC devices to provide the following
+ * {@link TagTechnology} implementations. If it is not provided, the
+ * Android device will never enumerate that class via {@link Tag#getTechList}.
+ * <ul>
+ * <li>{@link MifareClassic}
+ * <li>{@link MifareUltralight}
+ * <li>{@link NdefFormatable} must only be enumerated on tags for which this Android device
+ * is capable of formatting. Proprietary knowledge is often required to format a tag
+ * to make it NDEF compatible.
+ * </ul>
+ * <p>
+ * {@link TagTechnology} implementations provide methods that fall into two classes:
+ * <em>cached getters</em> and <em>I/O operations</em>.
+ * <h4>Cached getters</h4>
+ * These methods (usually prefixed by <code>get</code> or <code>is</code>) return
+ * properties of the tag, as determined at discovery time. These methods will never
+ * block or cause RF activity, and do not require {@link #connect} to have been called.
+ * They also never update, for example if a property is changed by an I/O operation with a tag
+ * then the cached getter will still return the result from tag discovery time.
+ * <h4>I/O operations</h4>
+ * I/O operations may require RF activity, and may block. They have the following semantics.
+ * <ul>
+ * <li>{@link #connect} must be called before using any other I/O operation.
+ * <li>{@link #close} must be called after completing I/O operations with a
+ * {@link TagTechnology}, and it will cancel all other blocked I/O operations on other threads
+ * (including {@link #connect} with {@link IOException}.
+ * <li>Only one {@link TagTechnology} can be connected at a time. Other calls to
+ * {@link #connect} will return {@link IOException}.
+ * <li>I/O operations may block, and should never be called on the main application
+ * thread.
+ * </ul>
+ */
 public interface TagTechnology extends Closeable {
     /**
      * This technology is an instance of {@link NfcA}.
@@ -90,22 +145,22 @@
     public static final int MIFARE_ULTRALIGHT = 9;
 
     /**
-     * Get the {@link Tag} object this technology came from.
+     * Get the {@link Tag} object backing this {@link TagTechnology} object.
+     * @return the {@link Tag} backing this {@link TagTechnology} object.
      */
     public Tag getTag();
 
     /**
-     * Opens a connection to the {@link Tag} enabling interactive commands. The command set
-     * varies by the technology type.
+     * Enable I/O operations to the tag from this {@link TagTechnology} object.
+     * <p>May cause RF activity and may block. Must not be called
+     * from the main application thread. A blocked call will be canceled with
+     * {@link IOException} by calling {@link #close} from another thread.
+     * <p>Only one {@link TagTechnology} object can be connected to a {@link Tag} at a time.
+     * <p>Applications must call {@link #close} when I/O operations are complete.
      *
-     * <p>This method blocks until the connection has been established.
-     *
-     * <p>A call to {@link #close} from another thread will cancel a blocked call and cause an
-     * IOException to be thrown on the thread that is blocked.
-     *
-     * @see #reconnect()
      * @see #close()
-     * @throws IOException if the target is lost, or connect canceled
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or connect is canceled
      */
     public void connect() throws IOException;
 
@@ -113,40 +168,34 @@
      * Re-connect to the {@link Tag} associated with this connection. Reconnecting to a tag can be
      * used to reset the state of the tag itself.
      *
-     * <p>This method blocks until the connection is re-established.
-     *
-     * <p>A call to {@link #close} from another thread will cancel a blocked call and cause an
-     * IOException to be thrown on the thread that is blocked.
+     * <p>May cause RF activity and may block. Must not be called
+     * from the main application thread. A blocked call will be canceled with
+     * {@link IOException} by calling {@link #close} from another thread.
      *
      * @see #connect()
      * @see #close()
-     * @throws IOException
+     * @throws TagLostException if the tag leaves the field
+     * @throws IOException if there is an I/O failure, or connect is canceled
      * @hide
      */
     public void reconnect() throws IOException;
 
     /**
-     * Closes the connection to the {@link Tag}. This call is non-blocking and causes all blocking
-     * operations such as {@link #connect} to be canceled and immediately throw
-     * {@link java.io.IOException} on the thread that is blocked.
-     *
-     * <p>
-     * Once this method is called, this object cannot be re-used and should be discarded. Further
-     * calls to {@link #connect} will fail.
+     * Disable I/O operations to the tag from this {@link TagTechnology} object, and release resources.
+     * <p>Also causes all blocked I/O operations on other thread to be canceled and
+     * return with {@link IOException}.
      *
      * @see #connect()
-     * @see #reconnect()
      */
     public void close() throws IOException;
 
     /**
-     * Helper to indicate if {@link #connect} has succeeded.
-     * <p>
-     * Does not cause RF activity, and does not block.
-     * @return true if {@link #connect} has completed successfully and the {@link Tag} is believed
-     * to be within range. Applications must still handle {@link java.io.IOException}
-     * while using methods that require a connection in case the connection is lost after this
-     * method returns.
+     * Helper to indicate if I/O operations should be possible.
+     *
+     * <p>Returns true if {@link #connect} has completed, and {@link #close} has not been
+     * called, and the {@link Tag} is not known to be out of range.
+     * <p>Does not cause RF activity, and does not block.
+     * @return true if I/O operations should be possible
      */
     public boolean isConnected();
 }
diff --git a/core/java/android/preference/SeekBarPreference.java b/core/java/android/preference/SeekBarPreference.java
index 658c2a7..037fb41 100644
--- a/core/java/android/preference/SeekBarPreference.java
+++ b/core/java/android/preference/SeekBarPreference.java
@@ -29,25 +29,30 @@
  */
 public class SeekBarPreference extends DialogPreference {
     private static final String TAG = "SeekBarPreference";
-    
+
     private Drawable mMyIcon;
 
     public SeekBarPreference(Context context, AttributeSet attrs) {
         super(context, attrs);
 
         setDialogLayoutResource(com.android.internal.R.layout.seekbar_dialog);
-        setPositiveButtonText(android.R.string.ok);
-        setNegativeButtonText(android.R.string.cancel);
-        
+        createActionButtons();
+
         // Steal the XML dialogIcon attribute's value
         mMyIcon = getDialogIcon();
         setDialogIcon(null);
     }
 
+    // Allow subclasses to override the action buttons
+    public void createActionButtons() {
+        setPositiveButtonText(android.R.string.ok);
+        setNegativeButtonText(android.R.string.cancel);
+    }
+
     @Override
     protected void onBindDialogView(View view) {
         super.onBindDialogView(view);
-        
+
         final ImageView iconView = (ImageView) view.findViewById(android.R.id.icon);
         if (mMyIcon != null) {
             iconView.setImageDrawable(mMyIcon);
diff --git a/core/java/android/preference/VolumePreference.java b/core/java/android/preference/VolumePreference.java
index 50ca71e..3b12780 100644
--- a/core/java/android/preference/VolumePreference.java
+++ b/core/java/android/preference/VolumePreference.java
@@ -236,14 +236,11 @@
             @Override
             public void onChange(boolean selfChange) {
                 super.onChange(selfChange);
-                if (mSeekBar != null) {
-                    int volume = System.getInt(mContext.getContentResolver(),
-                            System.VOLUME_SETTINGS[mStreamType], -1);
-                    // Works around an atomicity problem with volume updates
-                    // TODO: Fix the actual issue, probably in AudioService
-                    if (volume >= 0) {
-                        mSeekBar.setProgress(volume);
-                    }
+                if (mSeekBar != null && mAudioManager != null) {
+                    int volume = mAudioManager.isStreamMute(mStreamType) ?
+                            mAudioManager.getLastAudibleStreamVolume(mStreamType)
+                            : mAudioManager.getStreamVolume(mStreamType);
+                    mSeekBar.setProgress(volume);
                 }
             }
         };
diff --git a/core/java/android/server/BluetoothEventLoop.java b/core/java/android/server/BluetoothEventLoop.java
index e9f28fa..3316ea5 100644
--- a/core/java/android/server/BluetoothEventLoop.java
+++ b/core/java/android/server/BluetoothEventLoop.java
@@ -660,8 +660,7 @@
              } else {
                  Log.i(TAG, "Rejecting incoming HID connection from " + address);
              }
-        } else if (BluetoothUuid.isBnep(uuid) || BluetoothUuid.isNap(uuid) &&
-                mBluetoothService.allowIncomingTethering()){
+        } else if (BluetoothUuid.isBnep(uuid) && mBluetoothService.allowIncomingTethering()){
             authorized = true;
         } else {
             Log.i(TAG, "Rejecting incoming " + deviceUuid + " connection from " + address);
diff --git a/core/java/android/text/InputFilter.java b/core/java/android/text/InputFilter.java
index 2f55677..8d4b08e 100644
--- a/core/java/android/text/InputFilter.java
+++ b/core/java/android/text/InputFilter.java
@@ -88,7 +88,14 @@
             } else if (keep >= end - start) {
                 return null; // keep original
             } else {
-                return source.subSequence(start, start + keep);
+                keep += start;
+                if (Character.isHighSurrogate(source.charAt(keep - 1))) {
+                    --keep;
+                    if (keep == start) {
+                        return "";
+                    }
+                }
+                return source.subSequence(start, keep);
             }
         }
 
diff --git a/core/java/android/util/LruCache.java b/core/java/android/util/LruCache.java
new file mode 100644
index 0000000..b85bf39
--- /dev/null
+++ b/core/java/android/util/LruCache.java
@@ -0,0 +1,249 @@
+/*
+ * 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.util;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * A cache that holds strong references to a limited number of values. Each time
+ * a value is accessed, it is moved to the head of a queue. When a value is
+ * added to a full cache, the value at the end of that queue is evicted and may
+ * become eligible for garbage collection.
+ *
+ * <p>If your cached values hold resources that need to be explicitly released,
+ * override {@link #entryEvicted}. This method is only invoked when values are
+ * evicted. Values replaced by calls to {@link #put} must be released manually.
+ *
+ * <p>If a cache miss should be computed on demand for the corresponding keys,
+ * override {@link #create}. This simplifies the calling code, allowing it to
+ * assume a value will always be returned, even when there's a cache miss.
+ *
+ * <p>By default, the cache size is measured in the number of entries. Override
+ * {@link #sizeOf} to size the cache in different units. For, this cache is
+ * limited to 4MiB of bitmaps:
+ * <pre>   {@code
+ * int cacheSize = 4 * 1024 * 1024; // 4MiB
+ * LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) {
+ *     protected int sizeOf(String key, Bitmap value) {
+ *         return value.getByteCount();
+ *     }
+ * }}</pre>
+ */
+public class LruCache<K, V> {
+    private final LinkedHashMap<K, V> map;
+
+    /** Size of this cache in units. Not necessarily the number of elements. */
+    private int size;
+    private final int maxSize;
+
+    private int putCount;
+    private int createCount;
+    private int evictionCount;
+    private int hitCount;
+    private int missCount;
+
+    /**
+     * @param maxSize for caches that do not override {@link #sizeOf}, this is
+     *     the maximum number of entries in the cache. For all other caches,
+     *     this is the maximum sum of the sizes of the entries in this cache.
+     */
+    public LruCache(int maxSize) {
+        if (maxSize <= 0) {
+            throw new IllegalArgumentException("maxSize <= 0");
+        }
+        this.maxSize = maxSize;
+        this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
+    }
+
+    /**
+     * Returns the value for {@code key} if it exists in the cache or can be
+     * created by {@code #create}. If a value was returned, it is moved to the
+     * head of the queue. This returns null if a value is not cached and cannot
+     * be created.
+     */
+    public synchronized final V get(K key) {
+        if (key == null) {
+            throw new NullPointerException();
+        }
+
+        V result = map.get(key);
+        if (result != null) {
+            hitCount++;
+            return result;
+        }
+
+        missCount++;
+
+        // TODO: release the lock while calling this potentially slow user code
+        result = create(key);
+
+        if (result != null) {
+            createCount++;
+            size += safeSizeOf(key, result);
+            map.put(key, result);
+            trimToSize(maxSize);
+        }
+        return result;
+    }
+
+    /**
+     * Caches {@code value} for {@code key}. The value is moved to the head of
+     * the queue.
+     *
+     * @return the previous value mapped by {@code key}. Although that entry is
+     *     no longer cached, it has not been passed to {@link #entryEvicted}.
+     */
+    public synchronized final V put(K key, V value) {
+        if (key == null || value == null) {
+            throw new NullPointerException();
+        }
+
+        putCount++;
+        size += safeSizeOf(key, value);
+        V previous = map.put(key, value);
+        if (previous != null) {
+            size -= safeSizeOf(key, previous);
+        }
+        trimToSize(maxSize);
+        return previous;
+    }
+
+    private void trimToSize(int maxSize) {
+        while (size > maxSize) {
+            Map.Entry<K, V> toEvict = map.eldest();
+            if (toEvict == null) {
+                break; // map is empty; if size is not 0 then throw an error below
+            }
+
+            K key = toEvict.getKey();
+            V value = toEvict.getValue();
+            map.remove(key);
+            size -= safeSizeOf(key, value);
+            evictionCount++;
+
+            // TODO: release the lock while calling this potentially slow user code
+            entryEvicted(key, value);
+        }
+
+        if (size < 0 || (map.isEmpty() && size != 0)) {
+            throw new IllegalStateException(getClass().getName()
+                    + ".sizeOf() is reporting inconsistent results!");
+        }
+    }
+
+    /**
+     * Called for entries that have reached the tail of the least recently used
+     * queue and are be removed. The default implementation does nothing.
+     */
+    protected void entryEvicted(K key, V value) {}
+
+    /**
+     * Called after a cache miss to compute a value for the corresponding key.
+     * Returns the computed value or null if no value can be computed. The
+     * default implementation returns null.
+     */
+    protected V create(K key) {
+        return null;
+    }
+
+    private int safeSizeOf(K key, V value) {
+        int result = sizeOf(key, value);
+        if (result < 0) {
+            throw new IllegalStateException("Negative size: " + key + "=" + value);
+        }
+        return result;
+    }
+
+    /**
+     * Returns the size of the entry for {@code key} and {@code value} in
+     * user-defined units.  The default implementation returns 1 so that size
+     * is the number of entries and max size is the maximum number of entries.
+     *
+     * <p>An entry's size must not change while it is in the cache.
+     */
+    protected int sizeOf(K key, V value) {
+        return 1;
+    }
+
+    /**
+     * Clear the cache, calling {@link #entryEvicted} on each removed entry.
+     */
+    public synchronized final void evictAll() {
+        trimToSize(-1); // -1 will evict 0-sized elements
+    }
+
+    /**
+     * For caches that do not override {@link #sizeOf}, this is the number of
+     * entries in the cache. For all other caches, this is the sum of the sizes
+     * of the entries in this cache.
+     */
+    public synchronized final int size() {
+        return size;
+    }
+
+    /**
+     * Returns the number of times {@link #get} returned a value.
+     */
+    public synchronized final int hitCount() {
+        return hitCount;
+    }
+
+    /**
+     * Returns the number of times {@link #get} returned null or required a new
+     * value to be created.
+     */
+    public synchronized final int missCount() {
+        return missCount;
+    }
+
+    /**
+     * Returns the number of times {@link #create(Object)} returned a value.
+     */
+    public synchronized final int createCount() {
+        return createCount;
+    }
+
+    /**
+     * Returns the number of times {@link #put} was called.
+     */
+    public synchronized final int putCount() {
+        return putCount;
+    }
+
+    /**
+     * Returns the number of values that have been evicted.
+     */
+    public synchronized final int evictionCount() {
+        return evictionCount;
+    }
+
+    /**
+     * Returns a copy of the current contents of the cache, ordered from least
+     * recently accessed to most recently accessed.
+     */
+    public synchronized final Map<K, V> snapshot() {
+        return new LinkedHashMap<K, V>(map);
+    }
+
+    @Override public synchronized final String toString() {
+        int accesses = hitCount + missCount;
+        int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0;
+        return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",
+                maxSize, hitCount, missCount, hitPercent);
+    }
+}
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 78d3a63..88306cd 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -2237,10 +2237,12 @@
         final View[] children = mChildren;
         for (int i = 0; i < count; i++) {
             final View child = children[i];
-            child.mRecreateDisplayList = (child.mPrivateFlags & INVALIDATED) == INVALIDATED;
-            child.mPrivateFlags &= ~INVALIDATED;
-            child.getDisplayList();
-            child.mRecreateDisplayList = false;
+            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
+                child.mRecreateDisplayList = (child.mPrivateFlags & INVALIDATED) == INVALIDATED;
+                child.mPrivateFlags &= ~INVALIDATED;
+                child.getDisplayList();
+                child.mRecreateDisplayList = false;
+            }
         }
     }
 
diff --git a/core/java/android/view/VolumePanel.java b/core/java/android/view/VolumePanel.java
index e447dbb..3bab29f 100644
--- a/core/java/android/view/VolumePanel.java
+++ b/core/java/android/view/VolumePanel.java
@@ -16,10 +16,17 @@
 
 package android.view;
 
-import android.bluetooth.HeadsetBase;
+import com.android.internal.R;
+
+import android.app.Dialog;
+import android.content.DialogInterface.OnDismissListener;
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.DialogInterface;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.content.res.Resources;
+import android.graphics.drawable.Drawable;
 import android.media.AudioManager;
 import android.media.AudioService;
 import android.media.AudioSystem;
@@ -29,12 +36,16 @@
 import android.os.Handler;
 import android.os.Message;
 import android.os.Vibrator;
-import android.util.Config;
+import android.telephony.TelephonyManager;
 import android.util.Log;
 import android.widget.ImageView;
 import android.widget.ProgressBar;
+import android.widget.SeekBar;
 import android.widget.TextView;
 import android.widget.Toast;
+import android.widget.SeekBar.OnSeekBarChangeListener;
+
+import java.util.HashMap;
 
 /**
  * Handle the volume up and down keys.
@@ -43,7 +54,7 @@
  *
  * @hide
  */
-public class VolumePanel extends Handler
+public class VolumePanel extends Handler implements OnSeekBarChangeListener, View.OnClickListener
 {
     private static final String TAG = "VolumePanel";
     private static boolean LOGD = false;
@@ -68,62 +79,256 @@
     private static final int BEEP_DURATION = 150;
     private static final int MAX_VOLUME = 100;
     private static final int FREE_DELAY = 10000;
+    private static final int TIMEOUT_DELAY = 3000;
 
     private static final int MSG_VOLUME_CHANGED = 0;
     private static final int MSG_FREE_RESOURCES = 1;
     private static final int MSG_PLAY_SOUND = 2;
     private static final int MSG_STOP_SOUNDS = 3;
     private static final int MSG_VIBRATE = 4;
+    private static final int MSG_TIMEOUT = 5;
+    private static final int MSG_RINGER_MODE_CHANGED = 6;
 
-    private static final int RINGTONE_VOLUME_TEXT = com.android.internal.R.string.volume_ringtone;
-    private static final int MUSIC_VOLUME_TEXT = com.android.internal.R.string.volume_music;
-    private static final int INCALL_VOLUME_TEXT = com.android.internal.R.string.volume_call;
-    private static final int ALARM_VOLUME_TEXT = com.android.internal.R.string.volume_alarm;
-    private static final int UNKNOWN_VOLUME_TEXT = com.android.internal.R.string.volume_unknown;
-    private static final int NOTIFICATION_VOLUME_TEXT =
-            com.android.internal.R.string.volume_notification;
-    private static final int BLUETOOTH_INCALL_VOLUME_TEXT =
-            com.android.internal.R.string.volume_bluetooth_call;
+//    private static final int RINGTONE_VOLUME_TEXT = com.android.internal.R.string.volume_ringtone;
+//    private static final int MUSIC_VOLUME_TEXT = com.android.internal.R.string.volume_music;
+//    private static final int INCALL_VOLUME_TEXT = com.android.internal.R.string.volume_call;
+//    private static final int ALARM_VOLUME_TEXT = com.android.internal.R.string.volume_alarm;
+//    private static final int UNKNOWN_VOLUME_TEXT = com.android.internal.R.string.volume_unknown;
+//    private static final int NOTIFICATION_VOLUME_TEXT =
+//            com.android.internal.R.string.volume_notification;
+//    private static final int BLUETOOTH_INCALL_VOLUME_TEXT =
+//            com.android.internal.R.string.volume_bluetooth_call;
 
     protected Context mContext;
     private AudioManager mAudioManager;
     protected AudioService mAudioService;
     private boolean mRingIsSilent;
 
-    private final Toast mToast;
+    /** Dialog containing all the sliders */
+    private final Dialog mDialog;
+    /** Dialog's content view */
     private final View mView;
-    private final TextView mMessage;
-    private final TextView mAdditionalMessage;
-    private final ImageView mSmallStreamIcon;
-    private final ImageView mLargeStreamIcon;
-    private final ProgressBar mLevel;
+//    private final TextView mMessage;
+//    private final TextView mAdditionalMessage;
+//    private final ImageView mSmallStreamIcon;
+//    private final ImageView mLargeStreamIcon;
+//    private final ProgressBar mLevel;
+
+    /** Contains the sliders and their touchable icons */
+    private final ViewGroup mSliderGroup;
+    /** The button that expands the dialog to show all sliders */
+    private final View mMoreButton;
+    /** Dummy divider icon that needs to vanish with the more button */
+    private final View mDivider;
+
+    /** Currently active stream that shows up at the top of the list of sliders */
+    private int mActiveStreamType = -1;
+    /** All the slider controls mapped by stream type */
+    private HashMap<Integer,StreamControl> mStreamControls;
+
+    // List of stream types and their order
+    // RING and VOICE_CALL are hidden unless explicitly requested
+    private static final int [] STREAM_TYPES = {
+        AudioManager.STREAM_RING,
+        AudioManager.STREAM_VOICE_CALL,
+        AudioManager.STREAM_MUSIC,
+        AudioManager.STREAM_NOTIFICATION
+    };
+
+    // These icons need to correspond to the ones above.
+    private static final int [] STREAM_ICONS_NORMAL = {
+        R.drawable.ic_audio_phone,
+        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_phone,
+        R.drawable.ic_audio_phone,
+        R.drawable.ic_audio_vol_mute,
+        R.drawable.ic_audio_notification_mute,
+    };
+
+    /** Object that contains data for each slider */
+    private class StreamControl {
+        int streamType;
+        ViewGroup group;
+        ImageView icon;
+        SeekBar seekbarView;
+        int iconRes;
+        int iconMuteRes;
+    }
 
     // Synchronize when accessing this
     private ToneGenerator mToneGenerators[];
     private Vibrator mVibrator;
 
-    public VolumePanel(Context context, AudioService volumeService) {
+    public VolumePanel(final Context context, AudioService volumeService) {
         mContext = context;
         mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
         mAudioService = volumeService;
-        mToast = new Toast(context);
 
         LayoutInflater inflater = (LayoutInflater) context
                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-        View view = mView = inflater.inflate(com.android.internal.R.layout.volume_adjust, null);
-        mMessage = (TextView) view.findViewById(com.android.internal.R.id.message);
-        mAdditionalMessage =
-                (TextView) view.findViewById(com.android.internal.R.id.additional_message);
-        mSmallStreamIcon = (ImageView) view.findViewById(com.android.internal.R.id.other_stream_icon);
-        mLargeStreamIcon = (ImageView) view.findViewById(com.android.internal.R.id.ringer_stream_icon);
-        mLevel = (ProgressBar) view.findViewById(com.android.internal.R.id.level);
+        View view = mView = inflater.inflate(R.layout.volume_adjust, null);
+        mView.setOnTouchListener(new View.OnTouchListener() {
+            public boolean onTouch(View v, MotionEvent event) {
+                resetTimeout();
+                return true;
+            }
+        });
+        mSliderGroup = (ViewGroup) mView.findViewById(R.id.slider_group);
+        mMoreButton = (ImageView) mView.findViewById(R.id.expand_button);
+        mMoreButton.setOnClickListener(this);
+        mDivider = (ImageView) mView.findViewById(R.id.expand_button_divider);
+
+        mDialog = new Dialog(context, R.style.Theme_Panel_Volume);
+        mDialog.setTitle("Volume control"); // No need to localize
+        mDialog.setContentView(mView);
+        mDialog.setOnDismissListener(new OnDismissListener() {
+            public void onDismiss(DialogInterface dialog) {
+                mActiveStreamType = -1;
+                mAudioManager.forceVolumeControlStream(mActiveStreamType);
+            }
+        });
+        // Change some window properties
+        Window window = mDialog.getWindow();
+        window.setGravity(Gravity.TOP);
+        WindowManager.LayoutParams lp = window.getAttributes();
+        lp.token = null;
+        lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
+        window.setAttributes(lp);
+        window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
+
+//        mMessage = (TextView) view.findViewById(com.android.internal.R.id.message);
+//        mAdditionalMessage =
+//                (TextView) view.findViewById(com.android.internal.R.id.additional_message);
+//        mSmallStreamIcon = (ImageView) view.findViewById(com.android.internal.R.id.other_stream_icon);
+//        mLargeStreamIcon = (ImageView) view.findViewById(com.android.internal.R.id.ringer_stream_icon);
+//        mLevel = (ProgressBar) view.findViewById(com.android.internal.R.id.level);
 
         mToneGenerators = new ToneGenerator[AudioSystem.getNumStreamTypes()];
         mVibrator = new Vibrator();
+
+        listenToRingerMode();
+    }
+
+    private void listenToRingerMode() {
+        final IntentFilter filter = new IntentFilter();
+        filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
+        mContext.registerReceiver(new BroadcastReceiver() {
+
+            public void onReceive(Context context, Intent intent) {
+                final String action = intent.getAction();
+
+                if (AudioManager.RINGER_MODE_CHANGED_ACTION.equals(action)) {
+                    removeMessages(MSG_RINGER_MODE_CHANGED);
+                    sendMessage(obtainMessage(MSG_RINGER_MODE_CHANGED));
+                }
+            }
+        }, filter);
+    }
+
+    private boolean isMuted(int streamType) {
+        return mAudioManager.isStreamMute(streamType);
+    }
+
+    private void createSliders() {
+        LayoutInflater inflater = (LayoutInflater) mContext
+                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+        mStreamControls = new HashMap<Integer,StreamControl>(STREAM_TYPES.length);
+        for (int i = 0; i < STREAM_TYPES.length; i++) {
+            StreamControl sc = new StreamControl();
+            sc.streamType = STREAM_TYPES[i];
+            sc.group = (ViewGroup) inflater.inflate(R.layout.volume_adjust_item, null);
+            sc.group.setTag(sc);
+            sc.icon = (ImageView) sc.group.findViewById(R.id.stream_icon);
+            sc.icon.setOnClickListener(this);
+            sc.icon.setTag(sc);
+            sc.iconRes = STREAM_ICONS_NORMAL[i];
+            sc.iconMuteRes = STREAM_ICONS_MUTED[i];
+            sc.icon.setImageResource(sc.iconRes);
+            sc.seekbarView = (SeekBar) sc.group.findViewById(R.id.seekbar);
+            sc.seekbarView.setMax(mAudioManager.getStreamMaxVolume(STREAM_TYPES[i]));
+            sc.seekbarView.setOnSeekBarChangeListener(this);
+            sc.seekbarView.setTag(sc);
+            mStreamControls.put(STREAM_TYPES[i], sc);
+        }
+    }
+
+    private void reorderSliders(int activeStreamType) {
+        mSliderGroup.removeAllViews();
+
+        StreamControl active = mStreamControls.get(activeStreamType);
+        if (active == null) {
+            Log.e("VolumePanel", "Missing stream type! - " + activeStreamType);
+            mActiveStreamType = -1;
+        } else {
+            mSliderGroup.addView(active.group);
+            mActiveStreamType = activeStreamType;
+            active.group.setVisibility(View.VISIBLE);
+            updateSlider(active);
+        }
+
+        for (int i = 0; i < STREAM_TYPES.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 == activeStreamType) {
+                continue;
+            }
+            StreamControl sc = mStreamControls.get(streamType);
+            mSliderGroup.addView(sc.group);
+            updateSlider(sc);
+        }
+    }
+
+    /** Update the mute and progress state of a slider */
+    private void updateSlider(StreamControl sc) {
+        sc.seekbarView.setProgress(mAudioManager.getLastAudibleStreamVolume(sc.streamType));
+        final boolean muted = isMuted(sc.streamType);
+        sc.icon.setImageResource(muted ? sc.iconMuteRes : sc.iconRes);
+        sc.seekbarView.setEnabled(!muted);
+    }
+
+    private boolean isExpanded() {
+        return mMoreButton.getVisibility() != View.VISIBLE;
+    }
+
+    private void expand() {
+        final int count = mSliderGroup.getChildCount();
+        for (int i = 0; i < count; i++) {
+            mSliderGroup.getChildAt(i).setVisibility(View.VISIBLE);
+        }
+        mMoreButton.setVisibility(View.INVISIBLE);
+        mDivider.setVisibility(View.INVISIBLE);
+    }
+
+    private void collapse() {
+        mMoreButton.setVisibility(View.VISIBLE);
+        mDivider.setVisibility(View.VISIBLE);
+        final int count = mSliderGroup.getChildCount();
+        for (int i = 1; i < count; i++) {
+            mSliderGroup.getChildAt(i).setVisibility(View.GONE);
+        }
+    }
+
+    private void updateStates() {
+        final int count = mSliderGroup.getChildCount();
+        for (int i = 0; i < count; i++) {
+            StreamControl sc = (StreamControl) mSliderGroup.getChildAt(i).getTag();
+            updateSlider(sc);
+        }
     }
 
     public void postVolumeChanged(int streamType, int flags) {
         if (hasMessages(MSG_VOLUME_CHANGED)) return;
+        if (mStreamControls == null) {
+            createSliders();
+        }
         removeMessages(MSG_FREE_RESOURCES);
         obtainMessage(MSG_VOLUME_CHANGED, streamType, flags).sendToTarget();
     }
@@ -137,6 +342,10 @@
 
         if (LOGD) Log.d(TAG, "onVolumeChanged(streamType: " + streamType + ", flags: " + flags + ")");
 
+        if (mActiveStreamType == -1) {
+            reorderSliders(streamType);
+        }
+
         if ((flags & AudioManager.FLAG_SHOW_UI) != 0) {
             onShowVolumeChanged(streamType, flags);
         }
@@ -154,12 +363,17 @@
 
         removeMessages(MSG_FREE_RESOURCES);
         sendMessageDelayed(obtainMessage(MSG_FREE_RESOURCES), FREE_DELAY);
+
+        resetTimeout();
     }
 
     protected void onShowVolumeChanged(int streamType, int flags) {
-        int index = mAudioService.getStreamVolume(streamType);
-        int message = UNKNOWN_VOLUME_TEXT;
-        int additionalMessage = 0;
+        int index = mAudioService.isStreamMute(streamType) ?
+                mAudioService.getLastAudibleStreamVolume(streamType)
+                : mAudioService.getStreamVolume(streamType);
+
+//        int message = UNKNOWN_VOLUME_TEXT;
+//        int additionalMessage = 0;
         mRingIsSilent = false;
 
         if (LOGD) {
@@ -168,31 +382,35 @@
         }
 
         // get max volume for progress bar
+
         int max = mAudioService.getStreamMaxVolume(streamType);
 
         switch (streamType) {
 
             case AudioManager.STREAM_RING: {
-                setRingerIcon();
-                message = RINGTONE_VOLUME_TEXT;
+//                setRingerIcon();
+//                message = RINGTONE_VOLUME_TEXT;
                 Uri ringuri = RingtoneManager.getActualDefaultRingtoneUri(
                         mContext, RingtoneManager.TYPE_RINGTONE);
                 if (ringuri == null) {
-                    additionalMessage =
-                        com.android.internal.R.string.volume_music_hint_silent_ringtone_selected;
+//                    additionalMessage =
+//                        com.android.internal.R.string.volume_music_hint_silent_ringtone_selected;
                     mRingIsSilent = true;
                 }
                 break;
             }
 
             case AudioManager.STREAM_MUSIC: {
-                message = MUSIC_VOLUME_TEXT;
+//                message = MUSIC_VOLUME_TEXT;
+                // Special case for when Bluetooth is active for music
                 if (mAudioManager.isBluetoothA2dpOn()) {
-                    additionalMessage =
-                        com.android.internal.R.string.volume_music_hint_playing_through_bluetooth;
-                    setLargeIcon(com.android.internal.R.drawable.ic_volume_bluetooth_ad2p);
+//                    additionalMessage =
+//                        com.android.internal.R.string.volume_music_hint_playing_through_bluetooth;
+//                    setLargeIcon(com.android.internal.R.drawable.ic_volume_bluetooth_ad2p);
+                    setMusicIcon(R.drawable.ic_audio_bt, R.drawable.ic_audio_bt_mute);
                 } else {
-                    setSmallIcon(index);
+                    setMusicIcon(R.drawable.ic_audio_vol, R.drawable.ic_audio_vol_mute);
+//                    setSmallIcon(index);
                 }
                 break;
             }
@@ -205,25 +423,25 @@
                  */
                 index++;
                 max++;
-                message = INCALL_VOLUME_TEXT;
-                setSmallIcon(index);
+//                message = INCALL_VOLUME_TEXT;
+//                setSmallIcon(index);
                 break;
             }
 
             case AudioManager.STREAM_ALARM: {
-                message = ALARM_VOLUME_TEXT;
-                setSmallIcon(index);
+//                message = ALARM_VOLUME_TEXT;
+//                setSmallIcon(index);
                 break;
             }
 
             case AudioManager.STREAM_NOTIFICATION: {
-                message = NOTIFICATION_VOLUME_TEXT;
-                setSmallIcon(index);
+//                message = NOTIFICATION_VOLUME_TEXT;
+//                setSmallIcon(index);
                 Uri ringuri = RingtoneManager.getActualDefaultRingtoneUri(
                         mContext, RingtoneManager.TYPE_NOTIFICATION);
                 if (ringuri == null) {
-                    additionalMessage =
-                        com.android.internal.R.string.volume_music_hint_silent_ringtone_selected;
+//                    additionalMessage =
+//                        com.android.internal.R.string.volume_music_hint_silent_ringtone_selected;
                     mRingIsSilent = true;
                 }
                 break;
@@ -237,34 +455,42 @@
                  */
                 index++;
                 max++;
-                message = BLUETOOTH_INCALL_VOLUME_TEXT;
-                setLargeIcon(com.android.internal.R.drawable.ic_volume_bluetooth_in_call);
+//                message = BLUETOOTH_INCALL_VOLUME_TEXT;
+//                setLargeIcon(com.android.internal.R.drawable.ic_volume_bluetooth_in_call);
                 break;
             }
         }
 
-        String messageString = Resources.getSystem().getString(message);
-        if (!mMessage.getText().equals(messageString)) {
-            mMessage.setText(messageString);
+//        String messageString = Resources.getSystem().getString(message);
+//        if (!mMessage.getText().equals(messageString)) {
+//            mMessage.setText(messageString);
+//        }
+//
+//        if (additionalMessage == 0) {
+//            mAdditionalMessage.setVisibility(View.GONE);
+//        } else {
+//            mAdditionalMessage.setVisibility(View.VISIBLE);
+//            mAdditionalMessage.setText(Resources.getSystem().getString(additionalMessage));
+//        }
+
+//        if (max != mLevel.getMax()) {
+//            mLevel.setMax(max);
+//        }
+//        mLevel.setProgress(index);
+
+        StreamControl sc = mStreamControls.get(streamType);
+        if (sc != null) {
+            sc.seekbarView.setProgress(index);
         }
 
-        if (additionalMessage == 0) {
-            mAdditionalMessage.setVisibility(View.GONE);
-        } else {
-            mAdditionalMessage.setVisibility(View.VISIBLE);
-            mAdditionalMessage.setText(Resources.getSystem().getString(additionalMessage));
+        if (!mDialog.isShowing()) {
+            mAudioManager.forceVolumeControlStream(streamType);
+            mDialog.setContentView(mView);
+            // Showing dialog - use collapsed state
+            collapse();
+            mDialog.show();
         }
 
-        if (max != mLevel.getMax()) {
-            mLevel.setMax(max);
-        }
-        mLevel.setProgress(index);
-
-        mToast.setView(mView);
-        mToast.setDuration(Toast.LENGTH_SHORT);
-        mToast.setGravity(Gravity.TOP, 0, 0);
-        mToast.show();
-
         // Do a little vibrate if applicable (only when going into vibrate mode)
         if ((flags & AudioManager.FLAG_VIBRATE) != 0 &&
                 mAudioService.isStreamAffectedByRingerMode(streamType) &&
@@ -333,59 +559,72 @@
         }
     }
 
-    /**
-     * Makes the small icon visible, and hides the large icon.
-     *
-     * @param index The volume index, where 0 means muted.
-     */
-    private void setSmallIcon(int index) {
-        mLargeStreamIcon.setVisibility(View.GONE);
-        mSmallStreamIcon.setVisibility(View.VISIBLE);
-
-        mSmallStreamIcon.setImageResource(index == 0
-                ? com.android.internal.R.drawable.ic_volume_off_small
-                : com.android.internal.R.drawable.ic_volume_small);
-    }
+//    /**
+//     * Makes the small icon visible, and hides the large icon.
+//     *
+//     * @param index The volume index, where 0 means muted.
+//     */
+//    private void setSmallIcon(int index) {
+//        mLargeStreamIcon.setVisibility(View.GONE);
+//        mSmallStreamIcon.setVisibility(View.VISIBLE);
+//
+//        mSmallStreamIcon.setImageResource(index == 0
+//                ? com.android.internal.R.drawable.ic_volume_off_small
+//                : com.android.internal.R.drawable.ic_volume_small);
+//    }
+//
+//    /**
+//     * Makes the large image view visible with the given icon.
+//     *
+//     * @param resId The icon to display.
+//     */
+//    private void setLargeIcon(int resId) {
+//        mSmallStreamIcon.setVisibility(View.GONE);
+//        mLargeStreamIcon.setVisibility(View.VISIBLE);
+//        mLargeStreamIcon.setImageResource(resId);
+//    }
+//
+//    /**
+//     * Makes the ringer icon visible with an icon that is chosen
+//     * based on the current ringer mode.
+//     */
+//    private void setRingerIcon() {
+//        mSmallStreamIcon.setVisibility(View.GONE);
+//        mLargeStreamIcon.setVisibility(View.VISIBLE);
+//
+//        int ringerMode = mAudioService.getRingerMode();
+//        int icon;
+//
+//        if (LOGD) Log.d(TAG, "setRingerIcon(), ringerMode: " + ringerMode);
+//
+//        if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
+//            icon = com.android.internal.R.drawable.ic_volume_off;
+//        } else if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
+//            icon = com.android.internal.R.drawable.ic_vibrate;
+//        } else {
+//            icon = com.android.internal.R.drawable.ic_volume;
+//        }
+//        mLargeStreamIcon.setImageResource(icon);
+//    }
 
     /**
-     * Makes the large image view visible with the given icon.
-     *
-     * @param resId The icon to display.
+     * Switch between icons because Bluetooth music is same as music volume, but with
+     * different icons.
      */
-    private void setLargeIcon(int resId) {
-        mSmallStreamIcon.setVisibility(View.GONE);
-        mLargeStreamIcon.setVisibility(View.VISIBLE);
-        mLargeStreamIcon.setImageResource(resId);
-    }
-
-    /**
-     * Makes the ringer icon visible with an icon that is chosen
-     * based on the current ringer mode.
-     */
-    private void setRingerIcon() {
-        mSmallStreamIcon.setVisibility(View.GONE);
-        mLargeStreamIcon.setVisibility(View.VISIBLE);
-
-        int ringerMode = mAudioService.getRingerMode();
-        int icon;
-
-        if (LOGD) Log.d(TAG, "setRingerIcon(), ringerMode: " + ringerMode);
-
-        if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
-            icon = com.android.internal.R.drawable.ic_volume_off;
-        } else if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
-            icon = com.android.internal.R.drawable.ic_vibrate;
-        } else {
-            icon = com.android.internal.R.drawable.ic_volume;
+    private void setMusicIcon(int resId, int resMuteId) {
+        StreamControl sc = mStreamControls.get(AudioManager.STREAM_MUSIC);
+        if (sc != null) {
+            sc.iconRes = resId;
+            sc.iconMuteRes = resMuteId;
+            sc.icon.setImageResource(isMuted(sc.streamType) ? sc.iconMuteRes : sc.iconRes);
         }
-        mLargeStreamIcon.setImageResource(icon);
     }
 
     protected void onFreeResources() {
         // We'll keep the views, just ditch the cached drawable and hence
         // bitmaps
-        mSmallStreamIcon.setImageDrawable(null);
-        mLargeStreamIcon.setImageDrawable(null);
+//        mSmallStreamIcon.setImageDrawable(null);
+//        mLargeStreamIcon.setImageDrawable(null);
 
         synchronized (this) {
             for (int i = mToneGenerators.length - 1; i >= 0; i--) {
@@ -426,7 +665,55 @@
                 break;
             }
 
+            case MSG_TIMEOUT: {
+                if (mDialog.isShowing()) {
+                    mDialog.dismiss();
+                    mActiveStreamType = -1;
+                }
+                break;
+            }
+            case MSG_RINGER_MODE_CHANGED: {
+                if (mDialog.isShowing()) {
+                    updateStates();
+                }
+                break;
+            }
         }
     }
 
+    private void resetTimeout() {
+        removeMessages(MSG_TIMEOUT);
+        sendMessageDelayed(obtainMessage(MSG_TIMEOUT), TIMEOUT_DELAY);
+    }
+
+    public void onProgressChanged(SeekBar seekBar, int progress,
+            boolean fromUser) {
+        final Object tag = seekBar.getTag();
+        if (fromUser && tag instanceof StreamControl) {
+            StreamControl sc = (StreamControl) tag;
+            if (mAudioManager.getStreamVolume(sc.streamType) != progress) {
+                mAudioManager.setStreamVolume(sc.streamType, progress, 0);
+            }
+        }
+        resetTimeout();
+    }
+
+    public void onStartTrackingTouch(SeekBar seekBar) {
+    }
+
+    public void onStopTrackingTouch(SeekBar seekBar) {
+    }
+
+    public void onClick(View v) {
+        if (v == mMoreButton) {
+            expand();
+        } else if (v.getTag() instanceof StreamControl) {
+            StreamControl sc = (StreamControl) v.getTag();
+            mAudioManager.setRingerMode(mAudioManager.isSilentMode()
+                    ? AudioManager.RINGER_MODE_NORMAL : AudioManager.RINGER_MODE_SILENT);
+            // Expand the dialog if it hasn't been expanded yet.
+            if (!isExpanded()) expand();
+        }
+        resetTimeout();
+    }
 }
diff --git a/core/java/android/webkit/CookieManager.java b/core/java/android/webkit/CookieManager.java
index fe137b5..cef389e 100644
--- a/core/java/android/webkit/CookieManager.java
+++ b/core/java/android/webkit/CookieManager.java
@@ -516,11 +516,17 @@
         }
     }
 
-    synchronized void waitForCookieOperationsToComplete() {
-        while (pendingCookieOperations > 0) {
-            try {
-                wait();
-            } catch (InterruptedException e) { }
+    /**
+     * Waits for pending operations to completed.
+     * {@hide}  Too late to release publically.
+     */
+    public void waitForCookieOperationsToComplete() {
+        synchronized (this) {
+            while (pendingCookieOperations > 0) {
+                try {
+                    wait();
+                } catch (InterruptedException e) { }
+            }
         }
     }
 
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index 599d167..26dab81 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -557,6 +557,9 @@
     // sending the same dimensions more than once.
     int mLastWidthSent;
     int mLastHeightSent;
+    // Since view height sent to webkit could be fixed to avoid relayout, this
+    // value records the last sent actual view height.
+    int mLastActualHeightSent;
 
     private int mContentWidth;   // cache of value from WebViewCore
     private int mContentHeight;  // cache of value from WebViewCore
@@ -2574,6 +2577,7 @@
         int mWidth;
         int mHeight;
         float mHeightWidthRatio;
+        int mActualViewHeight;
         int mTextWrapWidth;
         int mAnchorX;
         int mAnchorY;
@@ -2595,6 +2599,7 @@
 
         int viewWidth = getViewWidth();
         int newWidth = Math.round(viewWidth * mZoomManager.getInvScale());
+        // This height could be fixed and be different from actual visible height.
         int viewHeight = getViewHeightWithTitle() - getTitleHeight();
         int newHeight = Math.round(viewHeight * mZoomManager.getInvScale());
         // Make the ratio more accurate than (newHeight / newWidth), since the
@@ -2612,12 +2617,16 @@
             newHeight = 0;
             heightWidthRatio = 0;
         }
+        // Actual visible height.
+        int actualViewHeight = getViewHeight();
         // Avoid sending another message if the dimensions have not changed.
-        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force) {
+        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force ||
+                actualViewHeight != mLastActualHeightSent) {
             ViewSizeData data = new ViewSizeData();
             data.mWidth = newWidth;
             data.mHeight = newHeight;
             data.mHeightWidthRatio = heightWidthRatio;
+            data.mActualViewHeight = actualViewHeight;
             data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale());
             data.mScale = mZoomManager.getScale();
             data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress()
@@ -2627,6 +2636,7 @@
             mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
             mLastWidthSent = newWidth;
             mLastHeightSent = newHeight;
+            mLastActualHeightSent = actualViewHeight;
             mZoomManager.clearDocumentAnchor();
             return true;
         }
diff --git a/core/java/android/webkit/WebViewCore.java b/core/java/android/webkit/WebViewCore.java
index 82f44d6..a9102e9 100644
--- a/core/java/android/webkit/WebViewCore.java
+++ b/core/java/android/webkit/WebViewCore.java
@@ -1177,13 +1177,7 @@
                             break;
 
                         case VIEW_SIZE_CHANGED: {
-                            WebView.ViewSizeData data =
-                                    (WebView.ViewSizeData) msg.obj;
-                            viewSizeChanged(data.mWidth, data.mHeight,
-                                    data.mHeightWidthRatio,
-                                    data.mTextWrapWidth, data.mScale,
-                                    data.mAnchorX, data.mAnchorY,
-                                    data.mIgnoreHeight);
+                            viewSizeChanged((WebView.ViewSizeData) msg.obj);
                             break;
                         }
                         case SET_SCROLL_OFFSET:
@@ -1817,8 +1811,11 @@
     private float mCurrentViewScale = 1.0f;
 
     // notify webkit that our virtual view size changed size (after inv-zoom)
-    private void viewSizeChanged(int w, int h, float heightWidthRatio, int textwrapWidth,
-            float scale, int anchorX, int anchorY, boolean ignoreHeight) {
+    private void viewSizeChanged(WebView.ViewSizeData data) {
+        int w = data.mWidth;
+        int h = data.mHeight;
+        int textwrapWidth = data.mTextWrapWidth;
+        float scale = data.mScale;
         if (DebugFlags.WEB_VIEW_CORE) {
             Log.v(LOGTAG, "viewSizeChanged w=" + w + "; h=" + h
                     + "; textwrapWidth=" + textwrapWidth + "; scale=" + scale);
@@ -1865,11 +1862,13 @@
         }
         int height = h;
         if (width != w) {
+            float heightWidthRatio = data.mHeightWidthRatio;
             float ratio = (heightWidthRatio > 0) ? heightWidthRatio : (float) h / w;
             height = Math.round(ratio * width);
         }
-        nativeSetSize(width, height,
-                textwrapWidth, scale, w, h, anchorX, anchorY, ignoreHeight);
+        nativeSetSize(width, height, textwrapWidth, scale, w,
+                data.mActualViewHeight > 0 ? data.mActualViewHeight : h,
+                data.mAnchorX, data.mAnchorY, data.mIgnoreHeight);
         // Remember the current width and height
         boolean needInvalidate = (mCurrentViewWidth == 0);
         mCurrentViewWidth = w;
diff --git a/core/java/android/widget/SearchView.java b/core/java/android/widget/SearchView.java
index a37f12e..f051b77 100644
--- a/core/java/android/widget/SearchView.java
+++ b/core/java/android/widget/SearchView.java
@@ -330,8 +330,8 @@
 
     /**
      * Sets a listener to inform when the search button is pressed. This is only
-     * relevant when the text field is not visible by default. Calling #setIconified(false)
-     * can also cause this listener to be informed.
+     * relevant when the text field is not visible by default. Calling {@link #setIconified
+     * setIconified(false)} can also cause this listener to be informed.
      *
      * @param listener the listener to inform when the search button is clicked or
      * the text field is programmatically de-iconified.
@@ -386,7 +386,7 @@
      * if the default state is iconified, then it collapses to that state when the close button
      * is pressed. Changes to this property will take effect immediately.
      *
-     * <p>The default value is false.</p>
+     * <p>The default value is true.</p>
      *
      * @param iconified whether the search field should be iconified by default
      */
diff --git a/core/java/android/widget/Spinner.java b/core/java/android/widget/Spinner.java
index a92272c..fd7bceb 100644
--- a/core/java/android/widget/Spinner.java
+++ b/core/java/android/widget/Spinner.java
@@ -69,6 +69,8 @@
 
     private int mGravity;
 
+    private Rect mTempRect = new Rect();
+
     /**
      * Construct a new spinner with the given context's theme.
      *
@@ -260,8 +262,8 @@
         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
         if (mPopup != null && MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) {
             final int measuredWidth = getMeasuredWidth();
-            setMeasuredDimension(Math.min(Math.max(measuredWidth, mPopup.measureContentWidth()),
-                    MeasureSpec.getSize(widthMeasureSpec)),
+            setMeasuredDimension(Math.min(Math.max(measuredWidth,
+                    measureContentWidth(getAdapter())), MeasureSpec.getSize(widthMeasureSpec)),
                     getMeasuredHeight());
         }
     }
@@ -455,7 +457,50 @@
     public CharSequence getPrompt() {
         return mPopup.getHintText();
     }
-    
+
+    private int measureContentWidth(SpinnerAdapter adapter) {
+        if (adapter == null) {
+            return 0;
+        }
+
+        int width = 0;
+        View itemView = null;
+        int itemType = 0;
+        final int widthMeasureSpec =
+            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
+        final int heightMeasureSpec =
+            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
+
+        // Make sure the number of items we'll measure is capped. If it's a huge data set
+        // with wildly varying sizes, oh well.
+        final int start = Math.max(0, getSelectedItemPosition());
+        final int count = Math.min(adapter.getCount(), start + MAX_ITEMS_MEASURED);
+        for (int i = start; i < count; i++) {
+            final int positionType = adapter.getItemViewType(i);
+            if (positionType != itemType) {
+                itemType = positionType;
+                itemView = null;
+            }
+            itemView = adapter.getView(i, itemView, this);
+            if (itemView.getLayoutParams() == null) {
+                itemView.setLayoutParams(new ViewGroup.LayoutParams(
+                        ViewGroup.LayoutParams.WRAP_CONTENT,
+                        ViewGroup.LayoutParams.WRAP_CONTENT));
+            }
+            itemView.measure(widthMeasureSpec, heightMeasureSpec);
+            width = Math.max(width, itemView.getMeasuredWidth());
+        }
+
+        // Add background padding to measured width
+        Drawable popupBackground = getBackground();
+        if (popupBackground != null) {
+            popupBackground.getPadding(mTempRect);
+            width += mTempRect.left + mTempRect.right;
+        }
+
+        return width;
+    }
+
     /**
      * <p>Wrapper class for an Adapter. Transforms the embedded Adapter instance
      * into a ListAdapter.</p>
@@ -581,8 +626,6 @@
          */
         public void setPromptText(CharSequence hintText);
         public CharSequence getHintText();
-
-        public int measureContentWidth();
     }
     
     private class DialogPopup implements SpinnerPopup, DialogInterface.OnClickListener {
@@ -624,23 +667,14 @@
             setSelection(which);
             dismiss();
         }
-
-        public int measureContentWidth() {
-            // Doesn't matter for dialog mode
-            return 0;
-        }
     }
     
     private class DropdownPopup extends ListPopupWindow implements SpinnerPopup {
         private CharSequence mHintText;
-        private int mPopupMaxWidth;
-        private Rect mTempRect = new Rect();
+        private ListAdapter mAdapter;
 
         public DropdownPopup(Context context, AttributeSet attrs, int defStyleRes) {
             super(context, attrs, 0, defStyleRes);
-            
-            final DisplayMetrics metrics = context.getResources().getDisplayMetrics();
-            mPopupMaxWidth = metrics.widthPixels / 2;
 
             setAnchorView(Spinner.this);
             setModal(true);
@@ -653,6 +687,12 @@
             });
         }
         
+        @Override
+        public void setAdapter(ListAdapter adapter) {
+            super.setAdapter(adapter);
+            mAdapter = adapter;
+        }
+
         public CharSequence getHintText() {
             return mHintText;
         }
@@ -664,59 +704,12 @@
 
         @Override
         public void show() {
-            setWidth(Spinner.this.getWidth());
+            setWidth(Math.max(measureContentWidth((SpinnerAdapter) mAdapter),
+                    Spinner.this.getWidth()));
             setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
             super.show();
             getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
             setSelection(Spinner.this.getSelectedItemPosition());
         }
-
-        @Override
-        public int measureContentWidth() {
-            final SpinnerAdapter adapter = getAdapter();
-            if (adapter == null) {
-                return 0;
-            }
-
-            int width = 0;
-            View itemView = null;
-            int itemType = 0;
-            final int widthMeasureSpec =
-                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
-            final int heightMeasureSpec =
-                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
-
-            // Make sure the number of items we'll measure is capped. If it's a huge data set
-            // with wildly varying sizes, oh well.
-            final int start = Math.max(0, getSelectedItemPosition());
-            final int count = Math.min(adapter.getCount(), start + MAX_ITEMS_MEASURED);
-            for (int i = start; i < count; i++) {
-                final int positionType = adapter.getItemViewType(i);
-                if (positionType != itemType) {
-                    itemType = positionType;
-                    itemView = null;
-                }
-                itemView = adapter.getDropDownView(i, itemView, Spinner.this);
-                if (itemView.getLayoutParams() == null) {
-                    itemView.setLayoutParams(generateDefaultLayoutParams());
-                }
-                itemView.measure(widthMeasureSpec, heightMeasureSpec);
-                width = Math.max(width, itemView.getMeasuredWidth());
-            }
-
-            // Add background padding to measured width
-            Drawable popupBackground = getBackground();
-            if (popupBackground != null) {
-                popupBackground.getPadding(mTempRect);
-                width += mTempRect.left + mTempRect.right;
-            }
-
-            return width;
-        }
-
-        private ViewGroup.LayoutParams generateDefaultLayoutParams() {
-            return new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
-                    ViewGroup.LayoutParams.WRAP_CONTENT);
-        }
     }
 }
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 772eefd..28b106b 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -8012,11 +8012,9 @@
                 return true;
 
             case ID_SELECT_ALL:
+                // This does not enter text selection mode. Text is highlighted, so that it can be
+                // bulk edited, like selectAllOnFocus does.
                 selectAll();
-                // Update controller positions after selection change.
-                if (hasSelectionController()) {
-                    getSelectionController().show();
-                }
                 return true;
 
             case ID_PASTE:
@@ -8134,6 +8132,8 @@
             return true;
         }
 
+        boolean handled = false;
+
         // Long press in empty space moves cursor and shows the Paste affordance if available.
         if (!isPositionOnText(mLastDownPositionX, mLastDownPositionY) &&
                 mInsertionControllerEnabled) {
@@ -8141,11 +8141,10 @@
             stopSelectionActionMode();
             Selection.setSelection((Spannable)mText, offset);
             getInsertionController().show(0);
-            mDiscardNextActionUp = true;
-            return true;
+            handled = true;
         }
 
-        if (mSelectionActionMode != null) {
+        if (!handled && mSelectionActionMode != null) {
             if (touchPositionIsInSelection()) {
                 // Start a drag
                 final int start = getSelectionStart();
@@ -8156,21 +8155,21 @@
                 startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0);
                 stopSelectionActionMode();
             } else {
+                // New selection at touch position
                 updateSelectedRegion();
             }
-            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
-            mDiscardNextActionUp = true;
-            return true;
+            handled = true;
         }
 
         // Start a new selection
-        if (startSelectionActionMode()) {
+        handled |= !handled && startSelectionActionMode();
+
+        if (handled) {
             performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
             mDiscardNextActionUp = true;
-            return true;
         }
 
-        return false;
+        return handled;
     }
 
     /**
diff --git a/core/java/com/android/internal/service/wallpaper/ImageWallpaper.java b/core/java/com/android/internal/service/wallpaper/ImageWallpaper.java
index 8fde247..85095cf 100644
--- a/core/java/com/android/internal/service/wallpaper/ImageWallpaper.java
+++ b/core/java/com/android/internal/service/wallpaper/ImageWallpaper.java
@@ -114,14 +114,11 @@
             mReceiver = new WallpaperObserver();
             registerReceiver(mReceiver, filter);
 
+            updateSurfaceSize(surfaceHolder);
+
             synchronized (mLock) {
                 updateWallpaperLocked();
             }
-            surfaceHolder.setFixedSize(getDesiredMinimumWidth(), getDesiredMinimumHeight());
-            // Used a fixed size surface, because we are special.  We can do
-            // this because we know the current design of window animations doesn't
-            // cause this to break.
-            //surfaceHolder.setSizeFromLayout();
         }
 
         @Override
@@ -131,6 +128,23 @@
         }
 
         @Override
+        public void onDesiredSizeChanged(int desiredWidth, int desiredHeight) {
+            super.onDesiredSizeChanged(desiredWidth, desiredHeight);
+            SurfaceHolder surfaceHolder = getSurfaceHolder();
+            if (surfaceHolder != null) {
+                updateSurfaceSize(surfaceHolder);
+            }
+        }
+
+        void updateSurfaceSize(SurfaceHolder surfaceHolder) {
+            surfaceHolder.setFixedSize(getDesiredMinimumWidth(), getDesiredMinimumHeight());
+            // Used a fixed size surface, because we are special.  We can do
+            // this because we know the current design of window animations doesn't
+            // cause this to break.
+            //surfaceHolder.setSizeFromLayout();
+        }
+
+        @Override
         public void onVisibilityChanged(boolean visible) {
             if (DEBUG) {
                 Log.d(TAG, "onVisibilityChanged: visible=" + visible);
diff --git a/core/java/com/android/internal/statusbar/StatusBarNotification.java b/core/java/com/android/internal/statusbar/StatusBarNotification.java
index cb791be..c03ff1a 100644
--- a/core/java/com/android/internal/statusbar/StatusBarNotification.java
+++ b/core/java/com/android/internal/statusbar/StatusBarNotification.java
@@ -63,8 +63,7 @@
         this.initialPid = initialPid;
         this.notification = notification;
 
-        this.priority = ((notification.flags & Notification.FLAG_ONGOING_EVENT) != 0)
-            ? PRIORITY_ONGOING : PRIORITY_NORMAL;
+        this.priority = PRIORITY_NORMAL;
     }
 
     public StatusBarNotification(Parcel in) {
diff --git a/core/java/com/android/internal/view/menu/ActionMenuView.java b/core/java/com/android/internal/view/menu/ActionMenuView.java
index ff15e44..7775f00 100644
--- a/core/java/com/android/internal/view/menu/ActionMenuView.java
+++ b/core/java/com/android/internal/view/menu/ActionMenuView.java
@@ -25,7 +25,6 @@
 import android.view.SoundEffectConstants;
 import android.view.View;
 import android.view.ViewGroup;
-import android.view.ViewParent;
 import android.widget.ImageButton;
 import android.widget.ImageView;
 import android.widget.LinearLayout;
@@ -193,61 +192,125 @@
         menu.setActionWidthLimit(width);
 
         menu.setMaxActionItems(mMaxItems);
+        final boolean cleared = mMenu != menu;
         mMenu = menu;
-        updateChildren(true);
+        updateChildren(cleared);
     }
 
     public void updateChildren(boolean cleared) {
-        final boolean reserveOverflow = mReserveOverflow;
-        removeAllViews();
-        
-        final ArrayList<MenuItemImpl> itemsToShow = mMenu.getActionItems(reserveOverflow);
+        final ArrayList<MenuItemImpl> itemsToShow = mMenu.getActionItems(mReserveOverflow);
         final int itemCount = itemsToShow.size();
         
         boolean needsDivider = false;
+        int childIndex = 0;
         for (int i = 0; i < itemCount; i++) {
             final MenuItemImpl itemData = itemsToShow.get(i);
             boolean hasDivider = false;
 
             if (needsDivider) {
-                addView(makeDividerView(), makeDividerLayoutParams());
+                if (!isDivider(getChildAt(childIndex))) {
+                    addView(makeDividerView(), childIndex, makeDividerLayoutParams());
+                }
                 hasDivider = true;
+                childIndex++;
             }
 
-            View actionView = itemData.getActionView();
-
-            if (actionView != null) {
-                final ViewParent parent = actionView.getParent();
-                if (parent instanceof ViewGroup) {
-                    ((ViewGroup) parent).removeView(actionView);
-                }
-                addView(actionView, makeActionViewLayoutParams(actionView));
+            View childToAdd = itemData.getActionView();
+            boolean needsPreDivider = false;
+            if (childToAdd != null) {
+                childToAdd.setLayoutParams(makeActionViewLayoutParams(childToAdd));
             } else {
                 ActionMenuItemView view = (ActionMenuItemView) itemData.getItemView(
                         MenuBuilder.TYPE_ACTION_BUTTON, this);
                 view.setItemInvoker(this);
-                if (i > 0 && !hasDivider && view.hasText() && itemData.getIcon() == null) {
-                    addView(makeDividerView(), makeDividerLayoutParams());
-                }
-                addView(view);
+                needsPreDivider = i > 0 && !hasDivider && view.hasText() &&
+                        itemData.getIcon() == null;
                 needsDivider = view.hasText();
+                childToAdd = view;
             }
+
+            boolean addPreDivider = removeChildrenUntil(childIndex, childToAdd, needsPreDivider);
+
+            if (addPreDivider) addView(makeDividerView(), childIndex, makeDividerLayoutParams());
+            if (needsPreDivider) childIndex++;
+
+            if (getChildAt(childIndex) != childToAdd) {
+                addView(childToAdd, childIndex);
+            }
+            childIndex++;
         }
 
-        if (reserveOverflow) {
-            if (mMenu.getNonActionItems(true).size() > 0) {
-                if (itemCount > 0) {
-                    addView(makeDividerView(), makeDividerLayoutParams());
-                }
+        final boolean hasOverflow = mOverflowButton != null && mOverflowButton.getParent() == this;
+        final boolean needsOverflow = mReserveOverflow && mMenu.getNonActionItems(true).size() > 0;
+
+        if (hasOverflow != needsOverflow) {
+            if (needsOverflow) {
                 if (mOverflowButton == null) {
                     OverflowMenuButton button = new OverflowMenuButton(mContext);
                     mOverflowButton = button;
                 }
-                addView(mOverflowButton);
+                boolean addDivider = removeChildrenUntil(childIndex, mOverflowButton, true);
+                if (addDivider && itemCount > 0) {
+                    addView(makeDividerView(), childIndex, makeDividerLayoutParams());
+                    childIndex++;
+                }
+                addView(mOverflowButton, childIndex);
+                childIndex++;
             } else {
-                mOverflowButton = null;
+                removeView(mOverflowButton);
+            }
+        } else {
+            if (needsOverflow) {
+                boolean overflowDivider = itemCount > 0;
+                boolean addDivider = removeChildrenUntil(childIndex, mOverflowButton,
+                        overflowDivider);
+                if (addDivider && itemCount > 0) {
+                    addView(makeDividerView(), childIndex, makeDividerLayoutParams());
+                }
+                if (overflowDivider) {
+                    childIndex += 2;
+                } else {
+                    childIndex++;
+                }
             }
         }
+
+        while (getChildCount() > childIndex) {
+            removeViewAt(childIndex);
+        }
+    }
+
+    private boolean removeChildrenUntil(int start, View targetChild, boolean needsPreDivider) {
+        final int childCount = getChildCount();
+        boolean found = false;
+        for (int i = start; i < childCount; i++) {
+            final View child = getChildAt(i);
+            if (child == targetChild) {
+                found = true;
+                break;
+            }
+        }
+
+        if (!found) {
+            return needsPreDivider;
+        }
+
+        for (int i = start; i < getChildCount(); ) {
+            final View child = getChildAt(i);
+            if (needsPreDivider && isDivider(child)) {
+                needsPreDivider = false;
+                i++;
+                continue;
+            }
+            if (child == targetChild) break;
+            removeViewAt(i);
+        }
+
+        return needsPreDivider;
+    }
+
+    private static boolean isDivider(View v) {
+        return v != null && v.getId() == com.android.internal.R.id.action_menu_divider;
     }
 
     public boolean showOverflowMenu() {
@@ -302,6 +365,7 @@
         ImageView result = new ImageView(mContext);
         result.setImageDrawable(mDivider);
         result.setScaleType(ImageView.ScaleType.FIT_XY);
+        result.setId(com.android.internal.R.id.action_menu_divider);
         return result;
     }
 
diff --git a/core/java/com/android/internal/widget/ActionBarView.java b/core/java/com/android/internal/widget/ActionBarView.java
index 3c3f14b..e3a66c5 100644
--- a/core/java/com/android/internal/widget/ActionBarView.java
+++ b/core/java/com/android/internal/widget/ActionBarView.java
@@ -250,6 +250,8 @@
     }
 
     public void setMenu(Menu menu) {
+        if (menu == mOptionsMenu) return;
+
         MenuBuilder builder = (MenuBuilder) menu;
         mOptionsMenu = builder;
         if (mMenuView != null) {
diff --git a/core/jni/android/graphics/Path.cpp b/core/jni/android/graphics/Path.cpp
index 90c4dd4..eb9e004 100644
--- a/core/jni/android/graphics/Path.cpp
+++ b/core/jni/android/graphics/Path.cpp
@@ -36,7 +36,8 @@
     static void finalizer(JNIEnv* env, jobject clazz, SkPath* obj) {
 #ifdef USE_OPENGL_RENDERER
         if (android::uirenderer::Caches::hasInstance()) {
-            android::uirenderer::Caches::getInstance().pathCache.removeDeferred(obj);
+            android::uirenderer::Caches::getInstance().resourceCache.destructor(obj);
+            return;
         }
 #endif
         delete obj;
diff --git a/core/res/res/drawable-hdpi/dialog_bottom_holo_dark.9.png b/core/res/res/drawable-hdpi/dialog_bottom_holo_dark.9.png
index 065cc9c..6c6252e 100644
--- a/core/res/res/drawable-hdpi/dialog_bottom_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/dialog_bottom_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_bottom_holo_light.9.png b/core/res/res/drawable-hdpi/dialog_bottom_holo_light.9.png
index 94decee..175c750 100644
--- a/core/res/res/drawable-hdpi/dialog_bottom_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/dialog_bottom_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_full_holo_dark.9.png b/core/res/res/drawable-hdpi/dialog_full_holo_dark.9.png
index 3b9e0cf..6e9abe65 100644
--- a/core/res/res/drawable-hdpi/dialog_full_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/dialog_full_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_full_holo_light.9.png b/core/res/res/drawable-hdpi/dialog_full_holo_light.9.png
index 0665b08..f96d09e 100644
--- a/core/res/res/drawable-hdpi/dialog_full_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/dialog_full_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_middle_holo_dark.9.png b/core/res/res/drawable-hdpi/dialog_middle_holo_dark.9.png
index dc62ab2..1f11f44 100644
--- a/core/res/res/drawable-hdpi/dialog_middle_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/dialog_middle_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_middle_holo_light.9.png b/core/res/res/drawable-hdpi/dialog_middle_holo_light.9.png
index e78e134..2e376cd 100644
--- a/core/res/res/drawable-hdpi/dialog_middle_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/dialog_middle_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_top_holo_dark.9.png b/core/res/res/drawable-hdpi/dialog_top_holo_dark.9.png
index ae223c8..73d56b7 100644
--- a/core/res/res/drawable-hdpi/dialog_top_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/dialog_top_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_top_holo_light.9.png b/core/res/res/drawable-hdpi/dialog_top_holo_light.9.png
index 7baced0..869decf 100644
--- a/core/res/res/drawable-hdpi/dialog_top_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/dialog_top_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_audio_bt.png b/core/res/res/drawable-hdpi/ic_audio_bt.png
new file mode 100644
index 0000000..597c384
--- /dev/null
+++ b/core/res/res/drawable-hdpi/ic_audio_bt.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_audio_bt_mute.png b/core/res/res/drawable-hdpi/ic_audio_bt_mute.png
new file mode 100644
index 0000000..14542eb
--- /dev/null
+++ b/core/res/res/drawable-hdpi/ic_audio_bt_mute.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_audio_phone.png b/core/res/res/drawable-hdpi/ic_audio_phone.png
new file mode 100644
index 0000000..2fff204
--- /dev/null
+++ b/core/res/res/drawable-hdpi/ic_audio_phone.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_audio_vol.png b/core/res/res/drawable-hdpi/ic_audio_vol.png
index cf3f3f5..6ea2693 100644
--- a/core/res/res/drawable-hdpi/ic_audio_vol.png
+++ b/core/res/res/drawable-hdpi/ic_audio_vol.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_audio_vol_mute.png b/core/res/res/drawable-hdpi/ic_audio_vol_mute.png
index c4ac4ef..f7428c7 100644
--- a/core/res/res/drawable-hdpi/ic_audio_vol_mute.png
+++ b/core/res/res/drawable-hdpi/ic_audio_vol_mute.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_sysbar_quicksettings.png b/core/res/res/drawable-hdpi/ic_sysbar_quicksettings.png
new file mode 100644
index 0000000..47b4ba2
--- /dev/null
+++ b/core/res/res/drawable-hdpi/ic_sysbar_quicksettings.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/scrubber_control_disabled_holo.png b/core/res/res/drawable-hdpi/scrubber_control_disabled_holo.png
index 401e904..d428e5a 100644
--- a/core/res/res/drawable-hdpi/scrubber_control_disabled_holo.png
+++ b/core/res/res/drawable-hdpi/scrubber_control_disabled_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/scrubber_control_holo.png b/core/res/res/drawable-hdpi/scrubber_control_holo.png
index 175917e..a5fb73c 100644
--- a/core/res/res/drawable-hdpi/scrubber_control_holo.png
+++ b/core/res/res/drawable-hdpi/scrubber_control_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/stat_notify_chat.png b/core/res/res/drawable-hdpi/stat_notify_chat.png
index 9c713c8..d7c1545 100644
--- a/core/res/res/drawable-hdpi/stat_notify_chat.png
+++ b/core/res/res/drawable-hdpi/stat_notify_chat.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/toast_frame.9.png b/core/res/res/drawable-hdpi/toast_frame.9.png
index 8f5d811..736683e 100644
--- a/core/res/res/drawable-hdpi/toast_frame.9.png
+++ b/core/res/res/drawable-hdpi/toast_frame.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_bottom_holo_dark.9.png b/core/res/res/drawable-mdpi/dialog_bottom_holo_dark.9.png
index 43e6528..9471615 100644
--- a/core/res/res/drawable-mdpi/dialog_bottom_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/dialog_bottom_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_bottom_holo_light.9.png b/core/res/res/drawable-mdpi/dialog_bottom_holo_light.9.png
index 09a1cd8..0502b93 100644
--- a/core/res/res/drawable-mdpi/dialog_bottom_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/dialog_bottom_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_full_holo_dark.9.png b/core/res/res/drawable-mdpi/dialog_full_holo_dark.9.png
index bd5f9e0..f364b2e 100644
--- a/core/res/res/drawable-mdpi/dialog_full_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/dialog_full_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_full_holo_light.9.png b/core/res/res/drawable-mdpi/dialog_full_holo_light.9.png
index 45e9712..91c2076 100644
--- a/core/res/res/drawable-mdpi/dialog_full_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/dialog_full_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_middle_holo_dark.9.png b/core/res/res/drawable-mdpi/dialog_middle_holo_dark.9.png
index 8082ddd9..92788c9 100644
--- a/core/res/res/drawable-mdpi/dialog_middle_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/dialog_middle_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_middle_holo_light.9.png b/core/res/res/drawable-mdpi/dialog_middle_holo_light.9.png
index ccdcd1d..74b66f8 100644
--- a/core/res/res/drawable-mdpi/dialog_middle_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/dialog_middle_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_top_holo_dark.9.png b/core/res/res/drawable-mdpi/dialog_top_holo_dark.9.png
index 79aaffb..f25cfb6 100644
--- a/core/res/res/drawable-mdpi/dialog_top_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/dialog_top_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_top_holo_light.9.png b/core/res/res/drawable-mdpi/dialog_top_holo_light.9.png
index 0740051..ff3ff06 100644
--- a/core/res/res/drawable-mdpi/dialog_top_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/dialog_top_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_audio_bt.png b/core/res/res/drawable-mdpi/ic_audio_bt.png
new file mode 100644
index 0000000..282c643
--- /dev/null
+++ b/core/res/res/drawable-mdpi/ic_audio_bt.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_audio_bt_mute.png b/core/res/res/drawable-mdpi/ic_audio_bt_mute.png
new file mode 100644
index 0000000..017338e
--- /dev/null
+++ b/core/res/res/drawable-mdpi/ic_audio_bt_mute.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_audio_phone.png b/core/res/res/drawable-mdpi/ic_audio_phone.png
new file mode 100644
index 0000000..00ec59e
--- /dev/null
+++ b/core/res/res/drawable-mdpi/ic_audio_phone.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_audio_vol.png b/core/res/res/drawable-mdpi/ic_audio_vol.png
index 049e92a..c32fdbc 100644
--- a/core/res/res/drawable-mdpi/ic_audio_vol.png
+++ b/core/res/res/drawable-mdpi/ic_audio_vol.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_audio_vol_mute.png b/core/res/res/drawable-mdpi/ic_audio_vol_mute.png
index be71492..52611b6 100644
--- a/core/res/res/drawable-mdpi/ic_audio_vol_mute.png
+++ b/core/res/res/drawable-mdpi/ic_audio_vol_mute.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_sysbar_quicksettings.png b/core/res/res/drawable-mdpi/ic_sysbar_quicksettings.png
new file mode 100644
index 0000000..7928104
--- /dev/null
+++ b/core/res/res/drawable-mdpi/ic_sysbar_quicksettings.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/scrubber_control_disabled_holo.png b/core/res/res/drawable-mdpi/scrubber_control_disabled_holo.png
index 26f018f..66dc001 100644
--- a/core/res/res/drawable-mdpi/scrubber_control_disabled_holo.png
+++ b/core/res/res/drawable-mdpi/scrubber_control_disabled_holo.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/scrubber_control_holo.png b/core/res/res/drawable-mdpi/scrubber_control_holo.png
index 242c16d..6e0e85a 100644
--- a/core/res/res/drawable-mdpi/scrubber_control_holo.png
+++ b/core/res/res/drawable-mdpi/scrubber_control_holo.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/stat_notify_chat.png b/core/res/res/drawable-mdpi/stat_notify_chat.png
index 91b4290..36ac850 100644
--- a/core/res/res/drawable-mdpi/stat_notify_chat.png
+++ b/core/res/res/drawable-mdpi/stat_notify_chat.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/toast_frame.9.png b/core/res/res/drawable-mdpi/toast_frame.9.png
index 08c4f86..1b06b7c8 100755
--- a/core/res/res/drawable-mdpi/toast_frame.9.png
+++ b/core/res/res/drawable-mdpi/toast_frame.9.png
Binary files differ
diff --git a/core/res/res/drawable-xlarge-nodpi/default_wallpaper.jpg b/core/res/res/drawable-xlarge-nodpi/default_wallpaper.jpg
index 8729fe1..7d7cdbb 100644
--- a/core/res/res/drawable-xlarge-nodpi/default_wallpaper.jpg
+++ b/core/res/res/drawable-xlarge-nodpi/default_wallpaper.jpg
Binary files differ
diff --git a/core/res/res/layout/volume_adjust.xml b/core/res/res/layout/volume_adjust.xml
index 18da85f..b0ca3e8 100644
--- a/core/res/res/layout/volume_adjust.xml
+++ b/core/res/res/layout/volume_adjust.xml
@@ -17,56 +17,48 @@
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
-    android:background="@android:drawable/dialog_full_holo_dark"
     android:gravity="left">
 
     <LinearLayout
-        android:layout_width="416dip"
-        android:layout_height="wrap_content"
-        android:paddingLeft="16dip"
-        android:paddingTop="16dip"
-        android:paddingRight="16dip"
-        android:paddingBottom="8dip"
-        android:orientation="vertical">
-
-    <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:layout_marginBottom="8dip"
-        android:gravity="left">
-    
+        android:layout_marginTop="80dip"
+        android:background="@android:drawable/dialog_full_holo_dark"
+        android:orientation="horizontal"
+        >
+
+        <LinearLayout
+            android:id="@+id/slider_group"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:orientation="vertical"
+            >
+            <!-- Sliders go here -->
+        </LinearLayout>
+
         <ImageView
-            android:id="@+id/other_stream_icon"
+            android:id="@+id/expand_button_divider"
+            android:src="?attr/dividerVertical"
+            android:layout_width="wrap_content"
+            android:layout_height="32dip"
+            android:scaleType="fitXY"
+            android:layout_gravity="top"
+            android:layout_marginTop="16dip"
+            android:layout_marginBottom="16dip"
+            />
+
+        <ImageView
+            android:id="@+id/expand_button"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:layout_marginRight="16dip" />
-
-        <TextView
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:id="@+id/message"
-            android:textAppearance="?android:attr/textAppearanceMedium" />
-
+            android:layout_gravity="top"
+            android:padding="16dip"
+            android:background="?attr/selectableItemBackground"
+            android:src="@drawable/ic_sysbar_quicksettings"
+            />
+        
     </LinearLayout>
 
-    <TextView
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:id="@+id/additional_message"
-        android:textAppearance="?android:attr/textAppearanceSmall" />
-
-    <ImageView
-        android:id="@+id/ringer_stream_icon"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_marginTop="14dip" />
-
-    <ProgressBar
-        style="?android:attr/progressBarStyleHorizontal"
-        android:id="@+id/level"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content" />
-    </LinearLayout>
 </FrameLayout>
 
 
diff --git a/core/res/res/layout/volume_adjust_item.xml b/core/res/res/layout/volume_adjust_item.xml
new file mode 100644
index 0000000..e841d87
--- /dev/null
+++ b/core/res/res/layout/volume_adjust_item.xml
@@ -0,0 +1,45 @@
+<?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="wrap_content"
+    android:layout_height="80dip"
+    android:orientation="horizontal"
+    android:layout_marginTop="8dip"
+    android:layout_marginBottom="8dip"
+    android:gravity="left|center_vertical">
+
+    <ImageView
+        android:id="@+id/stream_icon"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:padding="16dip"
+        android:layout_marginLeft="8dip"
+        android:background="?attr/selectableItemBackground"
+        />
+
+    <SeekBar
+        style="?android:attr/seekBarStyle"
+        android:id="@+id/seekbar"
+        android:layout_width="300dip"
+        android:layout_height="wrap_content"
+        android:padding="16dip"
+        android:layout_marginLeft="8dip"
+        android:layout_marginRight="8dip" />
+
+</LinearLayout>
+
+
diff --git a/core/res/res/values/ids.xml b/core/res/res/values/ids.xml
index 7a0fede..d05685c 100644
--- a/core/res/res/values/ids.xml
+++ b/core/res/res/values/ids.xml
@@ -73,4 +73,5 @@
   <item type="id" name="fillInIntent" />
   <item type="id" name="rowTypeId" />
   <item type="id" name="up" />
+  <item type="id" name="action_menu_divider" />
 </resources>
diff --git a/core/res/res/values/styles.xml b/core/res/res/values/styles.xml
index e2751bd..5700641 100644
--- a/core/res/res/values/styles.xml
+++ b/core/res/res/values/styles.xml
@@ -208,6 +208,11 @@
         <item name="windowExitAnimation">@anim/fade_out</item>
     </style>
 
+    <!-- Window animations used for volume panel. -->
+    <style name="Animation.VolumePanel">
+        <item name="windowEnterAnimation">@null</item>
+        <item name="windowExitAnimation">@anim/fade_out</item>
+    </style>
     <!-- Status Bar Styles -->
 
     <style name="TextAppearance.StatusBar">
diff --git a/core/res/res/values/themes.xml b/core/res/res/values/themes.xml
index 38b068e..6d5b482 100644
--- a/core/res/res/values/themes.xml
+++ b/core/res/res/values/themes.xml
@@ -730,6 +730,11 @@
         <item name="android:windowCloseOnTouchOutside">false</item>
     </style>
 
+    <style name="Theme.Panel.Volume">
+        <item name="android:windowAnimationStyle">@android:style/Animation.VolumePanel</item>
+        <item name="android:windowCloseOnTouchOutside">true</item>
+    </style>
+
     <!-- Default theme with an Action Bar. -->
     <style name="Theme.WithActionBar">
         <item name="android:windowActionBar">true</item>
diff --git a/core/tests/coretests/src/android/util/LruCacheTest.java b/core/tests/coretests/src/android/util/LruCacheTest.java
new file mode 100644
index 0000000..506315d
--- /dev/null
+++ b/core/tests/coretests/src/android/util/LruCacheTest.java
@@ -0,0 +1,385 @@
+/*
+ * 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.util;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import junit.framework.TestCase;
+
+public final class LruCacheTest extends TestCase {
+    private int expectedCreateCount;
+    private int expectedPutCount;
+    private int expectedHitCount;
+    private int expectedMissCount;
+    private int expectedEvictionCount;
+
+    public void testStatistics() {
+        LruCache<String, String> cache = new LruCache<String, String>(3);
+        assertStatistics(cache);
+
+        assertEquals(null, cache.put("a", "A"));
+        expectedPutCount++;
+        assertStatistics(cache);
+        assertHit(cache, "a", "A");
+        assertSnapshot(cache, "a", "A");
+
+        assertEquals(null, cache.put("b", "B"));
+        expectedPutCount++;
+        assertStatistics(cache);
+        assertHit(cache, "a", "A");
+        assertHit(cache, "b", "B");
+        assertSnapshot(cache, "a", "A", "b", "B");
+
+        assertEquals(null, cache.put("c", "C"));
+        expectedPutCount++;
+        assertStatistics(cache);
+        assertHit(cache, "a", "A");
+        assertHit(cache, "b", "B");
+        assertHit(cache, "c", "C");
+        assertSnapshot(cache, "a", "A", "b", "B", "c", "C");
+
+        assertEquals(null, cache.put("d", "D"));
+        expectedPutCount++;
+        expectedEvictionCount++; // a should have been evicted
+        assertStatistics(cache);
+        assertMiss(cache, "a");
+        assertHit(cache, "b", "B");
+        assertHit(cache, "c", "C");
+        assertHit(cache, "d", "D");
+        assertHit(cache, "b", "B");
+        assertHit(cache, "c", "C");
+        assertSnapshot(cache, "d", "D", "b", "B", "c", "C");
+
+        assertEquals(null, cache.put("e", "E"));
+        expectedPutCount++;
+        expectedEvictionCount++; // d should have been evicted
+        assertStatistics(cache);
+        assertMiss(cache, "d");
+        assertMiss(cache, "a");
+        assertHit(cache, "e", "E");
+        assertHit(cache, "b", "B");
+        assertHit(cache, "c", "C");
+        assertSnapshot(cache, "e", "E", "b", "B", "c", "C");
+    }
+
+    public void testStatisticsWithCreate() {
+        LruCache<String, String> cache = newCreatingCache();
+        assertStatistics(cache);
+
+        assertCreated(cache, "aa", "created-aa");
+        assertHit(cache, "aa", "created-aa");
+        assertSnapshot(cache, "aa", "created-aa");
+
+        assertCreated(cache, "bb", "created-bb");
+        assertMiss(cache, "c");
+        assertSnapshot(cache, "aa", "created-aa", "bb", "created-bb");
+
+        assertCreated(cache, "cc", "created-cc");
+        assertSnapshot(cache, "aa", "created-aa", "bb", "created-bb", "cc", "created-cc");
+
+        expectedEvictionCount++; // aa will be evicted
+        assertCreated(cache, "dd", "created-dd");
+        assertSnapshot(cache, "bb", "created-bb",  "cc", "created-cc", "dd", "created-dd");
+
+        expectedEvictionCount++; // bb will be evicted
+        assertCreated(cache, "aa", "created-aa");
+        assertSnapshot(cache, "cc", "created-cc", "dd", "created-dd", "aa", "created-aa");
+    }
+
+    public void testCreateOnCacheMiss() {
+        LruCache<String, String> cache = newCreatingCache();
+        String created = cache.get("aa");
+        assertEquals("created-aa", created);
+    }
+
+    public void testNoCreateOnCacheHit() {
+        LruCache<String, String> cache = newCreatingCache();
+        cache.put("aa", "put-aa");
+        assertEquals("put-aa", cache.get("aa"));
+    }
+
+    public void testConstructorDoesNotAllowZeroCacheSize() {
+        try {
+            new LruCache<String, String>(0);
+            fail();
+        } catch (IllegalArgumentException expected) {
+        }
+    }
+
+    public void testCannotPutNullKey() {
+        LruCache<String, String> cache = new LruCache<String, String>(3);
+        try {
+            cache.put(null, "A");
+            fail();
+        } catch (NullPointerException expected) {
+        }
+    }
+
+    public void testCannotPutNullValue() {
+        LruCache<String, String> cache = new LruCache<String, String>(3);
+        try {
+            cache.put("a", null);
+            fail();
+        } catch (NullPointerException expected) {
+        }
+    }
+
+    public void testToString() {
+        LruCache<String, String> cache = new LruCache<String, String>(3);
+        assertEquals("LruCache[maxSize=3,hits=0,misses=0,hitRate=0%]", cache.toString());
+
+        cache.put("a", "A");
+        cache.put("b", "B");
+        cache.put("c", "C");
+        cache.put("d", "D");
+
+        cache.get("a"); // miss
+        cache.get("b"); // hit
+        cache.get("c"); // hit
+        cache.get("d"); // hit
+        cache.get("e"); // miss
+
+        assertEquals("LruCache[maxSize=3,hits=3,misses=2,hitRate=60%]", cache.toString());
+    }
+
+    public void testEvictionWithSingletonCache() {
+        LruCache<String, String> cache = new LruCache<String, String>(1);
+        cache.put("a", "A");
+        cache.put("b", "B");
+        assertSnapshot(cache, "b", "B");
+    }
+
+    public void testEntryEvictedWhenFull() {
+        List<String> expectedEvictionLog = new ArrayList<String>();
+        final List<String> evictionLog = new ArrayList<String>();
+        LruCache<String, String> cache = new LruCache<String, String>(3) {
+            @Override protected void entryEvicted(String key, String value) {
+                evictionLog.add(key + "=" + value);
+            }
+        };
+
+        cache.put("a", "A");
+        cache.put("b", "B");
+        cache.put("c", "C");
+        assertEquals(expectedEvictionLog, evictionLog);
+
+        cache.put("d", "D");
+        expectedEvictionLog.add("a=A");
+        assertEquals(expectedEvictionLog, evictionLog);
+    }
+
+    /**
+     * Replacing the value for a key doesn't cause an eviction but it does bring
+     * the replaced entry to the front of the queue.
+     */
+    public void testPutDoesNotCauseEviction() {
+        final List<String> evictionLog = new ArrayList<String>();
+        List<String> expectedEvictionLog = new ArrayList<String>();
+        LruCache<String, String> cache = new LruCache<String, String>(3) {
+            @Override protected void entryEvicted(String key, String value) {
+                evictionLog.add(key + "=" + value);
+            }
+        };
+
+        cache.put("a", "A");
+        cache.put("b", "B");
+        cache.put("c", "C");
+        cache.put("b", "B2");
+        assertEquals(expectedEvictionLog, evictionLog);
+        assertSnapshot(cache, "a", "A", "c", "C", "b", "B2");
+    }
+
+    public void testCustomSizesImpactsSize() {
+        LruCache<String, String> cache = new LruCache<String, String>(10) {
+            @Override protected int sizeOf(String key, String value) {
+                return key.length() + value.length();
+            }
+        };
+
+        assertEquals(0, cache.size());
+        cache.put("a", "AA");
+        assertEquals(3, cache.size());
+        cache.put("b", "BBBB");
+        assertEquals(8, cache.size());
+        cache.put("a", "");
+        assertEquals(6, cache.size());
+    }
+
+    public void testEvictionWithCustomSizes() {
+        LruCache<String, String> cache = new LruCache<String, String>(4) {
+            @Override protected int sizeOf(String key, String value) {
+                return value.length();
+            }
+        };
+
+        cache.put("a", "AAAA");
+        assertSnapshot(cache, "a", "AAAA");
+        cache.put("b", "BBBB"); // should evict a
+        assertSnapshot(cache, "b", "BBBB");
+        cache.put("c", "CC"); // should evict b
+        assertSnapshot(cache, "c", "CC");
+        cache.put("d", "DD");
+        assertSnapshot(cache, "c", "CC", "d", "DD");
+        cache.put("e", "E"); // should evict c
+        assertSnapshot(cache, "d", "DD", "e", "E");
+        cache.put("f", "F");
+        assertSnapshot(cache, "d", "DD", "e", "E", "f", "F");
+        cache.put("g", "G"); // should evict d
+        assertSnapshot(cache, "e", "E", "f", "F", "g", "G");
+        cache.put("h", "H");
+        assertSnapshot(cache, "e", "E", "f", "F", "g", "G", "h", "H");
+        cache.put("i", "III"); // should evict e, f, and g
+        assertSnapshot(cache, "h", "H", "i", "III");
+        cache.put("j", "JJJ"); // should evict h and i
+        assertSnapshot(cache, "j", "JJJ");
+    }
+
+    public void testEvictionThrowsWhenSizesAreInconsistent() {
+        LruCache<String, int[]> cache = new LruCache<String, int[]>(4) {
+            @Override protected int sizeOf(String key, int[] value) {
+                return value[0];
+            }
+        };
+
+        int[] a = { 4 };
+        cache.put("a", a);
+
+        // get the cache size out of sync
+        a[0] = 1;
+        assertEquals(4, cache.size());
+
+        // evict something
+        try {
+            cache.put("b", new int[] { 2 });
+            fail();
+        } catch (IllegalStateException expected) {
+        }
+    }
+
+    public void testEvictionThrowsWhenSizesAreNegative() {
+        LruCache<String, String> cache = new LruCache<String, String>(4) {
+            @Override protected int sizeOf(String key, String value) {
+                return -1;
+            }
+        };
+
+        try {
+            cache.put("a", "A");
+            fail();
+        } catch (IllegalStateException expected) {
+        }
+    }
+
+    /**
+     * Naive caches evict at most one element at a time. This is problematic
+     * because evicting a small element may be insufficient to make room for a
+     * large element.
+     */
+    public void testDifferentElementSizes() {
+        LruCache<String, String> cache = new LruCache<String, String>(10) {
+            @Override protected int sizeOf(String key, String value) {
+                return value.length();
+            }
+        };
+
+        cache.put("a", "1");
+        cache.put("b", "12345678");
+        cache.put("c", "1");
+        assertSnapshot(cache, "a", "1", "b", "12345678", "c", "1");
+        cache.put("d", "12345678"); // should evict a and b
+        assertSnapshot(cache, "c", "1", "d", "12345678");
+        cache.put("e", "12345678"); // should evict c and d
+        assertSnapshot(cache, "e", "12345678");
+    }
+
+    public void testEvictAll() {
+        final List<String> evictionLog = new ArrayList<String>();
+        LruCache<String, String> cache = new LruCache<String, String>(10) {
+            @Override protected void entryEvicted(String key, String value) {
+                evictionLog.add(key + "=" + value);
+            }
+        };
+
+        cache.put("a", "A");
+        cache.put("b", "B");
+        cache.put("c", "C");
+        cache.evictAll();
+        assertEquals(0, cache.size());
+        assertEquals(Arrays.asList("a=A", "b=B", "c=C"), evictionLog);
+    }
+
+    public void testEvictAllEvictsSizeZeroElements() {
+        LruCache<String, String> cache = new LruCache<String, String>(10) {
+            @Override protected int sizeOf(String key, String value) {
+                return 0;
+            }
+        };
+
+        cache.put("a", "A");
+        cache.put("b", "B");
+        cache.evictAll();
+        assertSnapshot(cache);
+    }
+
+    private LruCache<String, String> newCreatingCache() {
+        return new LruCache<String, String>(3) {
+            @Override protected String create(String key) {
+                return (key.length() > 1) ? ("created-" + key) : null;
+            }
+        };
+    }
+
+    private void assertHit(LruCache<String, String> cache, String key, String value) {
+        assertEquals(value, cache.get(key));
+        expectedHitCount++;
+        assertStatistics(cache);
+    }
+
+    private void assertMiss(LruCache<String, String> cache, String key) {
+        assertEquals(null, cache.get(key));
+        expectedMissCount++;
+        assertStatistics(cache);
+    }
+
+    private void assertCreated(LruCache<String, String> cache, String key, String value) {
+        assertEquals(value, cache.get(key));
+        expectedMissCount++;
+        expectedCreateCount++;
+        assertStatistics(cache);
+    }
+
+    private void assertStatistics(LruCache<?, ?> cache) {
+        assertEquals("create count", expectedCreateCount, cache.createCount());
+        assertEquals("put count", expectedPutCount, cache.putCount());
+        assertEquals("hit count", expectedHitCount, cache.hitCount());
+        assertEquals("miss count", expectedMissCount, cache.missCount());
+        assertEquals("eviction count", expectedEvictionCount, cache.evictionCount());
+    }
+
+    private <T> void assertSnapshot(LruCache<T, T> cache, T... keysAndValues) {
+        List<T> actualKeysAndValues = new ArrayList<T>();
+        for (Map.Entry<T, T> entry : cache.snapshot().entrySet()) {
+            actualKeysAndValues.add(entry.getKey());
+            actualKeysAndValues.add(entry.getValue());
+        }
+
+        // assert using lists because order is important for LRUs
+        assertEquals(Arrays.asList(keysAndValues), actualKeysAndValues);
+    }
+}
diff --git a/data/sounds/alarms/ogg/Barium.ogg b/data/sounds/alarms/ogg/Barium.ogg
index 2a91185..9a92022 100644
--- a/data/sounds/alarms/ogg/Barium.ogg
+++ b/data/sounds/alarms/ogg/Barium.ogg
Binary files differ
diff --git a/data/sounds/alarms/ogg/Cesium.ogg b/data/sounds/alarms/ogg/Cesium.ogg
index 76eca08..a8c379a 100644
--- a/data/sounds/alarms/ogg/Cesium.ogg
+++ b/data/sounds/alarms/ogg/Cesium.ogg
Binary files differ
diff --git a/data/sounds/effects/ogg/KeypressDelete.ogg b/data/sounds/effects/ogg/KeypressDelete.ogg
index d5ba9fa..5e724f4 100644
--- a/data/sounds/effects/ogg/KeypressDelete.ogg
+++ b/data/sounds/effects/ogg/KeypressDelete.ogg
Binary files differ
diff --git a/data/sounds/effects/ogg/KeypressReturn.ogg b/data/sounds/effects/ogg/KeypressReturn.ogg
index 0111365..a1200b2 100644
--- a/data/sounds/effects/ogg/KeypressReturn.ogg
+++ b/data/sounds/effects/ogg/KeypressReturn.ogg
Binary files differ
diff --git a/data/sounds/effects/ogg/KeypressSpacebar.ogg b/data/sounds/effects/ogg/KeypressSpacebar.ogg
index 1776762..0d0fbf1 100644
--- a/data/sounds/effects/ogg/KeypressSpacebar.ogg
+++ b/data/sounds/effects/ogg/KeypressSpacebar.ogg
Binary files differ
diff --git a/data/sounds/effects/ogg/KeypressStandard.ogg b/data/sounds/effects/ogg/KeypressStandard.ogg
index a261975..5878135 100644
--- a/data/sounds/effects/ogg/KeypressStandard.ogg
+++ b/data/sounds/effects/ogg/KeypressStandard.ogg
Binary files differ
diff --git a/data/sounds/effects/ogg/Lock.ogg b/data/sounds/effects/ogg/Lock.ogg
index a24df3d..2e57d9e 100644
--- a/data/sounds/effects/ogg/Lock.ogg
+++ b/data/sounds/effects/ogg/Lock.ogg
Binary files differ
diff --git a/data/sounds/effects/ogg/LowBattery.ogg b/data/sounds/effects/ogg/LowBattery.ogg
index dfb5d88..c21218c 100644
--- a/data/sounds/effects/ogg/LowBattery.ogg
+++ b/data/sounds/effects/ogg/LowBattery.ogg
Binary files differ
diff --git a/data/sounds/effects/ogg/Unlock.ogg b/data/sounds/effects/ogg/Unlock.ogg
index 114df93..490f98e 100644
--- a/data/sounds/effects/ogg/Unlock.ogg
+++ b/data/sounds/effects/ogg/Unlock.ogg
Binary files differ
diff --git a/data/sounds/notifications/Aldebaran.ogg b/data/sounds/notifications/Aldebaran.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/Antares.ogg b/data/sounds/notifications/Antares.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/Betelgeuse.ogg b/data/sounds/notifications/Betelgeuse.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/Canopus.ogg b/data/sounds/notifications/Canopus.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/CetiAlpha.ogg b/data/sounds/notifications/CetiAlpha.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/CetiAlpha.wav b/data/sounds/notifications/CetiAlpha.wav
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/Merope.ogg b/data/sounds/notifications/Merope.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/Sirrah.ogg b/data/sounds/notifications/Sirrah.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Antimony.ogg b/data/sounds/notifications/ogg/Antimony.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Argon.ogg b/data/sounds/notifications/ogg/Argon.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Beryllium.ogg b/data/sounds/notifications/ogg/Beryllium.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Cobalt.ogg b/data/sounds/notifications/ogg/Cobalt.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Fluorine.ogg b/data/sounds/notifications/ogg/Fluorine.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Gallium.ogg b/data/sounds/notifications/ogg/Gallium.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Helium.ogg b/data/sounds/notifications/ogg/Helium.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Iridium.ogg b/data/sounds/notifications/ogg/Iridium.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Krypton.ogg b/data/sounds/notifications/ogg/Krypton.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Palladium.ogg b/data/sounds/notifications/ogg/Palladium.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Radon.ogg b/data/sounds/notifications/ogg/Radon.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Rubidium.ogg b/data/sounds/notifications/ogg/Rubidium.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Selenium.ogg b/data/sounds/notifications/ogg/Selenium.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Strontium.ogg b/data/sounds/notifications/ogg/Strontium.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Thallium.ogg b/data/sounds/notifications/ogg/Thallium.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Xenon.ogg b/data/sounds/notifications/ogg/Xenon.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/notifications/ogg/Zirconium.ogg b/data/sounds/notifications/ogg/Zirconium.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Andromeda.ogg b/data/sounds/ringtones/ogg/Andromeda.ogg
index 8f6bd3e..26c230e 100644
--- a/data/sounds/ringtones/ogg/Andromeda.ogg
+++ b/data/sounds/ringtones/ogg/Andromeda.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Aquila.ogg b/data/sounds/ringtones/ogg/Aquila.ogg
index b391be9..9eab4ff 100644
--- a/data/sounds/ringtones/ogg/Aquila.ogg
+++ b/data/sounds/ringtones/ogg/Aquila.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/ArgoNavis.ogg b/data/sounds/ringtones/ogg/ArgoNavis.ogg
index b4202ac..8bee29e 100644
--- a/data/sounds/ringtones/ogg/ArgoNavis.ogg
+++ b/data/sounds/ringtones/ogg/ArgoNavis.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Bootes.ogg b/data/sounds/ringtones/ogg/Bootes.ogg
index 0716a4f..4634294 100644
--- a/data/sounds/ringtones/ogg/Bootes.ogg
+++ b/data/sounds/ringtones/ogg/Bootes.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/CanisMajor.ogg b/data/sounds/ringtones/ogg/CanisMajor.ogg
index 177d3de..0e575e0 100644
--- a/data/sounds/ringtones/ogg/CanisMajor.ogg
+++ b/data/sounds/ringtones/ogg/CanisMajor.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Cassiopeia.ogg b/data/sounds/ringtones/ogg/Cassiopeia.ogg
index c4a7948..942d4e4 100644
--- a/data/sounds/ringtones/ogg/Cassiopeia.ogg
+++ b/data/sounds/ringtones/ogg/Cassiopeia.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Centaurus.ogg b/data/sounds/ringtones/ogg/Centaurus.ogg
index 404bdbc..79a393c 100644
--- a/data/sounds/ringtones/ogg/Centaurus.ogg
+++ b/data/sounds/ringtones/ogg/Centaurus.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Cygnus.ogg b/data/sounds/ringtones/ogg/Cygnus.ogg
index b2e1e65..80317ef 100644
--- a/data/sounds/ringtones/ogg/Cygnus.ogg
+++ b/data/sounds/ringtones/ogg/Cygnus.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Draco.ogg b/data/sounds/ringtones/ogg/Draco.ogg
index 88d5a04..d09b891 100644
--- a/data/sounds/ringtones/ogg/Draco.ogg
+++ b/data/sounds/ringtones/ogg/Draco.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Eridani.ogg b/data/sounds/ringtones/ogg/Eridani.ogg
index b665a29..8d8a1f0 100644
--- a/data/sounds/ringtones/ogg/Eridani.ogg
+++ b/data/sounds/ringtones/ogg/Eridani.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Hydra.ogg b/data/sounds/ringtones/ogg/Hydra.ogg
index edde14f..935c12f 100644
--- a/data/sounds/ringtones/ogg/Hydra.ogg
+++ b/data/sounds/ringtones/ogg/Hydra.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Iridium.ogg b/data/sounds/ringtones/ogg/Iridium.ogg
old mode 100755
new mode 100644
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Lyra.ogg b/data/sounds/ringtones/ogg/Lyra.ogg
index 696f278..e4bf37a 100644
--- a/data/sounds/ringtones/ogg/Lyra.ogg
+++ b/data/sounds/ringtones/ogg/Lyra.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Machina.ogg b/data/sounds/ringtones/ogg/Machina.ogg
index ac16f7e..33388e6 100644
--- a/data/sounds/ringtones/ogg/Machina.ogg
+++ b/data/sounds/ringtones/ogg/Machina.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Orion.ogg b/data/sounds/ringtones/ogg/Orion.ogg
index 807f107..0323e4d 100644
--- a/data/sounds/ringtones/ogg/Orion.ogg
+++ b/data/sounds/ringtones/ogg/Orion.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Pegasus.ogg b/data/sounds/ringtones/ogg/Pegasus.ogg
index 66c4970..d1bf4b0 100644
--- a/data/sounds/ringtones/ogg/Pegasus.ogg
+++ b/data/sounds/ringtones/ogg/Pegasus.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Perseus.ogg b/data/sounds/ringtones/ogg/Perseus.ogg
index ad06021..e5f3fc2 100644
--- a/data/sounds/ringtones/ogg/Perseus.ogg
+++ b/data/sounds/ringtones/ogg/Perseus.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Pyxis.ogg b/data/sounds/ringtones/ogg/Pyxis.ogg
index 2d3adce..8f66bea 100644
--- a/data/sounds/ringtones/ogg/Pyxis.ogg
+++ b/data/sounds/ringtones/ogg/Pyxis.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Rigel.ogg b/data/sounds/ringtones/ogg/Rigel.ogg
index af2c176..4fcb3c0 100644
--- a/data/sounds/ringtones/ogg/Rigel.ogg
+++ b/data/sounds/ringtones/ogg/Rigel.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Scarabaeus.ogg b/data/sounds/ringtones/ogg/Scarabaeus.ogg
index e70fc69..3dcd0d7 100644
--- a/data/sounds/ringtones/ogg/Scarabaeus.ogg
+++ b/data/sounds/ringtones/ogg/Scarabaeus.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Sceptrum.ogg b/data/sounds/ringtones/ogg/Sceptrum.ogg
index fc50aef..a006afe 100644
--- a/data/sounds/ringtones/ogg/Sceptrum.ogg
+++ b/data/sounds/ringtones/ogg/Sceptrum.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Solarium.ogg b/data/sounds/ringtones/ogg/Solarium.ogg
index d27f141..108ba11 100644
--- a/data/sounds/ringtones/ogg/Solarium.ogg
+++ b/data/sounds/ringtones/ogg/Solarium.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Testudo.ogg b/data/sounds/ringtones/ogg/Testudo.ogg
index 0ca8d6b..42db3a5 100644
--- a/data/sounds/ringtones/ogg/Testudo.ogg
+++ b/data/sounds/ringtones/ogg/Testudo.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/UrsaMinor.ogg b/data/sounds/ringtones/ogg/UrsaMinor.ogg
index c0010e82..5591d73 100644
--- a/data/sounds/ringtones/ogg/UrsaMinor.ogg
+++ b/data/sounds/ringtones/ogg/UrsaMinor.ogg
Binary files differ
diff --git a/data/sounds/ringtones/ogg/Vespa.ogg b/data/sounds/ringtones/ogg/Vespa.ogg
index 4423bbb..6fb8ebd 100644
--- a/data/sounds/ringtones/ogg/Vespa.ogg
+++ b/data/sounds/ringtones/ogg/Vespa.ogg
Binary files differ
diff --git a/data/sounds/ringtones/wav/Carina.wav b/data/sounds/ringtones/wav/Carina.wav
old mode 100755
new mode 100644
Binary files differ
diff --git a/docs/html/guide/appendix/faq/commontasks.jd b/docs/html/guide/appendix/faq/commontasks.jd
index 200a93f..4747379 100644
--- a/docs/html/guide/appendix/faq/commontasks.jd
+++ b/docs/html/guide/appendix/faq/commontasks.jd
@@ -124,8 +124,9 @@
 <h2>Implementing Activity Callbacks</h2>
 <p>Android calls a number of callbacks to let you draw your screen, store data before
     pausing, and refresh data after closing. You must implement at least some of
-    these methods. See <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Lifecycles</a>
-    discussion in Application Fundamentals to learn when and in what order these methods 
+    these methods. See the <a
+href="{@docRoot}guide/topics/fundamentals/activites.html#Lifecycle">Activities</a>
+    document to learn when and in what order these methods 
     are called. Here are some of the standard types of screen classes that Android provides:</p>
 <ul>
     <li>{@link android.app.Activity android.app.Activity} - This is a standard screen,
@@ -150,9 +151,9 @@
 <p>When you open a new screen you can decide whether to make it transparent or floating,
     or full-screen. The choice of new screen affects the event sequence of events
     in the old screen (if the new screen obscures the old screen, a different
-    series of events is called in the old screen). See <a
-    href="{@docRoot}guide/topics/fundamentals.html#lcycles">Lifecycles</a> discussion
-    in Application Fundamentals for details. </p> 
+    series of events is called in the old screen). See the <a
+    href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activities</a> document for
+details. </p> 
 <p>Transparent or floating windows are implemented in three
     standard ways: </p>
 <ul>
@@ -309,7 +310,8 @@
     the application is finalized. See the topics for {@link android.app.Activity#onSaveInstanceState} and
     {@link android.app.Activity#onCreate} for
     examples of storing and retrieving state.</p>
-<p>Read more about the lifecycle of an application in <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p>
+<p>Read more about the lifecycle of an activity in <a
+href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a> document.</p>
 <h3>Storing and Retrieving Larger or More Complex Persistent Data<a name="storingandretrieving" id="storingandretrieving"></a></h3>
 <p>Your application can store files or complex collection objects, and reserve them
     for private use by itself or other activities in the application, or it can expose
diff --git a/docs/html/guide/appendix/install-location.jd b/docs/html/guide/appendix/install-location.jd
index 914aa66..7f96809 100644
--- a/docs/html/guide/appendix/install-location.jd
+++ b/docs/html/guide/appendix/install-location.jd
@@ -193,7 +193,7 @@
 provide additional services when innactive. When external storage becomes unavailable and a game
 process is killed, there should be no visible effect when the storage becomes available again and
 the user restarts the game (assuming that the game properly saved its state during the normal
-<a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Activity lifecycle</a>).</p>
+<a href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activity lifecycle</a>).</p>
 
 <p>If your application requires several megabytes for the APK file, you should
 carefully consider whether to enable the application to install on the external storage so that
diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs
index ab52999..dfc4f7b 100644
--- a/docs/html/guide/guide_toc.cs
+++ b/docs/html/guide/guide_toc.cs
@@ -28,6 +28,16 @@
         <span class="zh-CN" style="display:none">Android 是什么?</span>
         <span class="zh-TW" style="display:none">什麼是 Android?</span>
           </a></li>
+      <li><a href="<?cs var:toroot ?>guide/topics/fundamentals.html">
+        <span class="en">Application Fundamentals</span>
+        <span class="de" style="display:none">Anwendungsgrundlagen</span>
+        <span class="es" style="display:none">Fundamentos de las aplicaciones</span>
+        <span class="fr" style="display:none">Principes de base des applications</span>
+        <span class="it" style="display:none">Concetti fondamentali sulle applicazioni</span>
+        <span class="ja" style="display:none">開発の基礎</span>
+        <span class="zh-CN" style="display:none">应用程序基础</span>
+        <span class="zh-TW" style="display:none">應用程式基本原理</span>
+      </a></li>
 
   <!--  <li><a style="color:gray;">The Android SDK</a></li> -->
   <!--  <li><a style="color:gray;">Walkthrough for Developers</a></li> -->
@@ -47,21 +57,41 @@
       <span class="zh-TW" style="display:none">架構主題</span>
     </h2>
     <ul>
-      <li><a href="<?cs var:toroot ?>guide/topics/fundamentals.html">
-            <span class="en">Application Fundamentals</span>
-            <span class="de" style="display:none">Anwendungsgrundlagen</span>
-            <span class="es" style="display:none">Fundamentos de las aplicaciones</span>
-            <span class="fr" style="display:none">Principes de base des applications</span>
-            <span class="it" style="display:none">Concetti fondamentali sulle applicazioni</span>
-            <span class="ja" style="display:none">開発の基礎</span>
-            <span class="zh-CN" style="display:none">应用程序基础</span>
-            <span class="zh-TW" style="display:none">應用程式基本原理</span>
-
-          </a></li>
-      <li><a href="<?cs var:toroot ?>guide/topics/fundamentals/fragments.html">
+      <li class="toggle-list">
+        <div><a href="<?cs var:toroot ?>guide/topics/fundamentals/activities.html">
+          <span class="en">Activities</span>
+        </a></div>
+        <ul>
+          <li><a href="<?cs var:toroot ?>guide/topics/fundamentals/fragments.html">
             <span class="en">Fragments</span>
           </a> <span class="new">new!</span></li>
+          <li><a href="<?cs var:toroot ?>guide/topics/fundamentals/tasks-and-back-stack.html">
+            <span class="en">Tasks and Back Stack</span>
+          </a></li>
+        </ul>
+      </li>
+      <li class="toggle-list">
+        <div><a href="<?cs var:toroot ?>guide/topics/fundamentals/services.html">
+          <span class="en">Services</span>
+        </a></div>
+        <ul>
+          <li><a href="<?cs var:toroot ?>guide/topics/fundamentals/bound-services.html">
+            <span class="en">Bound Services</span>
+          </a></li>
+        </ul>
+      </li>
+      <li><a href="<?cs var:toroot ?>guide/topics/providers/content-providers.html">
+            <span class="en">Content Providers</span>
+          </a></li>
+      <li><a href="<?cs var:toroot ?>guide/topics/intents/intents-filters.html">
+            <span class="en">Intents and Intent Filters</span>
+          </a></li>
+      <li><a href="<?cs var:toroot ?>guide/topics/fundamentals/processes-and-threads.html">
+            <span class="en">Processes and Threads</span>
+          </a></li>
     </ul>
+
+
     <ul>
       <li class="toggle-list">
         <div><a href="<?cs var:toroot ?>guide/topics/ui/index.html">
@@ -95,7 +125,7 @@
                 <span class="en">Creating Status Bar Notifications</span>
               </a></li>
             </ul>
-          </li>
+          </li><!-- end of notifying the user -->
           <li><a href="<?cs var:toroot ?>guide/topics/ui/themes.html">
                 <span class="en">Applying Styles and Themes</span>
               </a></li>
@@ -112,7 +142,8 @@
                 <span class="en">How Android Draws Views</span>
               </a></li>
         </ul>
-      </li>
+      </li><!-- end of User Interface -->
+      
       <li class="toggle-list">
         <div><a href="<?cs var:toroot ?>guide/topics/resources/index.html">
                <span class="en">Application Resources</span>
@@ -144,12 +175,9 @@
               <li><a href="<?cs var:toroot ?>guide/topics/resources/style-resource.html">Style</a></li>
               <li><a href="<?cs var:toroot ?>guide/topics/resources/more-resources.html">More Types</a></li>
             </ul>
-          </li>
+          </li><!-- end of resource types -->
         </ul>
-      </li>
-      <li><a href="<?cs var:toroot ?>guide/topics/intents/intents-filters.html">
-            <span class="en">Intents and Intent Filters</span>
-          </a></li>
+      </li><!-- end of app resources -->
       <li class="toggle-list">
         <div><a href="<?cs var:toroot ?>guide/topics/data/data-storage.html">
             <span class="en">Data Storage</span>
@@ -161,18 +189,13 @@
             </li>
           </ul>
       </li>
-      <li><a href="<?cs var:toroot ?>guide/topics/providers/content-providers.html">
-            <span class="en">Content Providers</span>
-          </a></li>
       <li><a href="<?cs var:toroot ?>guide/topics/security/security.html">
             <span class="en">Security and Permissions</span>
           </a></li>
-  <!--  <li><a style="color:gray;">Processes and Threads</a></li> -->
-  <!--  <li><a style="color:gray;">Interprocess Communication</a></li> -->
       <li class="toggle-list">
         <div><a href="<?cs var:toroot ?>guide/topics/manifest/manifest-intro.html">
-               <span class="en">The AndroidManifest.xml File</span>
-             </a></div>
+          <span class="en">The AndroidManifest.xml File</span>
+        </a></div>
         <ul>
           <li><a href="<?cs var:toroot ?>guide/topics/manifest/action-element.html">&lt;action&gt;</a></li>
           <li><a href="<?cs var:toroot ?>guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></li>
@@ -199,8 +222,9 @@
           <li><a href="<?cs var:toroot ?>guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a></li>
           <li><a href="<?cs var:toroot ?>guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a></li>
         </ul>
-      </li>
-    </ul>
+      </li><!-- end of the manifest file -->
+    </ul>  
+      
     <ul>
       <li class="toggle-list">
         <div><a href="<?cs var:toroot ?>guide/topics/graphics/index.html">
@@ -252,6 +276,10 @@
       <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/network/sip.html">
+            <span class="en">Session Initiation Protocol</span></a>
+            <span class="new">new!</span>
+          </li>
       <li class="toggle-list">
         <div><a href="<?cs var:toroot?>guide/topics/search/index.html">
             <span class="en">Search</span>
@@ -510,33 +538,25 @@
           <li><a href="<?cs var:toroot ?>guide/developing/tools/logcat.html">logcat</a></li>
           <li><a href="<?cs var:toroot ?>guide/developing/tools/mksdcard.html">mksdcard</a></li>
           <li><a href="<?cs var:toroot ?>guide/developing/tools/monkey.html">Monkey</a></li>
-              <li class="toggle-list">
-                 <div>
-                     <a href="<?cs var:toroot ?>guide/developing/tools/monkeyrunner_concepts.html">
-                     <span class="en">monkeyrunner</span>
-                  </a>
-                  </div>
-                  <ul>
-                      <li>
-                          <a href="<?cs var:toroot ?>guide/developing/tools/MonkeyDevice.html">
-                                <span class="en">MonkeyDevice</span>
-                        </a>
-                    </li>
-                    <li>
-                        <a href="<?cs var:toroot ?>guide/developing/tools/MonkeyImage.html">
-                            <span class="en">MonkeyImage</span>
-                        </a>
-                    </li>
-                    <li>
-                        <a href="<?cs var:toroot ?>guide/developing/tools/MonkeyRunner.html">
-                            <span class="en">MonkeyRunner</span>
-                        </a>
-                    </li>
-                  </ul>
-              </li>
-              <li><a href="<?cs var:toroot ?>guide/developing/tools/proguard.html">ProGuard</a></li>
-              <li><a href="<?cs var:toroot ?>guide/developing/tools/adb.html#sqlite">sqlite3</a></li>
-              <li><a href="<?cs var:toroot ?>guide/developing/tools/traceview.html">Traceview</a></li>
+          <li class="toggle-list">
+            <div><a href="<?cs var:toroot ?>guide/developing/tools/monkeyrunner_concepts.html">
+              <span class="en">monkeyrunner</span>
+            </a></div>
+            <ul>
+              <li><a href="<?cs var:toroot ?>guide/developing/tools/MonkeyDevice.html">
+                <span class="en">MonkeyDevice</span>
+                </a></li>
+              <li><a href="<?cs var:toroot ?>guide/developing/tools/MonkeyImage.html">
+                <span class="en">MonkeyImage</span>
+                </a></li>
+              <li><a href="<?cs var:toroot ?>guide/developing/tools/MonkeyRunner.html">
+                <span class="en">MonkeyRunner</span>
+                </a></li>
+            </ul>
+          </li>
+          <li><a href="<?cs var:toroot ?>guide/developing/tools/proguard.html">ProGuard</a></li>
+          <li><a href="<?cs var:toroot ?>guide/developing/tools/adb.html#sqlite">sqlite3</a></li>
+          <li><a href="<?cs var:toroot ?>guide/developing/tools/traceview.html">Traceview</a></li>
           <li><a href="<?cs var:toroot ?>guide/developing/tools/zipalign.html">zipalign</a></li>
         </ul>
       </li>
diff --git a/docs/html/guide/index.jd b/docs/html/guide/index.jd
index 1ffea20..38f71c0 100644
--- a/docs/html/guide/index.jd
+++ b/docs/html/guide/index.jd
@@ -28,7 +28,7 @@
 
 <dt><b>Framework Topics</b></dt>
 <dd>Discussions of particular parts of the Android framework
-and API.  For an overview of the framework, begin with
+and API.  For an introduction to the framework, begin with
 <a href="{@docRoot}guide/topics/fundamentals.html">Application
 Fundamentals</a>.  Then explore other topics &mdash; from 
 designing a user interface and setting up resources to storing 
diff --git a/docs/html/guide/practices/ui_guidelines/activity_task_design.jd b/docs/html/guide/practices/ui_guidelines/activity_task_design.jd
index 6cb98e6..7f35b04 100644
--- a/docs/html/guide/practices/ui_guidelines/activity_task_design.jd
+++ b/docs/html/guide/practices/ui_guidelines/activity_task_design.jd
@@ -81,8 +81,10 @@
 <p>
   Be sure to look at the <a href="#design_tips">Design Tips</a> section
   for guidelines, tips, and things to avoid. This document is a
-  complement to <a href={@docRoot}guide/topics/fundamentals.html
-  title="Application Fundamentals">Application Fundamentals</a>, 
+  complement to the <a href="{@docRoot}guide/topics/fundamentals.html">Application
+Fundamentals</a> documentation (particularly the <a
+href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
+document),
   which covers the underlying mechanics for programmers.
 </p>
 
@@ -146,9 +148,9 @@
   
 <p>
   An activity handles a particular type of content (data) and accepts a
-  set of related user actions. In general, each activity has a 
-  <a href={@docRoot}guide/topics/fundamentals.html#actlife
-  title=lifecycle>lifecycle</a> that is independent of the other
+  set of related user actions. Each activity has a 
+  <a href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">lifecycle</a> that is
+independent of the other
   activities in its application or task &mdash; each activity is
   launched (started) independently, and the user or system can start,
   run, pause, resume, stop and restart it as needed. Because of this
@@ -225,9 +227,8 @@
 <p>
   An activity is the most prominent of four <em>components</em> of an
   application. The other components are service, content provider and
-  broadcast receiver. For more details on activities, see Activity in
-  <a href={@docRoot}guide/topics/fundamentals.html#appcomp
-  title="Application Components">Application Components</a>.
+  broadcast receiver. For more details on activities, see the
+  <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a> document.
 </p>
 
 
@@ -553,15 +554,6 @@
       network connection and allows the map to continue loading in the
       background.
 
-      <p>
-      Note that when you write an activity, you can make it stop or
-      continue running when it is moved to the background (see
-      onStop() in <a href={@docRoot}guide/topics/fundamentals.html#actlife
-      title="Activity Lifecycle">Activity Lifecycle</a>).
-      For activities that download data from the network, it's recommended
-      to let them continue downloading so the user can multi-task.
-      </p>
-
     </li>
 
     <li>
@@ -715,9 +707,8 @@
     </p>
 
     <p>
-      For more on intents, see {@link android.content.Intent Intent class} and
-      <a href={@docRoot}guide/topics/fundamentals.html#ifilters
-      title="intent filters">intent filters</a>.
+      For more about intents, see <a
+href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Filters</a>.
     </p>
 
 
@@ -914,8 +905,8 @@
         Home screen), or from a shortcut icon on the Home screen, or
         from the task switcher.  (The mechanism for this is for the
         activity to have an 
-        <a href={@docRoot}guide/topics/fundamentals.html#ifilters
-        title="Intent filter">intent filter</a> with action MAIN and
+        <a href={@docRoot}guide/topics/intents/intents-filters.html>intent filter</a> with action
+MAIN and
         category LAUNCHER.)
       </li>
     </ul>
diff --git a/docs/html/guide/publishing/licensing.jd b/docs/html/guide/publishing/licensing.jd
index e099413..5551384 100644
--- a/docs/html/guide/publishing/licensing.jd
+++ b/docs/html/guide/publishing/licensing.jd
@@ -2123,7 +2123,7 @@
 <tr>
 <td>LICENSED</td>
 <td>The application is licensed to the user. The user has purchased the
-application or the application is free.</td>
+application or the application only exists as a draft.</td>
 <td>Yes</td>
 <td><code>VT</code>,&nbsp;<code>GT</code>, <code>GR</code></td>
 <td><em>Allow access according to Policy constraints.</em></td>
@@ -2201,6 +2201,17 @@
 
 </table>
 
+<p class="note"><strong>Note:</strong> As documented in <a href="#test-env">
+Setting Up The Testing Environment</a>, the response code can be manually
+overridden for the application developer and any registered test users via the
+Android Market publisher site.
+<br/><br/>
+Additionally, as noted above, applications that are in draft mode (in other
+words, applicaitons that have been uploaded but have <em>never</em> been
+published) will return LICENSED for all users, even if not listed as a test
+user. Since the application has never been offered for download, it is assumed
+that any users running it must have obtained it from an authorized channel for
+testing purposes.</p>
 
 <h2 id="extras">Server Response Extras</h2>
 
diff --git a/docs/html/guide/topics/appwidgets/index.jd b/docs/html/guide/topics/appwidgets/index.jd
index 3de5627..89306a2 100644
--- a/docs/html/guide/topics/appwidgets/index.jd
+++ b/docs/html/guide/topics/appwidgets/index.jd
@@ -333,10 +333,10 @@
 on the period defined by the first one and the second update period will be ignored 
 (they'll both be updated every two hours, not every hour).</p>
 
-<p class="note"><strong>Note:</strong> Because the AppWidgetProvider is a BroadcastReceiver,
-your process is not guaranteed to keep running after the callback methods return (see
-<a href="{@docRoot}guide/topics/fundamentals.html#broadlife">Application Fundamentals &gt;
-Broadcast Receiver Lifecycle</a> for more information). If your App Widget setup process can take several
+<p class="note"><strong>Note:</strong> Because {@link android.appwidget.AppWidgetProvider} is an
+extension of {@link android.content.BroadcastReceiver}, your process is not guaranteed to keep
+running after the callback methods return (see {@link android.content.BroadcastReceiver} for
+information about the broadcast lifecycle). If your App Widget setup process can take several
 seconds (perhaps while performing web requests) and you require that your process continues, 
 consider starting a {@link android.app.Service} 
 in the {@link android.appwidget.AppWidgetProvider#onUpdate(Context,AppWidgetManager,int[])
diff --git a/docs/html/guide/topics/fundamentals.jd b/docs/html/guide/topics/fundamentals.jd
index 1658fa6..f427a92 100644
--- a/docs/html/guide/topics/fundamentals.jd
+++ b/docs/html/guide/topics/fundamentals.jd
@@ -4,1779 +4,512 @@
 <div id="qv-wrapper">
 <div id="qv">
 
-<h2>In this document</h2>
-<ol>
-<li><a href="#appcomp">Application Components</a>
-  <ol>
-    <li><a href="#actcomp">Activating components: intents</a></li>
-    <li><a href="#endcomp">Shutting down components</a></li>
-    <li><a href="#manfile">The manifest file</a></li>
-    <li><a href="#ifilters">Intent filters</a></li>
-  </ol></li>
-<li><a href="#acttask">Activities and Tasks</a>
-  <ol>
-    <li><a href="#afftask">Affinities and new tasks</a></li>
-    <li><a href="#lmodes">Launch modes</a></li>
-    <li><a href="#clearstack">Clearing the stack</a></li>
-    <li><a href="#starttask">Starting tasks</a></li>
-    <li><a href="#commonpatterns">Common patterns</a></li>
-  </ol></li>
-<li><a href="#procthread">Processes and Threads</a>
-  <ol>
-    <li><a href="#procs">Processes</a></li>
-    <li><a href="#threads">Threads</a></li>
-    <li><a href="#rpc">Remote procedure calls</a></li>
-    <li><a href="#tsafe">Thread-safe methods</a></li>
-  </ol></li>
-<li><a href="#lcycles">Component Lifecycles</a>
-  <ol>
-    <li><a href="#actlife">Activity lifecycle</a></li>
-    <li><a href="#servlife">Service lifecycle</a></li>
-    <li><a href="#broadlife">Broadcast receiver lifecycle</a></li>
-    <li><a href="#proclife">Processes and lifecycles</a></li>
-  </ol></li>
-</ol>
-
-<h2>Key classes</h2>
-<ol>
-<li>{@link android.app.Activity}</li>
-<li>{@link android.app.Service}</li>
-<li>{@link android.content.BroadcastReceiver}</li>
-<li>{@link android.content.ContentProvider}</li>
-<li>{@link android.content.Intent}</li>
-</ol>
-
-</div>
-</div>
-
-<p>
-Android applications are written in the Java programming language. 
-The compiled Java code &mdash; along with any data and resource 
-files required by the application &mdash; is bundled into an 
-<i>Android package</i>, an archive file 
-marked by an {@code .apk} suffix. This file is the vehicle 
-for distributing the application and installing it on mobile devices; 
-it's the file users download to their devices.  All the code in a 
-single {@code .apk} file is considered to be one <i>application</i>.
-</p>
-
-<p>
-In many ways, each Android application lives in its own world:
-</p>
-
+<h2>Quickview</h2>
 <ul>
-<li>By default, every application runs in its own Linux process.
-Android starts the process when any of the application's code needs to be 
-executed, and shuts down the process when it's no longer needed and system 
-resources are required by other applications.</li>
-
-<li>Each process has its own virtual machine (VM), so application code 
-runs in isolation from the code of all other applications.</li>
-
-<li>By default, each application is assigned a unique Linux user ID.  
-Permissions are set so that the application's files are visible only to
-that user and only to the application itself &mdash; although there are ways
-to export them to other applications as well.</li>
+  <li>Android applications are composed of one or more application components (activities,
+services, content providers, and broadcast receivers)</li>
+  <li>Each component performs a different role in the overall application behavior, and each
+one can be activated individually (even by other applications)</li>
+  <li>The manifest file must declare all components in the application and should also declare
+all application requirements, such as the minimum version of Android required and any hardware
+configurations required</li>
+  <li>Non-code application resources (images, strings, layout files, etc.) should include
+alternatives for different device configurations (such as different strings for different
+languages and different layouts for different screen sizes)</li>
 </ul>
 
-<p>
-It's possible to arrange for two applications to share the same user ID, 
-in which case they will be able to see each other's files.  To conserve 
-system resources, applications with the same ID can also arrange to run 
-in the same Linux process, sharing the same VM.
-</p>
+
+<h2>In this document</h2>
+<ol>
+<li><a href="#Components">Application Components</a>
+  <ol>
+    <li><a href="#ActivatingComponents">Activating components</a></li>
+  </ol>
+</li>
+<li><a href="#Manifest">The Manifest File</a>
+  <ol>
+    <li><a href="#DeclaringComponents">Declaring components</a></li>
+    <li><a href="#DeclaringRequirements">Declaring application requirements</a></li>
+  </ol>
+</li>
+<li><a href="#Resources">Application Resources</a></li>
+</ol>
+</div>
+</div>
+
+<p>Android applications are written in the Java programming language. The Android SDK tools compile
+the code&mdash;along with any data and resource files&mdash;into an <i>Android package</i>, an
+archive file with an {@code .apk} suffix. All the code in a single {@code .apk} file is considered
+to be one application and is the file that Android-powered devices use to install the
+application.</p>
+
+<p>Once installed on a device, each Android application lives in its own security sandbox: </p>
+
+<ul>
+ <li>The Android operating system is a multi-user Linux system in which each application is a
+different user.</li>
+
+<li>By default, the system assigns each application a unique Linux user ID (the ID is used only by
+the system and is unknown to the application). The system sets permissions for all the files in an
+application so that only the user ID assigned to that application can access them. </li>
+
+<li>Each process has its own virtual machine (VM), so an application's code runs in isolation from
+other applications.</li>
+
+<li>By default, every application runs in its own Linux process. Android starts the process when any
+of the application's components need to be executed, then shuts down the process when it's no longer
+needed or when the system must recover memory for other applications.</li>
+</ul>
+
+<p>In this way, the Android system implements the <em>principle of least privilege</em>. That is,
+each application, by default, has access only to the components that it requires to do its work and
+no more. This creates a very secure environment in which an application cannot access parts of
+the system for which it is not given permission.</p>
+
+<p>However, there are ways for an application to share data with other applications and for an
+application to access system services:</p>
+
+<ul>
+  <li>It's possible to arrange for two applications to share the same Linux user ID, in which case
+they are able to access each other's files.  To conserve system resources, applications with the
+same user ID can also arrange to run in the same Linux process and share the same VM (the
+applications must also be signed with the same certificate).</li>
+  <li>An application can request permission to access device data such as the user's
+contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more. All
+application permissions must be granted by the user at install time.</li>
+</ul>
+
+<p>That covers the basics regarding how an Android application exists within the system. The rest of
+this document introduces you to:</p>
+<ul>
+  <li>The core framework components that define your application.</li>
+  <li>The manifest file in which you declare components and required device features for your
+application.</li>
+  <li>Resources that are separate from the application code and allow your application to
+gracefully optimize its behavior for a variety of device configurations.</li>
+</ul>
+
+<p class="note"><strong>Tip:</strong> If you're new to Android development, we suggest that you
+follow the Beginner's Path link at the bottom of this page. For each document in the Application
+Fundamentals, the Beginner's Path points you to the document we suggest you read next, in order
+to get up to speed on the core Android concepts.</p>
 
 
-<h2 id="appcomp">Application Components</h2>
 
-<p>
-A central feature of Android is that one application can make use of elements 
-of other applications (provided those applications permit it).  For example, 
-if your application needs to display a scrolling list of images and another 
-application has developed a suitable scroller and made it available to others, 
-you can call upon that scroller to do the work, rather than develop your own.  
-Your application doesn't incorporate the code of the other application or 
-link to it.  Rather, it simply starts up that piece of the other application 
-when the need arises.
-</p>
+<h2 id="Components">Application Components</h2>
 
-<p>
-For this to work, the system must be able to start an application process 
-when any part of it is needed, and instantiate the Java objects for that part.  
-Therefore, unlike applications on most other systems, Android applications don't 
-have a single entry point for everything in the application (no {@code main()} 
-function, for example).  Rather, they have essential <i>components</i> that 
-the system can instantiate and run as needed.  There are four types of components:
-</p>
+<p>Application components are the essential building blocks of an Android application. Each
+component is a different point through which the system can enter your application. Not all
+components are actual entry points for the user and some depend on each other, but each one exists
+as its own entity and plays a specific role&mdash;each one is a unique building block that
+helps define your application's overall behavior.</p>
+
+<p>There are four different types of application components. Each type serves a distinct purpose
+and has a distinct lifecycle that defines how the component is created and destroyed.</p>
+
+<p>Here are the four types of application components:</p>
 
 <dl>
 
 <dt><b>Activities</b></dt>
-<dd>An <i>activity</i> presents a visual user interface for one focused endeavor 
-the user can undertake.  For example, an activity might present a list of 
-menu items users can choose from or it might display photographs along
-with their captions.  A text messaging application might have one activity 
-that shows a list of contacts to send messages to, a second activity to write 
-the message to the chosen contact, and other activities to review old messages 
-or change settings.  Though they work together to form a cohesive user interface, 
-each activity is independent of the others.  
-Each one is implemented as a subclass of the {@link android.app.Activity} base class.  
 
-<p>
-An application might consist of just one activity or, like the text messaging
-application just mentioned, it may contain several.  
-What the activities are, and how many there are depends, of course, on the 
-application and its design.  Typically, one of the activities is marked
-as the first one that should be presented to the user when the application is 
-launched.  Moving from one activity to another is accomplished by having the 
-current activity start the next one.  
-</p>
+<dd>An <i>activity</i> represents a single screen with a user interface. For example,
+an email application might have one activity that shows a list of new
+emails, another activity to compose an email, and another activity for reading emails. Although
+the activities work together to form a cohesive user experience in the email application, each one
+is independent of the others. As such, a different application can start any one of these
+activities (if the email application allows it). For example, a camera application can start the
+activity in the email application that composes new mail, in order for the user to share a picture.
 
-<p>
-Each activity is given a default window to draw in.  Typically, the window 
-fills the screen, but it might be smaller than the screen and float on top 
-of other windows.  An activity can also make use of additional windows &mdash; 
-for example, a pop-up dialog that calls for a user response in the midst of 
-the activity, or a window that presents users with vital information when they 
-select a particular item on-screen.
-</p>
+<p>An activity is implemented as a subclass of {@link android.app.Activity} and you can learn more
+about it in the <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a>
+developer guide.</p>
+</dd>
 
-<p>
-The visual content of the window is provided by a hierarchy of views &mdash; 
-objects derived from the base {@link android.view.View} class.  Each view 
-controls a particular rectangular space within the window.  Parent views 
-contain and organize the layout of their children.  Leaf views (those at the 
-bottom of the hierarchy) draw in the rectangles they control and respond to 
-user actions directed at that space.  Thus, views are where the activity's 
-interaction with the user takes place.  For example, a view might display 
-a small image and initiate an action when the user taps that image.  Android 
-has a number of ready-made views that you can use &mdash; including buttons, 
-text fields, scroll bars, menu items, check boxes, and more.
-</p>
 
-<p>
-A view hierarchy is placed within an activity's window by the 
-<code>{@link android.app.Activity#setContentView Activity.setContentView()}</code> 
-method.  The <i>content view</i> is the View object at the root of the hierarchy.  
-(See the separate <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> 
-document for more information on views and the hierarchy.)
-</p>
+<dt><b>Services</b></dt>
 
-<p><dt><b>Services</b></dt>
-<dd>A <i>service</i> doesn't have a visual user interface, but rather runs in 
-the background for an indefinite period of time.  For example, a service might 
-play background music as the user attends to other matters, or it might fetch 
-data over the network or calculate something and provide the result to activities 
-that need it.  Each service extends the {@link android.app.Service} base class.
+<dd>A <i>service</i> is a component that runs in the background to perform long-running
+operations or to perform work for remote processes. A service
+does not provide a user interface. For example, a service might play music in the background while
+the user is in a different application, or it might fetch data over the network without
+blocking user interaction with an activity. Another component, such as an activity, can start the
+service and let it run or bind to it in order to interact with it.
 
-<p>
-A prime example is a media player playing songs from a play list.  The player 
-application would probably have one or more activities that allow the user to 
-choose songs and start playing them.  However, the music playback itself would 
-not be handled by an activity because users will expect the music to keep 
-playing even after they leave the player and begin something different.  
-To keep the music going, the media player activity could start a service to run 
-in the background.  The system would then keep the music playback service running 
-even after the activity that started it leaves the screen.
-</p>
+<p>A service is implemented as a subclass of {@link android.app.Service} and you can learn more
+about it in the <a href="{@docRoot}guide/topics/fundamentals/services.html">Services</a> developer
+guide.</p>
+</dd>
 
-<p> 
-It's possible to connect to (bind to) an ongoing service (and start the service 
-if it's not already running).  While connected, you can communicate with the 
-service through an interface that the service exposes.  For the music service, 
-this interface might allow users to pause, rewind, stop, and restart the playback.
-</p>
-
-<p>
-Like activities and the other components, services run in the main thread of 
-the application process.  So that they won't block other components or the 
-user interface, they often spawn another thread for time-consuming tasks 
-(like music playback).  See <a href="#procthread">Processes and Threads</a>, later.
-</p></dd>
-
-<dt><b>Broadcast receivers</b></dt>
-<dd>A <i>broadcast receiver</i> is a component that does nothing but 
-receive and react to broadcast announcements.  Many broadcasts originate in 
-system code &mdash; for example, announcements that the timezone has changed, 
-that the battery is low, that a picture has been taken, or that the user 
-changed a language preference.  Applications can also initiate broadcasts
-&mdash; for example, to let other applications know that some data has been
-downloaded to the device and is available for them to use.
-
-<p>
-An application can have any number of broadcast receivers to respond to any 
-announcements it considers important.  All receivers extend the {@link 
-android.content.BroadcastReceiver} base class.
-</p>
-
-<p>
-Broadcast receivers do not display a user interface.  However, they may start
-an activity in response to the information they receive, or they may use 
-the {@link android.app.NotificationManager} to alert the user.  Notifications 
-can get the user's attention in various ways &mdash; flashing 
-the backlight, vibrating the device, playing a sound, and so on.  They 
-typically place a persistent icon in the status bar, which users can open to 
-get the message. 
-</p></dd>
 
 <dt><b>Content providers</b></dt>
-<dd>A <i>content provider</i> makes a specific set of the application's data 
-available to other applications. The data can be stored in the file system, 
-in an SQLite database, or in any other manner that makes sense.  
-The content provider extends the {@link android.content.ContentProvider} base 
-class to implement a standard set of methods that enable other applications 
-to retrieve and store data of the type it controls.  However, applications 
-do not call these methods directly.  Rather they use a {@link 
-android.content.ContentResolver} object and call its methods instead.  
-A ContentResolver can talk to any content provider; it cooperates with the
-provider to manage any interprocess communication that's involved. 
 
-<p>
-See the separate 
-<a href="{@docRoot}guide/topics/providers/content-providers.html">Content 
-Providers</a> document for more information on using content providers.
-</p></dd>
+<dd>A <i>content provider</i> manages a shared set of application data. You can store the data in
+the file system, an SQLite database, on the web, or any other persistent storage location your
+application can access. Through the content provider, other applications can query or even modify
+the data (if the content provider allows it). For example, the Android system provides a content
+provider that manages the user's contact information. As such, any application with the proper
+permissions can query part of the content provider (such as {@link
+android.provider.ContactsContract.Data}) to read and write information about a particular person.
+
+<p>Content providers are also useful for reading and writing data that is private to your
+application and not shared. For example, the <a
+href="{@docRoot}resources/samples/NotePad/index.html">Note Pad</a> sample application uses a
+content provider to save notes.</p>
+
+<p>A content provider is implemented as a subclass of {@link android.content.ContentProvider}
+and must implement a standard set of APIs that enable other applications to perform
+transactions. For more information, see the <a
+href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> developer
+guide.</p>
+</dd>
+
+
+<dt><b>Broadcast receivers</b></dt>
+
+<dd>A <i>broadcast receiver</i> is a component that responds to system-wide broadcast
+announcements.  Many broadcasts originate from the system&mdash;for example, a broadcast announcing
+that the screen has turned off, the battery is low, or a picture was captured.
+Applications can also initiate broadcasts&mdash;for example, to let other applications know that
+some data has been downloaded to the device and is available for them to use. Although broadcast
+receivers don't display a user interface, they may <a
+href="{@docRoot}guide/topics/ui/notifiers/notifications.html">create a status bar notification</a>
+to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is
+just a "gateway" to other components and is intended to do a very minimal amount of work. For
+instance, it might initiate a service to perform some work based on the event.
+
+<p>A broadcast receiver is implemented as a subclass of {@link android.content.BroadcastReceiver}
+and each broadcast is delivered as an {@link android.content.Intent} object. For more information,
+see the {@link android.content.BroadcastReceiver} class.</p>
+</dd>
 
 </dl>
 
-<p>
-Whenever there's a request that should be handled by a particular component, 
-Android makes sure that the application process of the component is running, 
-starting it if necessary, and that an appropriate instance of the component 
-is available, creating the instance if necessary.  
-</p>
 
 
-<h3 id="actcomp">Activating components: intents</h3> 
+<p>A unique aspect of the Android system design is that any application can start another
+application’s component. For example, if you want the user to capture a
+photo with the device camera, there's probably another application that does that and your
+application can use it, instead of developing an activity to capture a photo yourself. You don't
+need to incorporate or even link to the code from the camera application.
+Instead, you can simply start the activity in the camera application that captures a
+photo. When complete, the photo is even returned to your application so you can use it. To the user,
+it seems as if the camera is actually a part of your application.</p>
 
-<p>
-Content providers are activated when they're targeted by a request from a 
-ContentResolver.  The other three components &mdash; activities, services, 
-and broadcast receivers &mdash; are activated by asynchronous messages 
-called <i>intents</i>.  An intent is an {@link android.content.Intent} 
-object that holds the content of the message.  For activities and services,
-it names the action being requested and specifies the URI of the data to 
-act on, among other things. For example, it might convey a request for 
-an activity to present an image to the user or let the user edit some
-text.  For broadcast receivers, the Intent object names the action being 
-announced.  For example, it might announce to interested parties that the 
-camera button has been pressed.
-</p>
+<p>When the system starts a component, it starts the process for that application (if it's not
+already running) and instantiates the classes needed for the component. For example, if your
+application starts the activity in the camera application that captures a photo, that activity
+runs in the process that belongs to the camera application, not in your application's process.
+Therefore, unlike applications on most other systems, Android applications don't have a single entry
+point (there's no {@code main()} function, for example).</p>
 
-<p>
-There are separate methods for activating each type of component: 
-</p>
+<p>Because the system runs each application in a separate process with file permissions that
+restrict access to other applications, your application cannot directly activate a component from
+another application. The Android system, however, can. So, to activate a component in
+another application, you must deliver a message to the system that specifies your <em>intent</em> to
+start a particular component. The system then activates the component for you.</p>
 
+
+<h3 id="ActivatingComponents">Activating Components</h3>
+
+<p>Three of the four component types&mdash;activities, services, and
+broadcast receivers&mdash;are activated by an asynchronous message called an <em>intent</em>.
+Intents bind individual components to each other at runtime (you can think of them
+as the messengers that request an action from other components), whether the component belongs
+to your application or another.</p>
+
+<p>An intent is created with an {@link android.content.Intent} object, which defines a message to
+activate either a specific component or a specific <em>type</em> of component&mdash;an intent
+can be either explicit or implicit, respectively.</p>
+
+<p>For activities and services, an intent defines the action to perform (for example, to "view" or
+"send" something) and may specify the URI of the data to act on (among other things that the
+component being started might need to know). For example, an intent might convey a request for an
+activity to show an image or to open a web page. In some cases, you can start an
+activity to receive a result, in which case, the activity also returns
+the result in an {@link android.content.Intent} (for example, you can issue an intent to let
+the user pick a personal contact and have it returned to you&mdash;the return intent includes a
+URI pointing to the chosen contact).</p>
+
+<p>For broadcast receivers, the intent simply defines the
+announcement being broadcast (for example, a broadcast to indicate the device battery is low
+includes only a known action string that indicates "battery is low").</p>
+
+<p>The other component type, content provider, is not activated by intents. Rather, it is
+activated when targeted by a request from a {@link android.content.ContentResolver}. The content
+resolver handles all direct transactions with the content provider so that the component that's
+performing transactions with the provider doesn't need to and instead calls methods on the {@link
+android.content.ContentResolver} object. This leaves a layer of abstraction between the content
+provider and the component requesting information (for security).</p>
+
+<p>There are separate methods for activiting each type of component:</p>
 <ul>
-
-<li>An activity is launched (or given something new to do) by passing an 
-Intent object to <code>{@link android.content.Context#startActivity 
-Context.startActivity()}</code> or <code>{@link 
-android.app.Activity#startActivityForResult 
-Activity.startActivityForResult()}</code>.  The responding activity can 
-look at the initial intent that caused it to be launched by calling its 
-<code>{@link android.app.Activity#getIntent getIntent()}</code> method.  
-Android calls the activity's <code>{@link 
-android.app.Activity#onNewIntent onNewIntent()}</code> method to pass 
-it any subsequent intents.
-
-<p>
-One activity often starts the next one.  If it expects a result back from 
-the activity it's starting, it calls {@code startActivityForResult()} 
-instead of {@code startActivity()}.  For example, if it starts an activity 
-that lets the user pick a photo, it might expect to be returned the chosen 
-photo.  The result is returned in an Intent object that's passed to the 
-calling activity's <code>{@link android.app.Activity#onActivityResult 
-onActivityResult()}</code> method.
-</p>
-</li>
-
-<li><p>A service is started (or new instructions are given to an ongoing 
-service) by passing an Intent object to <code>{@link 
-android.content.Context#startService Context.startService()}</code>.  
-Android calls the service's <code>{@link android.app.Service#onStartCommand
-onStartCommand()}</code> method and passes it the Intent object.</p>
-
-<p>
-Similarly, an intent can be passed to <code>{@link 
-android.content.Context#bindService Context.bindService()}</code> to 
-establish an ongoing connection between the calling component and a 
-target service.  The service receives the Intent object in
-an <code>{@link android.app.Service#onBind onBind()}</code> call.
-(If the service is not already running, {@code bindService()} can
-optionally start it.)  For example, an activity might establish a connection 
-with the music playback service mentioned earlier so that it can provide 
-the user with the means (a user interface) for controlling the playback.  
-The activity would call {@code bindService()} to set up that connection, 
-and then call methods defined by the service to affect the playback.
-</p>
-
-<p>
-A later section, <a href="#rpc">Remote procedure calls</a>, has more details 
-about binding to a service.
-</p>
-</li>
-
-<li><p>An application can initiate a broadcast by passing an Intent object to 
-methods like <code>{@link 
-android.content.Context#sendBroadcast(Intent) Context.sendBroadcast()}</code>, 
-<code>{@link android.content.Context#sendOrderedBroadcast(Intent, String) 
-Context.sendOrderedBroadcast()}</code>, and <code>{@link 
-android.content.Context#sendStickyBroadcast Context.sendStickyBroadcast()}</code>
-in any of their variations.  Android delivers the intent to all interested 
-broadcast receivers by calling their <code>{@link 
-android.content.BroadcastReceiver#onReceive onReceive()}</code> methods.</p></li>
-
+  <li>You can start an activity (or give it something new to do) by
+passing an {@link android.content.Intent} to {@link android.content.Context#startActivity
+startActivity()} or {@link android.app.Activity#startActivityForResult startActivityForResult()}
+(when you want the activity to return a result).</li>
+  <li>You can start a service (or give new instructions to an ongoing service) by
+passing an {@link android.content.Intent} to {@link android.content.Context#startService
+startService()}. Or you can bind to the service by passing an {@link android.content.Intent} to
+{@link android.content.Context#bindService bindService()}.</li>
+  <li>You can initiate a broadcast by passing an {@link android.content.Intent} to methods like
+{@link android.content.Context#sendBroadcast(Intent) sendBroadcast()}, {@link
+android.content.Context#sendOrderedBroadcast(Intent, String) sendOrderedBroadcast()}, or {@link
+android.content.Context#sendStickyBroadcast sendStickyBroadcast()}.</li>
+  <li>You can perform a query to a content provider by calling {@link
+android.content.ContentProvider#query query()} on a {@link android.content.ContentResolver}.</li>
 </ul>
 
-<p>
-For more on intent messages, see the separate article, 
-<a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents 
-and Intent Filters</a>.
-</p>
+<p>For more information about using intents, see the <a
+href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and
+Intent Filters</a> document. More information about activating specific components is also provided
+in the following documents: <a
+href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a>, <a
+href="{@docRoot}guide/topics/fundamentals/services.html">Services</a>, {@link
+android.content.BroadcastReceiver} and <a
+href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>.</p>
 
 
-<h3 id="endcomp">Shutting down components</h3>
+<h2 id="Manifest">The Manifest File</h2>
 
-<p>
-A content provider is active only while it's responding to a request from 
-a ContentResolver.  And a broadcast receiver is active only while it's 
-responding to a broadcast message.  So there's no need to explicitly shut 
-down these components.
-</p>
+<p>Before the Android system can start an application component, the system must know that the
+component exists by reading the application's {@code AndroidManifest.xml} file (the "manifest"
+file). Your application must declare all its components in this file, which must be at the root of
+the application project directory.</p>
 
-<p>
-Activities, on the other hand, provide the user interface.  They're 
-in a long-running conversation with the user and may remain active, 
-even when idle, as long as the conversation continues.  Similarly, services 
-may also remain running for a long time.  So Android has methods to shut 
-down activities and services in an orderly way:
-</p>
-
+<p>The manifest does a number of things in addition to declaring the application's components,
+such as:</p>
 <ul>
-<li>An activity can be shut down by calling its
-<code>{@link android.app.Activity#finish finish()}</code> method.  One activity can
-shut down another activity (one it started with {@code startActivityForResult()}) by 
-calling <code>{@link android.app.Activity#finishActivity finishActivity()}</code>.</li>
-
-<li>A service can be stopped by calling its
-<code>{@link android.app.Service#stopSelf stopSelf()}</code> method, or by calling 
-<code>{@link android.content.Context#stopService Context.stopService()}</code>.</li>
+  <li>Identify any user permissions the application requires, such as Internet access or
+read-access to the user's contacts.</li>
+  <li>Declare the minimum <a href="{@docRoot}guide/appendix/api-levels.html">API Level</a>
+required by the application, based on which APIs the application uses.</li>
+  <li>Declare hardware and software features used or required by the application, such as a camera,
+bluetooth services, or a multitouch screen.</li>
+  <li>API libraries the application needs to be linked against (other than the Android framework
+APIs), such as the <a
+href="http://code.google.com/android/add-ons/google-apis/maps-overview.html">Google Maps
+library</a>.</li>
+  <li>And more</li>
 </ul>
 
-<p>
-Components might also be shut down by the system when they are no longer being
-used or when Android must reclaim memory for more active components.  A later
-section, <a href="#lcycles">Component Lifecycles</a>, discusses this
-possibility and its ramifications in more detail.
-</p>
 
+<h3 id="DeclaringComponents">Declaring components</h3>
 
-<h3 id="manfile">The manifest file</h3>
+<p>The primary task of the manifest is to inform the system about the application's components. For
+example, a manifest file can declare an activity as follows: </p>
 
-<p>
-Before Android can start an application component, it must learn that 
-the component exists.  Therefore, applications declare their components 
-in a manifest file that's bundled into the Android package, the {@code .apk} 
-file that also holds the application's code, files, and resources.  
-</p>
-
-<p>
-The manifest is a structured XML file and is always named AndroidManifest.xml 
-for all applications.  It does a number of things in addition to declaring the 
-application's components, such as naming any libraries the application needs 
-to be linked against (besides the default Android library) and identifying 
-any permissions the application expects to be granted.
-</p>
-
-<p>
-But the principal task of the manifest is to inform Android about the application's 
-components.  For example, an activity might be declared as follows:
-</p>
-
-<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
-&lt;manifest . . . &gt;
-    &lt;application . . . &gt;
-        &lt;activity android:name="com.example.project.FreneticActivity"
-                  android:icon="@drawable/small_pic.png"
-                  android:label="@string/freneticLabel" 
-                  . . .  &gt;
+<pre>
+&lt;?xml version="1.0" encoding="utf-8"?&gt;
+&lt;manifest ... &gt;
+    &lt;application android:icon="@drawable/app_icon.png" ... &gt;
+        &lt;activity android:name="com.example.project.ExampleActivity"
+                  android:label="@string/example_label" ... &gt;
         &lt;/activity&gt;
-        . . .
+        ...
     &lt;/application&gt;
 &lt;/manifest&gt;</pre>
 
-<p>
-The {@code name} attribute of the 
-<code><a href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></code>
-element names the {@link android.app.Activity} subclass that implements the 
-activity.  The {@code icon} and {@code label} attributes point to 
-resource files containing an icon and label that can be displayed 
-to users to represent the activity.
-</p>
+<p>In the <code><a
+href="{@docRoot}guide/topics/manifest/application-element.html">&lt;application&gt;</a></code>
+element, the {@code android:icon} attribute points to resources for an icon that identifies the
+application.</p>
 
-<p>
-The other components are declared in a similar way &mdash; 
-<code><a href="{@docRoot}guide/topics/manifest/service-element.html">&lt;service&gt;</a></code>
-elements for services,
-<code><a href="{@docRoot}guide/topics/manifest/receiver-element.html">&lt;receiver&gt;</a></code>
-elements for broadcast receivers, and 
-<code><a href="{@docRoot}guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></code>
-elements for content providers.  Activities, services, and content providers 
-that are not declared in the manifest are not visible to the system and are 
-consequently never run. However, broadcast receivers can either be 
-declared in the manifest, or they can be created dynamically in code 
-(as {@link android.content.BroadcastReceiver} objects) 
-and registered with the system by calling 
-<code>{@link android.content.Context#registerReceiver Context.registerReceiver()}</code>.
-</p>
+<p>In the <code><a
+href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></code> element,
+the {@code android:name} attribute specifies the fully qualified class name of the {@link
+android.app.Activity} subclass and the {@code android:label} attributes specifies a string
+to use as the user-visible label for the activity.</p>
 
-<p>
-For more on how to structure a manifest file for your application, see 
-<a href="{@docRoot}guide/topics/manifest/manifest-intro.html">The 
-AndroidManifest.xml File</a>.
+<p>You must declare all application components this way:</p>
+<ul>
+  <li><code><a
+href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></code> elements
+for activities</li>
+  <li><code><a
+href="{@docRoot}guide/topics/manifest/service-element.html">&lt;service&gt;</a></code> elements for
+services</li>
+  <li><code><a
+href="{@docRoot}guide/topics/manifest/receiver-element.html">&lt;receiver&gt;</a></code> elements
+for broadcast receivers</li>
+  <li><code><a
+href="{@docRoot}guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></code> elements
+for content providers</li>
+</ul>
+
+<p>Activities, services, and content providers that you include in your source but do not declare
+in the manifest are not visible to the system and, consequently, can never run.  However,
+broadcast
+receivers can be either declared in the manifest or created dynamically in code (as
+{@link android.content.BroadcastReceiver} objects) and registered with the system by calling
+{@link android.content.Context#registerReceiver registerReceiver()}.</p>
+
+<p>For more about how to structure the manifest file for your application, see the <a
+href="{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml File</a>
+documentation. </p>
+
+
+
+<h3 id="DeclaringComponentCapabilities">Declaring component capabilities</h3>
+
+<p>As discussed above, in <a href="#ActivatingComponents">Activating Components</a>, you can use an
+{@link android.content.Intent} to start activities, services, and broadcast receivers. You can do so
+by explicitly naming the target component (using the component class name) in the intent. However,
+the real power of intents lies in the concept of intent actions. With intent actions, you simply
+describe the type of action you want to perform (and optionally, the data upon which you’d like to
+perform the action) and allow the system to find a component on the device that can perform the
+action and start it. If there are multiple components that can perform the action described by the
+intent, then the user selects which one to use.</p>
+
+<p>The way the system identifies the components that can respond to an intent is by comparing the
+intent received to the <i>intent filters</i> provided in the manifest file of other applications on
+the device.</p>
+
+<p>When you declare a component in your application's manifest, you can optionally include
+intent filters that declare the capabilities of the component so it can respond to intents
+from other applications. You can declare an intent filter for your component by
+adding an <a href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code
+&lt;intent-filter&gt;}</a> element as a child of the component's declaration element.</p>
+
+<p>For example, an email application with an activity for composing a new email might declare an
+intent filter in its manifest entry to respond to "send" intents (in order to send email). An
+activity in your application can then create an intent with the “send” action ({@link
+android.content.Intent#ACTION_SEND}), which the system matches to the email application’s “send”
+activity and launches it when you invoke the intent with {@link android.app.Activity#startActivity
+startActivity()}.</p>
+
+<p>For more about creating intent filters, see the <a
+href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Filters</a> document.
 </p>
 
 
-<h3 id="ifilters">Intent filters</h3>
 
-<p>
-An Intent object can explicitly name a target component.  If it does,
-Android finds that component (based on the declarations in the manifest 
-file) and activates it.  But if a target is not explicitly named, 
-Android must locate the best component to respond to the intent.  
-It does so by comparing the Intent object to the <i>intent filters</i> 
-of potential targets.  A component's intent filters inform Android of 
-the kinds of intents the component is able to handle.  Like other 
-essential information about the component, they're declared in the 
-manifest file.  Here's an extension of the previous example that adds 
-two intent filters to the activity:
-</p>
+<h3 id="DeclaringRequirements">Declaring application requirements</h3>
 
-<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
-&lt;manifest . . . &gt;
-    &lt;application . . . &gt;
-        &lt;activity android:name="com.example.project.FreneticActivity"
-                  android:icon="@drawable/small_pic.png"
-                  android:label="@string/freneticLabel" 
-                  . . .  &gt;
-            &lt;intent-filter . . . &gt;
-                &lt;action android:name="android.intent.action.MAIN" /&gt;
-                &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
-            &lt;/intent-filter&gt;
-            &lt;intent-filter . . . &gt;
-                &lt;action android:name="com.example.project.BOUNCE" /&gt;
-                &lt;data android:mimeType="image/jpeg" /&gt;
-                &lt;category android:name="android.intent.category.DEFAULT" /&gt;
-            &lt;/intent-filter&gt;
-        &lt;/activity&gt;
-        . . .
-    &lt;/application&gt;
-&lt;/manifest&gt;</pre>
+<p>There are a variety of devices powered by Android and not all of them provide the
+same features and capabilities. In order to prevent your application from being installed on devices
+that lack features needed by your application, it's important that you clearly define a profile for
+the types of devices your application supports by declaring device and software requirements in your
+manifest file. Most of these declarations are informational only and the system does not read
+them, but external services such as Android Market do read them in order to provide filtering
+for users when they search for applications from their device.</p>
 
-<p>
-The first filter in the example &mdash; the combination of the action
-"{@code android.intent.action.MAIN}" and the category
-"{@code android.intent.category.LAUNCHER}" &mdash; is a common one.
-It marks the activity as one that should be represented in the
-application launcher, the screen listing applications users can launch 
-on the device.  In other words, the activity is the entry point for 
-the application, the initial one users would see when they choose 
-the application in the launcher.
-</p>
+<p>For example, if your application requires a camera and uses APIs introduced in Android 2.1 (<a
+href="{@docRoot}guide/appendix/api-levels.html">API Level</a> 7), you should declare these as
+requirements in your manifest file. That way, devices that do <em>not</em> have a camera and have an
+Android version <em>lower</em> than 2.1 cannot install your application from Android Market.</p>
 
-<p>
-The second filter declares an action that the activity can perform on 
-a particular type of data.
-</p>
+<p>However, you can also declare that your applicaiton uses the camera, but does not
+<em>require</em> it. In that case, your application must perform a check at runtime to determine
+if the device has a camera and disable any features that use the camera if one is not available.</p>
 
-<p>
-A component can have any number of intent filters, each one declaring a 
-different set of capabilities.  If it doesn't have any filters, it can 
-be activated only by intents that explicitly name the component as the 
-target.
-</p>
-
-<p>
-For a broadcast receiver that's created and registered in code, the
-intent filter is instantiated directly as an {@link android.content.IntentFilter}
-object.  All other filters are set up in the manifest.
-</p>
-
-<p>
-For more on intent filters, see a separate document, 
-<a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents 
-and Intent Filters</a>.
-</p>
-
-
-<h2 id="acttask">Activities and Tasks</h2>
-
-<p>
-As noted earlier,  one activity can start another, including one defined 
-in a different application.  Suppose, for example, that you'd like 
-to let users display a street map of some location.  There's already an 
-activity that can do that, so all your activity needs to do is put together 
-an Intent object with the required information and pass it to 
-{@code startActivity()}.  The map viewer will display the map.  When the user 
-hits the BACK key, your activity will reappear on screen.
-</p>
-
-<p>
-To the user, it will seem as if the map viewer is part of the same application 
-as your activity, even though it's defined in another application and runs in 
-that application's process.  Android maintains this user experience by keeping 
-both activities in the same <i>task</i>.  Simply put, a task is what the user 
-experiences as an "application."  It's a group of related activities, arranged 
-in a stack.  The root activity in the stack is the one that began the task 
-&mdash; typically, it's an activity the user selected in the application launcher.  
-The activity at the top of the stack is one that's currently running &mdash; 
-the one that is the focus for user actions.  When one activity starts another, 
-the new activity is pushed on the stack; it becomes the running activity.  
-The previous activity remains in the stack.  When the user presses the BACK key, 
-the current activity is popped from the stack, and the previous one resumes as 
-the running activity.  
-</p>
-
-<p>
-The stack contains objects, so if a task has more than one instance of the same 
-Activity subclass open &mdash; multiple map viewers, for example &mdash; the 
-stack has a separate entry for each instance.  Activities in the stack are never 
-rearranged, only pushed and popped.
-</p>
-
-<p>
-A task is a stack of activities, not a class or an element in the manifest file. 
-So there's no way to set values for a task independently of its activities.  
-Values for the task as a whole are set in the root activity.  For example, the 
-next section will talk about the "affinity of a task"; that value is read from 
-the affinity set for the task's root activity.
-</p>
-
-<p>
-All the activities in a task move together as a unit.  The entire task (the entire 
-activity stack) can be brought to the foreground or sent to the background.  
-Suppose, for instance, that the current task has four activities in its stack 
-&mdash; three under the current activity.  The user presses the HOME key, goes 
-to the application launcher, and selects a new application (actually, a new <i>task</i>).  
-The current task goes into the background and the root activity for the new task is displayed.  
-Then, after a short period, the user goes back to the home screen and again selects 
-the previous application (the previous task).  That task, with all four 
-activities in the stack, comes forward.  When the user presses the BACK 
-key, the screen does not display the activity the user just left (the root
-activity of the previous task).  Rather, the activity on the top of the stack 
-is removed and the previous activity in the same task is displayed. 
-</p>
-
-<p>
-The behavior just described is the default behavior for activities and tasks.  
-But there are ways to modify almost all aspects of it.  The association of 
-activities with tasks, and the behavior of an activity within a task, is 
-controlled by the interaction between flags set in the Intent object that
-started the activity and attributes set in the activity's 
-<code><a href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></code>
-element in the manifest.  Both requester and respondent have a say in what happens.
-</p>
-
-<p>
-In this regard, the principal Intent flags are:
-
-<p style="margin-left: 2em">{@code FLAG_ACTIVITY_NEW_TASK}
-<br/>{@code FLAG_ACTIVITY_CLEAR_TOP}
-<br/>{@code FLAG_ACTIVITY_RESET_TASK_IF_NEEDED}
-<br/>{@code FLAG_ACTIVITY_SINGLE_TOP}</p>
-
-<p>
-The principal {@code &lt;activity&gt;} attributes are:
-  
-<p style="margin-left: 2em">{@code taskAffinity}
-<br/>{@code launchMode}
-<br/>{@code allowTaskReparenting}
-<br/>{@code clearTaskOnLaunch}
-<br/>{@code alwaysRetainTaskState}
-<br/>{@code finishOnTaskLaunch}</p>
-
-<p>
-The following sections describe what some of these flags and attributes do,
-how they interact, and what considerations should govern their use.
-</p>
-
-
-<h3 id="afftask">Affinities and new tasks</h3>
-
-<p>
-By default, all the activities in an application have an <i>affinity</i> for each 
-other &mdash; that is, there's a preference for them all to belong to the 
-same task.  However, an individual affinity can be set for each activity 
-with the {@code taskAffinity} attribute of the {@code &lt;activity&gt;} element. 
-Activities defined in different applications can share an affinity, or activities 
-defined in the same application can be assigned different affinities.  
-The affinity comes into play in two circumstances:  When the Intent object 
-that launches an activity contains the {@code FLAG_ACTIVITY_NEW_TASK} flag, 
-and when an activity has its {@code allowTaskReparenting} attribute set 
-to "{@code true}". 
-</p>
+<p>Here are some of the important device characteristics that you should consider as you design and
+develop your application:</p>
 
 <dl>
-<dt>The <code>{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}</code> flag</dt>
-<dd>As described earlier, a new activity is, by default, launched into 
-the task of the activity that called {@code startActivity()}.  It's pushed
- onto the same stack as the caller.  However, if the Intent object passed 
-to {@code startActivity()} contains the {@code FLAG_ACTIVITY_NEW_TASK} 
-flag, the system looks for a different task to house the new activity.  
-Often, as the name of the flag implies, it's a new task.  However, it 
-doesn't have to be.  If there's already an existing task with the same 
-affinity as the new activity, the activity is launched into that task.  If 
-not, it begins a new task.</dd>
+  <dt>Screen size and density</dt>
+  <dd>In order to categorize devices by their screen type, Android defines two characteristics for
+each device: screen size (the physical dimensions of the screen) and screen density (the physical
+density of the pixels on the screen, or dpi&mdash;dots per inch). To simplify all the different
+types of screen configurations, the Android system generalizes them into select groups that make
+them easier to target.
+<p>The screen sizes are: small, normal, large, and extra large.<br/>
+The screen densities are: low density, medium density, high density, and extra high density.</p>
 
-<dt>The <code><a 
-href="{@docRoot}guide/topics/manifest/activity-element.html#reparent">allowTaskReparenting</a></code>
-attribute</dt>
-<dd>If an activity has its {@code allowTaskReparenting} attribute set 
-to "{@code true}", it can move from the task it starts in to the task 
-it has an affinity for when that task comes to the fore.  For example, 
-suppose that an activity that reports weather conditions in selected 
-cities is defined as part of a travel application.  It has the same
-affinity as other activities in the same application (the default 
-affinity) and it allows reparenting.  One of your activities 
-starts the weather reporter, so it initially belongs to the same task as 
-your activity.  However, when the travel application next comes forward, 
-the weather reporter will be reassigned to and displayed with that task.</dd>
+<p>By default, your application is compatible with all screen sizes and densities,
+because the Android system makes the appropriate adjustments to your UI layout and image
+resources. However, you should create specialized layouts for certain screen sizes and provide
+specialized images for certain densities, using alternative layout resources, and by declaring in
+your manifest exactly which screen sizes your application supports with the <a
+href="{@docRoot}guide/topics/manifest/supports-screens.html">{@code
+&lt;supports-screens&gt;}</a> element.</p>
+<p>For more information, see the <a
+href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple Screens</a>
+document.</p></dd>
+
+  <dt>Input configurations</dt>
+  <dd>Many devices provide a different type of user input mechanism, such as a hardware keyboard, a
+trackball, or a five-way navigation pad. If your application requires a particular kind of input
+hardware, then you should declare it in your manifest with the <a
+href="{@docRoot}guide/topics/manifest/uses-configuration-element.html">{@code
+&lt;uses-configuration&gt;}</a> element. However, it is rare that an application should require
+a certain input configuration.</dd>
+
+  <dt>Device features</dt>
+  <dd>There are many hardware and software features that may or may not exist on a given
+Android-powered device, such as a camera, a light sensor, bluetooth, a certain
+version of OpenGL, or the fidelity of the touchscreen. You should never assume that a certain
+feature is available on all Android-powered devices (other than the availability of the standard
+Android library), so you should declare any features used by your application with the <a
+href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code &lt;uses-feature&gt;}</a>
+element.</dd>
+
+  <dt>Platform Version</dt>
+  <dd>Different Android-powered devices often run different versions of the Android platform,
+such as Android 1.6 or Android 2.3. Each successive version often includes additional APIs not
+available in the previous version. In order to indicate which set of APIs are available, each
+platform version specifies an <a
+href="{@docRoot}guide/appendix/api-levels.html">API Level</a> (for example, Android 1.0 is API Level
+1 and Android 2.3 is API Level 9). If you use any APIs that were added to the platform after
+version 1.0, you should declare the minimum API Level in which those APIs were introduced using the
+<a href="{@docRoot}guide/topics/manifest/uses-sdk.html">{@code &lt;uses-sdk&gt;}</a> element.</dd>
 </dl>
 
-<p>
-If an {@code .apk} file contains more than one "application"
-from the user's point of view, you will probably want to assign different 
-affinities to the activities associated with each of them.
-</p>
+<p>It's important that you declare all such requirements for your application, because, when you
+distribute your application on Android Market, Market uses these declarations to filter which
+applications are available on each device. As such, your application should be available only to
+devices that meet all your application requirements.</p>
 
+<p>For more information about how Android Market filters applications based on these (and other)
+requirements, see the <a href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a>
+document.</p>
 
-<h3 id="lmodes">Launch modes</h3>
 
-<p>
-There are four different launch modes that can be assigned to an {@code
-&lt;activity&gt;} element's 
-<code><a href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">launchMode</a></code> 
-attribute:
-</p>
 
-<p style="margin-left: 2em">"{@code standard}" (the default mode)
-<br>"{@code singleTop}"
-<br>"{@code singleTask}"
-<br>"{@code singleInstance}"</p>
+<h2 id="Resources">Application Resources</h2>
 
-<p>
-The modes differ from each other on these four points:
-</p>
+<p>An Android application is composed of more than just code&mdash;it requires resources that are
+separate from the source code, such as images, audio files, and anything relating to the visual
+presentation of the application. For example, you should define animations, menus, styles, colors,
+and the layout of activity user interfaces with XML files. Using application resources makes it easy
+to update various characteristics of your application without modifying code and&mdash;by providing
+sets of alternative resources&mdash;enables you to optimize your application for a  variety of
+device configurations (such as different languages and screen sizes).</p>
 
-<ul>
+<p>For every resource that you include in your Android project, the SDK build tools define a unique
+integer ID, which you can use to reference the resource from your application code or from
+other resources defined in XML. For example, if your application contains an image file named {@code
+logo.png} (saved in the {@code res/drawable/} directory), the SDK tools generate a resource ID
+named {@code R.drawable.logo}, which you can use to reference the image and insert it in your
+user interface.</p>
 
-<li><b>Which task will hold the activity that responds to the intent</b>.  
-For the "{@code standard}" and "{@code singleTop}" modes, it's the task that 
-originated the intent (and called 
-<code>{@link android.content.Context#startActivity startActivity()}</code>) 
-&mdash; unless the Intent object contains the 
-<code>{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}</code> flag.  
-In that case, a different task is chosen as described in the previous 
-section, <a href="#afftask">Affinities and new tasks</a>.  
+<p>One of the most important aspects of providing resources separate from your source code
+is the ability for you to provide alternative resources for different device
+configurations. For example, by defining UI strings in XML, you can translate the strings into other
+languages and save those strings in separate files. Then, based on a language <em>qualifier</em>
+that you append to the resource directory's name (such as {@code res/values-fr/} for French string
+values) and the user's language setting, the Android system applies the appropriate language strings
+to your UI.</p>
 
-<p>
-In contrast, the "{@code singleTask}" and "{@code singleInstance}" modes mark 
-activities that are always at the root of a task.  They define a task; they're
-never launched into another task.
-</p>  
+<p>Android supports many different <em>qualifiers</em> for your alternative resources. The
+qualifier is a short string that you include in the name of your resource directories in order to
+define the device configuration for which those resources should be used. As another
+example, you should often create different layouts for your activities, depending on the
+device's screen orientation and size. For example, when the device screen is in portrait
+orientation (tall), you might want a layout with buttons to be vertical, but when the screen is in
+landscape orientation (wide), the buttons should be aligned horizontally. To change the layout
+depending on the orientation, you can define two different layouts and apply the appropriate
+qualifier to each layout's directory name. Then, the system automatically applies the appropriate
+layout depending on the current device orientation.</p>
 
-<li><p><b>Whether there can be multiple instances of the activity</b>.  
-A "{@code standard}" or "{@code singleTop}" activity can be instantiated
-many times.  They can belong to multiple tasks, and a given task can have 
-multiple instances of the same activity.
-</p> 
+<p>For more about the different kinds of resources you can include in your application and how
+to create alternative resources for various device configurations, see the <a
+href="{@docRoot}guide/topics/resources/index.html">Application Resources</a> developer guide.</p>
 
-<p>
-In contrast, "{@code singleTask}" and "{@code singleInstance}" activities 
-are limited to just one instance.  Since these activities are at the root
-of a task, this limitation means that there is never more than a single
-instance of the task on the device at one time.
-</p>    
 
-<li><p><b>Whether the instance can have other activities in its task</b>.  
-A "{@code singleInstance}" activity stands alone as the only activity in its 
-task.  If it starts another activity, that activity will be launched into a 
-different task regardless of its launch mode &mdash; as if {@code
-FLAG_ACTIVITY_NEW_TASK} was in the intent.  In all other respects, the 
-"{@code singleInstance}" mode is identical to "{@code singleTask}".</p>
+<h2>Beginner's Path</h2>
 
-<p>
-The other three modes permit multiple activities to belong to the task.
-A "{@code singleTask}" activity will always be the root activity of the task, 
-but it can start other activities that will be assigned to its
-task.  Instances of "{@code standard}" and "{@code singleTop}"
-activities can appear anywhere in a stack.  
-</p></li>
-
-<li><b>Whether a new instance of the class will be launched 
-to handle a new intent</b>.  For the default "{@code standard}" mode, a 
-new instance is created to respond to every new intent.  Each instance 
-handles just one intent.  For the "{@code singleTop}" mode, an existing 
-instance of the class is re-used to handle a new intent if it resides 
-at the top of the activity stack of the target task.  If it does not 
-reside at the top, it is not re-used.  Instead, a new instance 
-is created for the new intent and pushed on the stack.
-
-<p>
-For example, suppose a task's activity stack consists of root activity A with 
-activities B, C, and D on top in that order, so the stack is A-B-C-D.  An intent 
-arrives for an activity of type D.  If D has the default "{@code standard}" launch 
-mode, a new instance of the class is launched and the stack becomes A-B-C-D-D.  
-However, if D's launch mode is "{@code singleTop}", the existing instance is 
-expected to handle the new intent (since it's at the top of the stack) and the 
-stack remains A-B-C-D.  
-</p>
-
-<p>
-If, on the other hand, the arriving intent is for an activity of type B, a new 
-instance of B would be launched no matter whether B's mode is "{@code standard}" 
-or "{@code singleTop}" (since B is not at the top of the stack), so the resulting 
-stack would be A-B-C-D-B.
-</p>
-
-<p>
-As noted above, there's never more than one instance of a "{@code singleTask}" 
-or "{@code singleInstance}" activity, so that instance is expected to handle
-all new intents.  A "{@code singleInstance}" activity is always at the top of 
-the stack (since it is the only activity in the task), so it is always in 
-position to handle the intent.  However, a "{@code singleTask}" activity may 
-or may not have other activities above it in the stack.  If it does, it is not 
-in position to handle the intent, and the intent is dropped.  (Even though the 
-intent is dropped, its arrival would have caused the task to come to the 
-foreground, where it would remain.)
-</p>
-</li>
-
-</ul>
-
-<p>
-When an existing activity is asked to handle a new intent, the Intent
-object is passed to the activity in an 
-<code>{@link android.app.Activity#onNewIntent onNewIntent()}</code> call.  
-(The intent object that originally started the activity can be retrieved by 
-calling <code>{@link android.app.Activity#getIntent getIntent()}</code>.)
-</p>
-
-<p>
-Note that when a new instance of an Activity is created to handle a new
-intent, the user can always press the BACK key to return to the previous state
-(to the previous activity).  But when an existing instance of an 
-Activity handles a new intent, the user cannot press the BACK key to 
-return to what that instance was doing before the new intent arrived.
-</p>
-
-<p>
-For more on launch modes, see the description of the <code><a 
-href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">&lt;activity&gt;</a></code>
-element.
-</p>
-
-
-<h3 id="clearstack">Clearing the stack</h3>
-
-<p>
-If the user leaves a task for a long time, the system clears the task of all
-activities except the root activity.  When the user returns to the task again, 
-it's as the user left it, except that only the initial activity is present. 
-The idea is that, after
-a time, users will likely have abandoned what they were doing before and are
-returning to the task to begin something new.
-</p>
-
-<p>
-That's the default.  There are some activity attributes that can be used to 
-control this behavior and modify it:
-</p>
-
-<dl>
-<dt>The <code><a 
-href="{@docRoot}guide/topics/manifest/activity-element.html#always">alwaysRetainTaskState</a></code>
-attribute</dt>
-<dd>If this attribute is set to "{@code true}" in the root activity of a task, 
-the default behavior just described does not happen.  
-The task retains all activities in its stack even after a long period.</dd>
-
-<dt>The <code><a 
-href="{@docRoot}guide/topics/manifest/activity-element.html#clear">clearTaskOnLaunch</a></code>
-attribute</dt>
-<dd>If this attribute is set to "{@code true}" in the root activity of a task, 
-the stack is cleared down to the root activity whenever the user leaves the task 
-and returns to it.  In other words, it's the polar opposite of 
-{@code alwaysRetainTaskState}.  The user always returns to the task in its
-initial state, even after a momentary absence.</dd>
-
-<dt>The <code><a 
-href="{@docRoot}guide/topics/manifest/activity-element.html#finish">finishOnTaskLaunch</a></code>
-attribute</dt>
-<dd>This attribute is like {@code clearTaskOnLaunch}, but it operates on a 
-single activity, not an entire task.  And it can cause any activity to go
-away, including the root activity.  When it's set to "{@code true}", the 
-activity remains part of the task only for the current session.  If the user 
-leaves and then returns to the task, it no longer is present.</dd>
-</dl>
-
-<p>
-There's another way to force activities to be removed from the stack.  
-If an Intent object includes the <code>{@link 
-android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_CLEAR_TOP}</code> 
-flag, and the target task already has an instance of the type of activity that 
-should handle the intent in its stack, all activities above that instance 
-are cleared away so that it stands at the top of the stack and can respond 
-to the intent. 
-If the launch mode of the designated activity is "{@code standard}", it too 
-will be removed from the stack, and a new instance will be launched to handle 
-the incoming intent.  That's because a new instance is always created for 
-a new intent when the launch mode is "{@code standard}".
-</p>
-
-<p>
-{@code FLAG_ACTIVITY_CLEAR_TOP} is most often used in conjunction
-with {@code FLAG_ACTIVITY_NEW_TASK}.  When used together, these flags are
-a way of locating an existing activity in another task and putting it in
-a position where it can respond to the intent.  
-</p>
-
-
-<h3 id="starttask">Starting tasks</h3>
-
-<p>
-An activity is set up as the entry point for a task by giving it 
-an intent filter with "{@code android.intent.action.MAIN}" as the 
-specified action and "{@code android.intent.category.LAUNCHER}" as 
-the specified category.  (There's an example of this type of filter 
-in the earlier <a href="#ifilters">Intent Filters</a> section.)  
-A filter of this kind causes an icon and label for the activity to be 
-displayed in the application launcher, giving users a way both to 
-launch the task and to return to it at any time after it has been 
-launched.
-</p>
-
-<p>
-This second ability is important:  Users must be able to leave a task
-and then come back to it later.  For this reason, the two launch modes
-that mark activities as always initiating a task, "{@code singleTask}" 
-and "{@code singleInstance}", should be used only when the activity has 
-a {@code MAIN} and {@code LAUNCHER} filter.  
-Imagine, for example, what could happen if the filter is missing:
-An intent launches a "{@code singleTask}" activity, initiating a new task, 
-and the user spends some time working in that task.  The user then presses 
-the HOME key.  The task is now ordered behind and obscured by the home 
-screen.  And, because it is not represented in the application launcher, 
-the user has no way to return to it.
-</p>
-
-<p>
-A similar difficulty attends the {@code FLAG_ACTIVITY_NEW_TASK} flag.
-If this flag causes an activity to
-begin a new task and the user presses the HOME key to leave it, there
-must be some way for the user to navigate back to it again.  Some 
-entities (such as the notification manager) always start activities 
-in an external task, never as part of their own, so they always put 
-{@code FLAG_ACTIVITY_NEW_TASK} in the intents they pass to 
-{@code startActivity()}.  If you have an activity that can be invoked 
-by an external entity that might use this flag, take care that the user 
-has a independent way to get back to the task that's started.
-</p> 
-
-<p>
-For those cases where you don't want the user to be able to return
-to an activity, set the {@code &lt;activity&gt;} element's {@code
-finishOnTaskLaunch} to "{@code true}".  
-See <a href="#clearstack">Clearing the stack</a>, earlier.
-</p>
-
-
-<h3 id="commonpatterns">Common patterns</h3>
-
-<p>
-In most cases an application won't use any flags or special features.
-This gives the standard interaction the user expects: launching the application
-brings any existing task to the foreground, or starts the main activity in
-a new task if there isn't one.
-</p>
-
-<p>
-If an application posts notifications, it needs to decide how the user's
-selection of a notification should impact any currently running task.  The
-current suggested behavior is that any current tasks be completely removed,
-replaced with a new task containing a stack of activities representing where
-the user is jumping in to the app.  This can be accomplished with a combination
-of the {@link android.app.PendingIntent#getActivities PendingIntent.getActivities()}
-method and {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TASK Intent.FLAG_ACTIVITY_CLEAR_TASK}.
-</p>
-
-<p>
-For example, here is sample code to build an array of Intents to launch an
-application into an activity three levels deep.  The first Intent is always
-the main Intent of the application as started by the launcher.  The exact
-details of the Intent data will of course depend on your application.
-</p>
-
-{@sample development/samples/ApiDemos/src/com/example/android/apis/app/StatusBarNotifications.java
-      intent_array}
-
-<p>
-In some cases an application may not want to directly launch its application
-from a notification, but instead go to a intermediate summary activity.  To
-accomplish this, the summary activity should be given a task affinity that
-is different from the main application (one will typically give it no affinity,
-that is "") so that it does not get launched into any existing application task.
-</p>
-
-{@sample development/samples/ApiDemos/AndroidManifest.xml no_task_affinity}
-
-<p>
-The PendingIntent to launch this then does not need to supply anything special:
-</p>
-
-{@sample development/samples/ApiDemos/src/com/example/android/apis/app/IncomingMessage.java
-      pending_intent}
-
-<p>
-If an application implements an app widget, it should generally use the same
-approach as the first one for notifications: when the user taps on the app
-widget it should throw away any current task of the application and start a
-new task with potentially multiple activities representing the state the
-user is jumping in to.
-</p>
-
-<h2 id="procthread">Processes and Threads</h2>
-
-<p>
-When the first of an application's components needs to be run, Android 
-starts a Linux process for it with a single thread of execution.  By default, 
-all components of the application run in that process and thread.
-</p>
-
-<p>
-However, you can arrange for components to run in other processes, and you 
-can spawn additional threads for any process.
-</p>
-
-
-<h3 id="procs">Processes</h3>
-
-<p>
-The process where a component runs is controlled by the manifest file.  
-The component elements &mdash; {@code &lt;activity&gt;}, 
-{@code &lt;service&gt;}, {@code &lt;receiver&gt;}, and {@code &lt;provider&gt;} 
-&mdash; each have a {@code process} attribute that can specify a process
-where that component should run.  These attributes can be set so that each 
-component runs in its own process, or so that some components share a process 
-while others do not.  They can also be set so that components of 
-different applications run in the same process &mdash; provided that the 
-applications share the same Linux user ID and are signed by the same authorities.
-The {@code &lt;application&gt;} element also has a {@code process} attribute,
-for setting a default value that applies to all components.
-</p>
-
-<p>
-All components are instantiated in the main thread of the specified
-process, and system calls to the component are dispatched from that
-thread.  Separate threads are not created for each instance.  Consequently,
-methods that respond to those calls &mdash; methods like 
-<code>{@link android.view.View#onKeyDown View.onKeyDown()}</code> that report
-user actions and the lifecycle notifications discussed later in the 
-<a href="#lcycles">Component Lifecycles</a> section &mdash; always run in the
-main thread of the process.  This means
-that no component should perform long or blocking operations (such as networking 
-operations or computation loops) when called by the system, since this will block
-any other components also in the process.  You can spawn separate threads for 
-long operations, as discussed under <a href="#threads">Threads</a>, next.
-</p>
-
-<p>
-Android may decide to shut down a process at some point, when memory is 
-low and required by other processes that are more immediately serving 
-the user.  Application components running in the process are consequently 
-destroyed.  A process is restarted for those components when there's again
-work for them to do.
-</p>  
-
-<p>
-When deciding which processes to terminate, Android weighs their relative
-importance to the user.  For example, it more readily shuts down a process 
-with activities that are no longer visible on screen than a process with
-visible activities.
-The decision whether to terminate a process, therefore, depends on the state 
-of the components running in that process.  Those states are the subject of
-a later section, <a href="#lcycles">Component Lifecycles</a>.
-</p>
-
-
-<h3 id="threads">Threads</h3>
-
-<p>
-Even though you may confine your application to a single process, there will
-likely be times when you will need to spawn a thread to do some background 
-work.  Since the user interface must always be quick to respond to user actions, 
-the thread that hosts an activity should not also host time-consuming operations 
-like network downloads.  Anything that may not be completed quickly should be
-assigned to a different thread. 
-</p>
-
-<p>
-Threads are created in code using standard Java {@link java.lang.Thread}
-objects.  Android provides a number of convenience classes for managing 
-threads &mdash; {@link android.os.Looper} for running a message loop within 
-a thread, {@link android.os.Handler} for processing messages, and 
-{@link android.os.HandlerThread} for setting up a thread with a message loop.
-</p>
-
-
-<h3 id="rpc">Remote procedure calls</h3>
-
-<p>
-Android has a lightweight mechanism for remote procedure calls (RPCs) 
-&mdash; where a method is called locally, but executed remotely (in another
-process), with any result returned back to the caller.
-This entails decomposing the method call and all its attendant data to a 
-level the operating system can understand, transmitting it from the local 
-process and address space to the remote process and address space, and 
-reassembling and reenacting the call there.  Return values have to be 
-transmitted in the opposite direction.  Android provides all the code 
-to do that work, so that you can concentrate on defining and implementing 
-the RPC interface itself.
-</p>
-
-<p>
-An RPC interface can include only methods. By default,
-all methods are executed synchronously (the local method blocks until the
-remote method finishes), even if there is no return value.
-</p>
-
-<p>
-In brief, the mechanism works as follows:  You'd begin by declaring the
-RPC interface you want to implement using a simple IDL (interface definition 
-language).  From that declaration, the 
-<code><a href="{@docRoot}guide/developing/tools/aidl.html">aidl</a></code> 
-tool generates a Java interface definition that must be made available to 
-both the local and the remote process.  It contains two inner class, as shown 
-in the following diagram:
-</p>
-
-<p style="margin-left: 2em">
-<img src="{@docRoot}images/binder_rpc.png" alt="RPC mechanism." />
-</p>
-
-<p>
-The inner classes have all the code needed to administer remote procedure
-calls for the interface you declared with the IDL. 
-Both inner classes implement the {@link android.os.IBinder}
-interface.  One of them is used locally and internally by the system;
-the code you write can ignore it.
-The other, called Stub, extends the {@link android.os.Binder}
-class.  In addition to internal code for effectuating the IPC calls, it 
-contains declarations for the methods in the RPC interface you declared.
-You would subclass Stub to implement those methods, as indicated in the 
-diagram.  
-</p>
-
-<p>
-Typically, the remote process would be managed by a service (because a 
-service can inform the system about the process and its connections to 
-other processes).  It would have both the interface file generated by 
-the {@code aidl} tool and the Stub subclass implementing the 
-RPC methods.  Clients of the service would have only the interface file
-generated by the {@code aidl} tool.
-</p>
-
-<p>
-Here's how a connection between a service and its clients is set up:
-</p>
-
-<ul>
-<li>Clients of the service (on the local side) would implement 
-<code>{@link android.content.ServiceConnection#onServiceConnected
-onServiceConnected()}</code> and 
-<code>{@link android.content.ServiceConnection#onServiceDisconnected
-onServiceDisconnected()}</code> methods so they can be notified 
-when a successful connection to the remote service is established, and 
-when it goes away.  They would then call
-<code>{@link android.content.Context#bindService bindService()}</code>
-to set up the connection.
-</li>  
-
-<li> 
-The service's <code>{@link android.app.Service#onBind onBind()}</code> 
-method would be implemented to either accept or reject the connection, 
-depending on the intent it receives (the intent passed to
-{@code bindService()}).  If the connection is accepted, it returns 
-an instance of the Stub subclass.
-</li>
-
-<li>If the service accepts the connection, Android calls the 
-client's {@code onServiceConnected()} method and passes it an IBinder 
-object, a proxy for the Stub subclass managed by the service.  Through
-the proxy, the client can make calls on the remote service.  
-</li>
-</ul>
-
-<p>
-This brief description omits some details of the RPC mechanism.  For more 
-information, see 
-<a href="{@docRoot}guide/developing/tools/aidl.html">Designing a Remote 
-Interface Using AIDL</a> and the {@link android.os.IBinder IBinder} class 
-description.
-</p>  
-
-
-<h3 id="tsafe">Thread-safe methods</h3>
-
-<p>
-In a few contexts, the methods you implement may be called from more 
-than one thread, and therefore must be written to be thread-safe.
-</p>
-
-<p>
-This is primarily true for methods that can be called remotely &mdash;
-as in the RPC mechanism discussed in the previous section.
-When a call on a method implemented in an IBinder object originates
-in the same process as the IBinder, the method is executed in the
-caller's thread.  However, when the call originates in another process, 
-the method is executed in a thread chosen from a pool of threads that 
-Android maintains in the same process as the IBinder; it's not executed 
-in the main thread of the process.  For example, whereas a service's 
-{@code onBind()} method would be called from the main thread of the 
-service's process, methods implemented in the object that {@code onBind()} 
-returns (for example, a Stub subclass that implements RPC methods) would 
-be called from threads in the pool. 
-Since services can have more than one client, more than one pool thread
-can engage the same IBinder method at the same time.  IBinder methods
-must, therefore, be implemented to be thread-safe.
-</p>  
-
-<p>
-Similarly, a content provider can receive data requests that originate in 
-other processes.  Although the ContentResolver and ContentProvider classes 
-hide the details of how the interprocess communication is managed, 
-ContentProvider methods that respond to those requests &mdash; the methods
-<code>{@link android.content.ContentProvider#query query()}</code>, 
-<code>{@link android.content.ContentProvider#insert insert()}</code>, 
-<code>{@link android.content.ContentProvider#delete delete()}</code>, 
-<code>{@link android.content.ContentProvider#update update()}</code>, and
-<code>{@link android.content.ContentProvider#getType getType()}</code>
-&mdash; are called from a pool of threads in the content provider's
-process, not the main thread of the process.  Since these methods
-may be called from any number of threads at the same time, they too must
-be implemented to be thread-safe.
-</p> 
-
-
-<h2 id="lcycles">Component Lifecycles</h2>
-
-<p>
-Application components have a lifecycle &mdash; a beginning when 
-Android instantiates them to respond to intents through to an end when 
-the instances are destroyed.  In between, they may sometimes be active 
-or inactive,or, in the case of activities, visible to the user or
-invisible.  This section discusses the lifecycles of activities,
-services, and broadcast receivers &mdash; including the states that they 
-can be in during their lifetimes, the methods that notify you of transitions
-between states, and the effect of those states on the possibility that
-the process hosting them might be terminated and the instances destroyed.
-</p> 
-
-
-<h3 id="actlife">Activity lifecycle</h3>
-
-<p>An activity has essentially three states:</p>
-
-<ul>
-<li> It is <em>active</em> or <em>running</em> when it is in the foreground of the 
-screen (at the top of the activity stack for the current task).  This is the
-activity that is the focus for the user's actions.</li>
-
-<li><p>It is <em>paused</em> if it has lost focus but is still visible to the user.
-That is, another activity lies on top of it and that activity either is transparent
-or doesn't cover the full screen, so some of the paused activity can show through. 
-A paused activity is completely alive (it maintains all state and member information 
-and remains attached to the window manager), but can be killed by the system in 
-extreme low memory situations.</p></li>
-
-<li><p>It is <em>stopped</em> if it is completely obscured by another activity.
-It still retains all state and member information.  However, it is no longer 
-visible to the user so its window is hidden and it will often be killed by the 
-system when memory is needed elsewhere.</p></li>
-</ul>
-
-<p>
-If an activity is paused or stopped, the system can drop it from memory either 
-by asking it to finish (calling its {@link android.app.Activity#finish finish()}
-method), or simply killing its process.  When it is displayed again 
-to the user, it must be completely restarted and restored to its previous state.
-</p>
-
-<p>
-As an activity transitions from state to state, it is notified of the change 
-by calls to the following protected methods:
-</p>
-
-<p style="margin-left: 2em">{@code void onCreate(Bundle <i>savedInstanceState</i>)}
-<br/>{@code void onStart()}
-<br/>{@code void onRestart()}
-<br/>{@code void onResume()}
-<br/>{@code void onPause()}
-<br/>{@code void onStop()}
-<br/>{@code void onDestroy()}</p>
-
-<p>
-All of these methods are hooks that you can override to do appropriate work 
-when the state changes.  All activities must implement 
-<code>{@link android.app.Activity#onCreate onCreate()}</code> to do the 
-initial setup when the object is first instantiated.  
-Many will also implement <code>{@link android.app.Activity#onPause onPause()}</code> 
-to commit data changes and otherwise prepare to stop interacting with the user.
-</p>
-
-<div class="sidebox-wrapper">
-<div class="sidebox">
-<h2>Calling into the superclass</h2>
-<p>
-An implementation of any activity lifecycle method should always first 
-call the superclass version.  For example:
-</p>
-
-<pre>protected void onPause() {
-    super.onPause();
-    . . .
-}</pre>
-</div>
-</div> 
-
-
-<p>
-Taken together, these seven methods define the entire lifecycle of an 
-activity.  There are three nested loops that you can monitor by
-implementing them: 
-</p> 
-
-<ul>
-<li>The <b>entire lifetime</b> of an activity happens between the first call
-to <code>{@link android.app.Activity#onCreate onCreate()}</code> through to a 
-single final call to <code>{@link android.app.Activity#onDestroy}</code>.  
-An activity does all its initial setup of "global" state in {@code onCreate()}, 
-and releases all remaining resources in {@code onDestroy()}.  For example, 
-if it has a thread running in the background to download data from the network, 
-it may create that thread in {@code onCreate()} and then stop the thread in 
-{@code onDestroy()}.</li>
-
-<li><p>The <b>visible lifetime</b> of an activity happens between a call to
-<code>{@link android.app.Activity#onStart onStart()}</code> until a 
-corresponding call to <code>{@link android.app.Activity#onStop onStop()}</code>.  
-During this time, the user can see the activity on-screen, though it may not 
-be in the foreground and interacting with the user.  Between these two methods, 
-you can maintain resources that are needed to show the activity to the user.  
-For example, you can register a {@link android.content.BroadcastReceiver} in 
-{@code onStart()} to monitor for changes that impact your UI, and unregister 
-it in {@code onStop()} when the user can no longer see what you are displaying.  
-The {@code onStart()} and {@code onStop()} methods can be called multiple times, 
-as the activity alternates between being visible and hidden to the user.</p></li>
-
-<li><p>The <b>foreground lifetime</b> of an activity happens between a call 
-to <code>{@link android.app.Activity#onResume onResume()}</code> until a 
-corresponding call to <code>{@link android.app.Activity#onPause onPause()}</code>.  
-During this time, the activity is in front of all other activities on screen and 
-is interacting with the user.  An activity can frequently transition between the 
-resumed and paused states &mdash; for example, {@code onPause()} is called when 
-the device goes to sleep or when a new activity is started, {@code onResume()} 
-is called when an activity result or a new intent is delivered.  Therefore, the 
-code in these two methods should be fairly lightweight.</p></li>
-</ul>
-
-<p>
-The following diagram illustrates these loops and the paths an activity
-may take between states.  The colored ovals are major states the activity 
-can be in.  The square rectangles represent the callback methods you can implement 
-to perform operations when the activity transitions between states.
-<p>
-
-<p style="margin-left: 2em"><img src="{@docRoot}images/activity_lifecycle.png"
-alt="State diagram for an Android activity lifecycle." /></p>  
-  
-<p>
-The following table describes each of these methods in more detail and 
-locates it within the activity's overall lifecycle:
-</p>
-
-<table border="2" width="85%" frame="hsides" rules="rows">
-<colgroup align="left" span="3"></colgroup>
-<colgroup align="left"></colgroup>
-<colgroup align="center"></colgroup>
-<colgroup align="center"></colgroup>
-
-<thead>
-<tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr>
-</thead>
-
-<tbody>
-<tr>
-  <td colspan="3" align="left"><code>{@link android.app.Activity#onCreate onCreate()}</code></td>
-  <td>Called when the activity is first created.
-      This is where you should do all of your normal static set up &mdash;
-      create views, bind data to lists, and so on.  This method is passed
-      a Bundle object containing the activity's previous state, if that 
-      state was captured (see <a href="#actstate">Saving Activity State</a>, 
-      later).
-      <p>Always followed by {@code onStart()}.</p></td>
-  <td align="center">No</td>
-      <td align="center">{@code onStart()}</td>
-</tr>
-
-<tr>
-   <td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
-   <td colspan="2" align="left"><code>{@link android.app.Activity#onRestart 
-onRestart()}</code></td>
-   <td>Called after the activity has been stopped, just prior to it being
-       started again.
-       <p>Always followed by {@code onStart()}</p></td>
-   <td align="center">No</td>
-   <td align="center">{@code onStart()}</td>
-</tr>
-
-<tr>
-   <td colspan="2" align="left"><code>{@link android.app.Activity#onStart onStart()}</code></td>
-   <td>Called just before the activity becomes visible to the user.
-       <p>Followed by {@code onResume()} if the activity comes
-       to the foreground, or {@code onStop()} if it becomes hidden.</p></td>
-    <td align="center">No</td>
-    <td align="center">{@code onResume()} <br/>or<br/> {@code onStop()}</td>
-</tr>
-
-<tr>
-   <td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
-   <td align="left"><code>{@link android.app.Activity#onResume onResume()}</code></td>
-   <td>Called just before the activity starts
-       interacting with the user.  At this point the activity is at
-       the top of the activity stack, with user input going to it.
-       <p>Always followed by {@code onPause()}.</p></td>
-   <td align="center">No</td>
-   <td align="center">{@code onPause()}</td>
-</tr>
-
-<tr>
-   <td align="left"><code>{@link android.app.Activity#onPause onPause()}</code></td>
-   <td>Called when the system is about to start resuming another
-       activity.  This method is typically used to commit unsaved changes to
-       persistent data, stop animations and other things that may be consuming
-       CPU, and so on.  It should do whatever it does very quickly, because
-       the next activity will not be resumed until it returns.
-       <p>Followed either by {@code onResume()} if the activity
-       returns back to the front, or by {@code onStop()} if it becomes
-       invisible to the user.</td>
-   <td align="center"><strong style="color:#800000">Yes</strong></td>
-   <td align="center">{@code onResume()} <br/>or<br/> {@code onStop()}</td>
-</tr>
-
-<tr>
-   <td colspan="2" align="left"><code>{@link android.app.Activity#onStop onStop()}</code></td>
-   <td>Called when the activity is no longer visible to the user.  This
-       may happen because it is being destroyed, or because another activity 
-       (either an existing one or a new one) has been resumed and is covering it. 
-       <p>Followed either by {@code onRestart()} if
-       the activity is coming back to interact with the user, or by
-       {@code onDestroy()} if this activity is going away.</p></td>
-   <td align="center"><strong style="color:#800000">Yes</strong></td>
-   <td align="center">{@code onRestart()} <br/>or<br/> {@code onDestroy()}</td>
-</tr>
-
-<tr>
-   <td colspan="3" align="left"><code>{@link android.app.Activity#onDestroy 
-onDestroy()}</code></td>
-   <td>Called before the activity is destroyed.  This is the final call 
-       that the activity will receive.  It could be called either because the
-       activity is finishing (someone called <code>{@link android.app.Activity#finish 
-       finish()}</code> on it), or because the system is temporarily destroying this
-       instance of the activity to save space.  You can distinguish
-       between these two scenarios with the <code>{@link
-       android.app.Activity#isFinishing isFinishing()}</code> method.</td>
-   <td align="center"><strong style="color:#800000">Yes</strong></td>
-   <td align="center"><em>nothing</em></td>
-</tr>
-</tbody>
-</table>
-
-<p>
-Note the <b>Killable</b> column in the table above.  It indicates
-whether or not the system can kill the process hosting the activity 
-<em>at any time after the method returns, without executing another
-line of the activity's code</em>.  Three methods ({@code onPause()},
-{@code onStop()}, and {@code onDestroy()}) are marked "Yes."  Because
-{@code onPause()} is the first of the three, it's the only one that's
-guaranteed to be called before the process is killed &mdash; 
-{@code onStop()} and {@code onDestroy()} may not be.  Therefore, you 
-should use {@code onPause()} to write any persistent data (such as user 
-edits) to storage.
-</p>
-
-<p>
-Methods that are marked "No" in the <b>Killable</b> column protect the
-process hosting the activity from being killed from the moment they are 
-called.  Thus an activity is in a killable state, for example, from the 
-time {@code onPause()} returns to the time {@code onResume()} is called.
-It will not again be killable until {@code onPause()} again returns.
-</p>
-
-<p>
-As noted in a later section, <a href="#proclife">Processes and lifecycle</a>,
-an activity that's not technically "killable" by this definition might
-still be killed by the system &mdash; but that would happen only in
-extreme and dire circumstances when there is no other recourse.
-</p>
-
-
-<h4 id="actstate">Saving activity state</h4>
-
-<p>
-When the system, rather than the user, shuts down an activity to conserve 
-memory, the user may expect to return to the activity and find it in its 
-previous state.
-</p>
-
-<p>
-To capture that state before the activity is killed, you can implement
-an <code>{@link android.app.Activity#onSaveInstanceState 
-onSaveInstanceState()}</code> method for the activity.  Android calls this 
-method before making the activity vulnerable to being destroyed &mdash;
-that is, before {@code onPause()} is called.  It
-passes the method a {@link android.os.Bundle} object where you can record 
-the dynamic state of the activity as name-value pairs.  When the activity is 
-again started, the Bundle is passed both to {@code onCreate()} and to a
-method that's called after {@code onStart()}, <code>{@link 
-android.app.Activity#onRestoreInstanceState onRestoreInstanceState()}</code>, 
-so that either or both of them can recreate the captured state.
-</p>
-
-<p>
-Unlike {@code onPause()} and the other methods discussed earlier,
-{@code onSaveInstanceState()} and {@code onRestoreInstanceState()} are
-not lifecycle methods.  They are not always called.  For example, Android
-calls {@code onSaveInstanceState()} before the activity becomes 
-vulnerable to being destroyed by the system, but does not bother
-calling it when the instance is actually being destroyed by a user action
-(such as pressing the BACK key).  In that case, the user won't expect to
-return to the activity, so there's no reason to save its state.
-</p>
-
-<p>
-Because {@code onSaveInstanceState()} is not always called, you should 
-use it only to record the transient state of the activity, not to store 
-persistent data.  Use {@code onPause()} for that purpose instead.
-</p>
-
-
-<h4 id="coordact">Coordinating activities</h4>
-
-<p>
-When one activity starts another, they both experience lifecycle
-transitions.  One pauses and may stop, while the other starts up.
-On occasion, you may need to coordinate these activities, one with
-the other.
-</p>
-
-<p>
-The order of lifecycle callbacks is well defined,
-particularly when the two activities are in the same process:
-</p>
-
-<ol>
-<li>The current activity's {@code onPause()} method is called.</li>
-
-<li>Next, the starting activity's {@code onCreate()}, {@code onStart()},
-and {@code onResume()} methods are called in sequence.</li>
-
-<li>Then, if the starting activity is no longer visible
-on screen, its {@code onStop()} method is called.</li>
-</ol>
-
-
-<h3 id="servlife">Service lifecycle</h3>
-
-<p>
-A service can be used in two ways:
-</p>
-
-<ul>
-<li>It can be started and allowed to run until someone stops it or
-it stops itself.  In this mode, it's started by calling 
-<code>{@link android.content.Context#startService Context.startService()}</code>
-and stopped by calling 
-<code>{@link android.content.Context#stopService Context.stopService()}</code>.
-It can stop itself by calling 
-<code>{@link android.app.Service#stopSelf() Service.stopSelf()}</code> or
-<code>{@link android.app.Service#stopSelfResult Service.stopSelfResult()}</code>.  
-Only one {@code stopService()} call is needed to stop the service, no matter how 
-many times {@code startService()} was called.</li>
-
-<li><p>It can be operated programmatically using an interface that
-it defines and exports.  Clients establish a connection to the Service 
-object and use that connection to call into the service.  The connection is 
-established by calling  
-<code>{@link android.content.Context#bindService Context.bindService()}</code>,
-and is closed by calling
-<code>{@link android.content.Context#unbindService Context.unbindService()}</code>.
-Multiple clients can bind to the same service.
-If the service has not already been launched, {@code bindService()} can optionally
-launch it.
-</p></li>
-</ul>
-
-<p>
-The two modes are not entirely separate.  You can bind to a service that 
-was started with {@code startService()}.  For example, a background music
-service could be started by calling {@code startService()} with an Intent
-object that identifies the music to play.  Only later, possibly when the 
-user wants to exercise some control over the player or get information 
-about the current song, would an activity
-establish a connection to the service by calling {@code bindService()}.  
-In cases like this, {@code stopService()} 
-will not actually stop the service until the last binding is closed.
-</p>
-
-<p>
-Like an activity, a service has lifecycle methods that you can implement
-to monitor changes in its state.  But they are fewer than the activity 
-methods &mdash; only three &mdash; and they are public, not protected:
-</p>
-
-<p style="margin-left: 2em">{@code void onCreate()}
-<br/>{@code void onStart(Intent <i>intent</i>)}
-<br/>{@code void onDestroy()}</p>
-
-<p>
-By implementing these methods, you can monitor two nested loops of the
-service's lifecycle:
-</p>
-
-<ul>
-<li>The <b>entire lifetime</b> of a service happens between the time
-<code>{@link android.app.Service#onCreate onCreate()}</code> is called and
-the time <code>{@link android.app.Service#onDestroy}</code> returns.  
-Like an activity, a service does its initial setup in {@code onCreate()}, 
-and releases all remaining resources in {@code onDestroy()}.  For example, 
-a music playback service could create the thread where the music will be played  
-in {@code onCreate()}, and then stop the thread in {@code onDestroy()}.</li>
-
-<li><p>The <b>active lifetime</b> of a service begins with a call to 
-<code>{@link android.app.Service#onStartCommand onStartCommand()}</code>.  This method
-is handed the Intent object that was passed to {@code startService()}.
-The music service would open the Intent to discover which music to
-play, and begin the playback.</p>
-
-<p>
-There's no equivalent callback for when the service stops &mdash; no
-{@code onStop()} method.
-</p></li>
-</ul>
-
-<p>
-The {@code onCreate()} and {@code onDestroy()} methods are called for all
-services, whether they're started by 
-<code>{@link android.content.Context#startService Context.startService()}</code>
-or 
-<code>{@link android.content.Context#bindService Context.bindService()}</code>.
-However, {@code onStartCommand()} is called only for services started by {@code
-startService()}.
-</p>
-
-<p>
-If a service permits others to
-bind to it, there are additional callback methods for it to implement:
-</p>
-
-<p style="margin-left: 2em">{@code IBinder onBind(Intent <i>intent</i>)}
-<br/>{@code boolean onUnbind(Intent <i>intent</i>)}
-<br/>{@code void onRebind(Intent <i>intent</i>)}</p>
-
-<p>
-The <code>{@link android.app.Service#onBind onBind()}</code> callback is passed 
-the Intent object that was passed to {@code bindService} and 
-<code>{@link android.app.Service#onUnbind onUnbind()}</code> is handed
-the intent that was passed to {@code unbindService()}.   
-If the service permits the binding, {@code onBind()} 
-returns the communications channel that clients use to interact with the service. 
-The {@code onUnbind()} method can ask for 
-<code>{@link android.app.Service#onRebind onRebind()}</code>
-to be called if a new client connects to the service.
-</p>
-
-<p>
-The following diagram illustrates the callback methods for a service.  
-Although, it separates services that are created via {@code startService}
-from those created by {@code bindService()}, keep in mind that any service,
-no matter how it's started, can potentially allow clients to bind to it,
-so any service may receive {@code onBind()} and {@code onUnbind()} calls.
-</p>
-
-<p style="margin-left: 2em"><img src="{@docRoot}images/service_lifecycle.png"
-alt="State diagram for Service callbacks." /></p>
-
-
-<h3 id="broadlife">Broadcast receiver lifecycle</h3>
-
-<p>
-A broadcast receiver has single callback method:
-</p>
-
-<p style="margin-left: 2em">{@code void onReceive(Context <i>curContext</i>, Intent <i>broadcastMsg</i>)}</p>
-
-<p>
-When a broadcast message arrives for the receiver, Android calls its 
-<code>{@link android.content.BroadcastReceiver#onReceive onReceive()}</code> 
-method and passes it the Intent object containing the message.  The broadcast 
-receiver is considered to be active only while it is executing this method.  
-When {@code onReceive()} returns, it is inactive.
-</p>
-
-<p>
-A process with an active broadcast receiver is protected from being killed. 
-But a process with only inactive components can be killed by the system at 
-any time, when the memory it consumes is needed by other processes.
-</p>
-
-<p>
-This presents a problem when the response to a broadcast message is time 
-consuming and, therefore, something that should be done in a separate thread, 
-away from the main thread where other components of the user interface run.
-If {@code onReceive()} spawns the thread and then returns, the entire process,
-including the new thread, is judged to be inactive (unless other application 
-components are active in the process), putting it in jeopardy of being killed.  
-The solution to this problem is for {@code onReceive()} to start a service 
-and let the service do the job, so the
-system knows that there is still active work being done in the process.
-</p>
-
-<p>
-The next section has more on the vulnerability of processes to being killed.
-</p>
-
-
-<h3 id="proclife">Processes and lifecycles</h3>
-
-<p>The Android system tries to maintain an application process for as
-long as possible, but eventually it will need to remove old processes when
-memory runs low.  To determine which processes to keep and which to kill, 
-Android places each process into an "importance hierarchy" based on the 
-components running in it and the state of those components.  Processes 
-with the lowest importance are eliminated first, then those with the next
-lowest, and so on.  There are five levels in the hierarchy.  The following 
-list presents them in order of importance:
-</p>
-
-<ol>
-
-<li>A <b>foreground process</b> is one that is required for
-what the user is currently doing.  A process is considered to be 
-in the foreground if any of the following conditions hold:
-
-<ul>
-<li>It is running an activity that the user is interacting with 
-(the Activity object's <code>{@link android.app.Activity#onResume 
-onResume()}</code> method has been called).</li>
-
-<li><p>It hosts a service that's bound 
-to the activity that the user is interacting with.</p></li>
-
-<li><p>It has a {@link android.app.Service} object that's executing
-one of its lifecycle callbacks (<code>{@link android.app.Service#onCreate 
-onCreate()}</code>, <code>{@link android.app.Service#onStartCommand onStartCommand()}</code>,
-or <code>{@link android.app.Service#onDestroy onDestroy()}</code>).</p></li>
-
-<li><p>It has a {@link android.content.BroadcastReceiver} object that's 
-executing its <code>{@link android.content.BroadcastReceiver#onReceive 
-onReceive()}</code> method.</p></li>
-</ul>
-
-<p>
-Only a few foreground processes will exist at any given time.  They 
-are killed only as a last resort &mdash; if memory is so low that 
-they cannot all continue to run.  Generally, at that point, the device has
-reached a memory paging state, so killing some foreground processes is 
-required to keep the user interface responsive.
-</p></li>
-
-<li><p>A <b>visible process</b> is one that doesn't have any foreground
-components, but still can affect what the user sees on screen.  
-A process is considered to be visible if either of the following conditions 
-holds:</p>
-
-<ul>
-<li>It hosts an activity that is not in the foreground, but is still visible 
-to the user (its <code>{@link android.app.Activity#onPause onPause()}</code> 
-method has been called).  This may occur, for example, if the foreground 
-activity is a dialog that allows the previous activity to be seen behind it.</li>
-
-<li><p>It hosts a service that's bound to a visible activity.</p></li>
-</ul>
-
-<p>
-A visible process is considered extremely important and will not be killed 
-unless doing so is required to keep all foreground processes running.
-</p></li>
-
-<li><p>A <b>service process</b> is one that is running a service that 
-has been started with the 
-<code>{@link android.content.Context#startService startService()}</code>
-method and that does not fall into either of the two higher categories.  
-Although service processes are not directly tied to anything the 
-user sees, they are generally doing things that the user cares about (such 
-as playing an mp3 in the background or downloading  data on the network), 
-so the system keeps them running unless there's not enough 
-memory to retain them along with all foreground and visible processes.  
-</p></li>
-
-<li><p>A <b>background process</b> is one holding an activity
-that's not currently visible to the user  (the Activity object's
-<code>{@link android.app.Activity#onStop onStop()}</code> method has been called).  
-These processes have no direct impact on the user experience, and can be killed 
-at any time to reclaim memory for a foreground, visible, or service process.  
-Usually there are many background processes running, so they are kept in an 
-LRU (least recently used) list to ensure that the process with the activity that 
-was most recently seen by the user is the last to be killed.
-If an activity implements its lifecycle methods correctly, and captures its current 
-state, killing its process will not have a deleterious effect on the user experience. 
-</p></li>
-
-<li><p>An <b>empty process</b> is one that doesn't hold any active application
-components.  The only reason to keep such a process around is as a cache to
-improve startup time the next time a component needs to run in it.  The system 
-often kills these processes in order to balance overall system resources between 
-process caches and the underlying kernel caches.</p></li>
-
-</ol>
-
-<p>
-Android ranks a process at the highest level it can, based upon the
-importance of the components currently active in the process.  For example, 
-if a process hosts a service and a visible activity, the process will be 
-ranked as a visible process, not a service process.
-</p>
-
-<p>
-In addition, a process's ranking may be increased because other processes are
-dependent on it.  A process that is serving another process can never be 
-ranked lower than the process it is serving.  For example, if a content 
-provider in process A is serving a client in process B, or if a service in 
-process A is bound to a component in process B, process A will always be 
-considered at least as important as process B.
-</p> 
+<p>For a close look at implementing activities&mdash;the components your users use to
+interact with your application&mdash;continue with the <b><a
+href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a></b> document.</p>
 
-<p>
-Because a process running a service is ranked higher than one with background
-activities, an activity that initiates a long-running operation might do
-well to start a service for that operation, rather than simply spawn a thread
-&mdash; particularly if the operation will likely outlast the activity.  
-Examples of this are playing music in the background 
-and uploading a picture taken by the camera to a web site.  Using a service
-guarantees that the operation will have at least "service process" priority,
-regardless of what happens to the activity.  As noted in the 
-<a href="#broadlife">Broadcast receiver lifecycle</a> section earlier, this
-is the same reason that broadcast receivers should employ services rather
-than simply put time-consuming operations in a thread.
-</p>
diff --git a/docs/html/guide/topics/fundamentals/index.jd b/docs/html/guide/topics/fundamentals/index.jd
deleted file mode 100644
index de2e312..0000000
--- a/docs/html/guide/topics/fundamentals/index.jd
+++ /dev/null
@@ -1,496 +0,0 @@
-page.title=Application Fundamentals
-@jd:body
-
-<div id="qv-wrapper">
-<div id="qv">
-
-<h2>Quickview</h2>
-<ul>
-  <li>Android applications are composed of one or more application components (activities,
-services, content providers, and broadcast receivers)</li>
-  <li>Each component performs a different role in the overall application behavior, and each
-one can be activated individually (even by other applications)</li>
-  <li>The manifest file must declare all components in the application and should also declare
-all application requirements, such as the minimum version of Android required and any hardware
-configurations required</li>
-  <li>Non-code application resources (images, strings, layout files, etc.) should include
-alternatives for different device configurations (such as different strings for different
-languages and different layouts for different screen sizes)</li>
-</ul>
-
-
-<h2>In this document</h2>
-<ol>
-<li><a href="#Components">Application Components</a>
-  <ol>
-    <li><a href="#ActivatingComponents">Activating components</a></li>
-  </ol>
-</li>
-<li><a href="#Manifest">The Manifest File</a>
-  <ol>
-    <li><a href="#DeclaringComponents">Declaring components</a></li>
-    <li><a href="#DeclaringRequirements">Declaring application requirements</a></li>
-  </ol>
-</li>
-<li><a href="#Resources">Application Resources</a></li>
-</ol>
-</div>
-</div>
-
-<p>Android applications are written in the Java programming language. The Android SDK tools compile
-the code&mdash;along with any data and resource files&mdash;into an <i>Android package</i>, an
-archive file with an {@code .apk} suffix. All the code in a single {@code .apk} file is considered
-to be one application and is the file that Android-powered devices use to install the
-application.</p>
-
-<p>Once installed on a device, each Android application lives in its own security sandbox: </p>
-
-<ul>
- <li>The Android operating system is a multi-user Linux system in which each application is a
-different user.</li>
-
-<li>By default, the system assigns each application a unique Linux user ID (the ID is used only by
-the system and is unknown to the application). The system sets permissions for all the files in an
-application so that only the user ID assigned to that application can access them. </li>
-
-<li>Each process has its own virtual machine (VM), so an application's code runs in isolation from
-other applications.</li>
-
-<li>By default, every application runs in its own Linux process. Android starts the process when any
-of the application's components need to be executed, then shuts down the process when it's no longer
-needed or when the system must recover memory for other applications.</li>
-</ul>
-
-<p>In this way, the Android system implements the <em>principle of least privilege</em>. That is,
-each application, by default, has access only to the components that it requires to do its work and
-no more. This creates a very secure environment in which an application cannot access parts of
-the system for which it is not given permission.</p>
-
-<p>However, there are ways for an application to share data with other applications and for an
-application to access system services:</p>
-
-<ul>
-  <li>It's possible to arrange for two applications to share the same Linux user ID, in which case
-they are able to access each other's files.  To conserve system resources, applications with the
-same user ID can also arrange to run in the same Linux process and share the same VM (the
-applications must also be signed with the same certificate).</li>
-  <li>An application can request permission to access device data such as the user's
-contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more. All
-application permissions must be granted by the user at install time.</li>
-</ul>
-
-<p>That covers the basics regarding how an Android application exists within the system. The rest of
-this document introduces you to:</p>
-<ul>
-  <li>The core framework components that define your application.</li>
-  <li>The manifest file in which you declare components and required device features for your
-application.</li>
-  <li>Resources that are separate from the application code and allow your application to
-gracefully optimize its behavior for a variety of device configurations.</li>
-</ul>
-
-<p class="note"><strong>Tip:</strong> If you're new to Android development, we suggest that you
-follow the Beginner's Path link at the bottom of this page. For each document in the Application
-Fundamentals, the Beginner's Path points you to the document we suggest you read next, in order
-to get up to speed on the core Android concepts.</p>
-
-
-
-<h2 id="Components">Application Components</h2>
-
-<p>Application components are the essential building blocks of an Android application. Each
-component is a different point through which the system can enter your application. Not all
-components are actual entry points for the user and some depend on each other, but each one exists
-as its own entity and plays a specific role&mdash;each one is a unique building block that
-helps define your application's overall behavior.</p>
-
-<p>There are four different types of application components. Each type serves a distinct purpose
-and has a distinct lifecycle that defines how the component is created and destroyed.</p>
-
-<p>Here are the four types of application components:</p>
-
-<dl>
-
-<dt><b>Activities</b></dt>
-
-<dd>An <i>activity</i> represents a single screen with a user interface. For example,
-an email application might have one activity that shows a list of new
-emails, another activity to compose an email, and another activity for reading emails. Although
-the activities work together to form a cohesive user experience in the email application, each one
-is independent of the others. As such, a different application can start any one of these
-activities (if the email application allows it). For example, a camera application can start the
-activity in the email application that composes new mail, in order for the user to share a picture.
-
-<p>An activity is implemented as a subclass of {@link android.app.Activity} and you can learn more
-about it in the <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a>
-developer guide.</p>
-</dd>
-
-
-<dt><b>Services</b></dt>
-
-<dd>A <i>service</i> is a component that runs in the background to perform long-running
-operations or to perform work for remote processes. A service
-does not provide a user interface. For example, a service might play music in the background while
-the user is in a different application, or it might fetch data over the network without
-blocking user interaction with an activity. Another component, such as an activity, can start the
-service and let it run or bind to it in order to interact with it.
-
-<p>A service is implemented as a subclass of {@link android.app.Service} and you can learn more
-about it in the <a href="{@docRoot}guide/topics/fundamentals/services.html">Services</a> developer
-guide.</p>
-</dd>
-
-
-<dt><b>Content providers</b></dt>
-
-<dd>A <i>content provider</i> manages a shared set of application data. You can store the data in
-the file system, an SQLite database, on the web, or any other persistent storage location your
-application can access. Through the content provider, other applications can query or even modify
-the data (if the content provider allows it). For example, the Android system provides a content
-provider that manages the user's contact information. As such, any application with the proper
-permissions can query part of the content provider (such as {@link
-android.provider.ContactsContract.Data}) to read and write information about a particular person.
-
-<p>Content providers are also useful for reading and writing data that is private to your
-application and not shared. For example, the <a
-href="{@docRoot}resources/samples/NotePad/index.html">Note Pad</a> sample application uses a
-content provider to save notes.</p>
-
-<p>A content provider is implemented as a subclass of {@link android.content.ContentProvider}
-and must implement a standard set of APIs that enable other applications to perform
-transactions. For more information, see the <a
-href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> developer
-guide.</p>
-</dd>
-
-
-<dt><b>Broadcast receivers</b></dt>
-
-<dd>A <i>broadcast receiver</i> is a component that responds to system-wide broadcast
-announcements.  Many broadcasts originate from the system&mdash;for example, a broadcast announcing
-that the screen has turned off, the battery is low, or a picture was captured.
-Applications can also initiate broadcasts&mdash;for example, to let other applications know that
-some data has been downloaded to the device and is available for them to use. Although broadcast
-receivers don't display a user interface, they may <a
-href="{@docRoot}guide/topics/ui/notifiers/notifications.html">create a status bar notification</a>
-to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is
-just a "gateway" to other components and is intended to do a very minimal amount of work. For
-instance, it might initiate a service to perform some work based on the event.
-
-<p>A broadcast receiver is implemented as a subclass of {@link android.content.BroadcastReceiver}
-and each broadcast is delivered as an {@link android.content.Intent} object. For more information,
-see the <a
-href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Filters</a>
-developer guide.</p>
-</dd>
-
-</dl>
-
-
-
-<p>A unique aspect of the Android system design is that any application can start another
-application’s component. For example, if you want the user to capture a
-photo with the device camera, there's probably another application that does that and your
-application can use it, instead of developing an activity to capture a photo yourself. You don't
-need to incorporate or even link to the code from the camera application.
-Instead, you can simply start the activity in the camera application that captures a
-photo. When complete, the photo is even returned to your application so you can use it. To the user,
-it seems as if the camera is actually a part of your application.</p>
-
-<p>When the system starts a component, it starts the process for that application (if it's not
-already running) and instantiates the classes needed for the component. For example, if your
-application starts the activity in the camera application that captures a photo, that activity
-runs in the process that belongs to the camera application, not in your application's process.
-Therefore, unlike applications on most other systems, Android applications don't have a single entry
-point (there's no {@code main()} function, for example).</p>
-
-<p>Because the system runs each application in a separate process with file permissions that
-restrict access to other applications, your application cannot directly activate a component from
-another application. The Android system, however, can. So, to activate a component in
-another application, you must deliver a message to the system that specifies your <em>intent</em> to
-start a particular component. The system then activates the component for you.</p>
-
-
-<h3 id="ActivatingComponents">Activating Components</h3>
-
-<p>Three of the four component types&mdash;activities, services, and
-broadcast receivers&mdash;are activated by an asynchronous message called an <em>intent</em>.
-Intents bind individual components to each other at runtime (you can think of them
-as the messengers that request an action from other components), whether the component belongs
-to your application or another.</p>
-
-<p>An intent is defined by an {@link android.content.Intent} object, which defines a message to
-activate either a specific component or a specific <em>type</em> of component&mdash;an intent
-can be either explicit or implicit, respectively.</p>
-
-<p>For activities and services, an intent defines the action to perform (for example, to "view" or
-"send" something) and may specify the URI of the data to act on (among other things that the
-component being started might need to know). For example, an intent might convey a request for an
-activity to present an image to the user or to open a web page. In some cases, you can start a
-component in order to receive a result, in which case, the component that is started also returns
-the result in an {@link android.content.Intent} object (for example, you can issue an intent to let
-the user pick a personal contact and have it returned to you&mdash;the return intent includes a
-URI pointing to the chosen contact). For broadcast receivers, the intent simply defines the
-announcement being broadcast (for example, a broadcast to indicate the device battery is low
-includes only a known action string that indicates "battery is low").</p>
-
-<p>The remaining type of component, content provider, is not activated by intents. Rather, it is
-activated when targeted by a request from a {@link android.content.ContentResolver}. The content
-resolver handles all direct transactions with the content provider so that the component that's
-performing transactions with the provider doesn't need to and instead calls methods on the {@link
-android.content.ContentResolver} object. This leaves a layer of abstraction between the content
-provider and the component requesting information (for security).</p>
-
-<p>For more information about using intents, see the <a
-href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and
-Intent Filters</a> document. More information about activating specific components is also provided
-in the <a href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a>, <a
-href="{@docRoot}guide/topics/fundamentals/services.html">Services</a>, and <a
-href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> developer
-guides.</p>
-
-
-<h2 id="Manifest">The Manifest File</h2>
-
-<p>Before the Android system can start an application component, the system must know that the
-component exists by reading the application's {@code AndroidManifest.xml} file (the "manifest"
-file). Your application must declare all its components in this file, which must be at the root of
-the application project directory.</p>
-
-<p>The manifest does a number of things in addition to declaring the application's components,
-such as:</p>
-<ul>
-  <li>Identify any user permissions the application requires, such as Internet access or
-read-access to the user's contacts.</li>
-  <li>Declare the minimum <a href="{@docRoot}guide/appendix/api-levels.html">API Level</a>
-required by the application, based on which APIs the application uses.</li>
-  <li>Declare hardware and software features used or required by the application, such as a camera,
-bluetooth services, or a multitouch screen.</li>
-  <li>API libraries the application needs to be linked against (other than the Android framework
-APIs), such as the <a
-href="http://code.google.com/android/add-ons/google-apis/maps-overview.html">Google Maps
-library</a>.</li>
-  <li>And more</li>
-</ul>
-
-
-<h3 id="DeclaringComponents">Declaring components</h3>
-
-<p>The primary task of the manifest is to inform the system about the application's components. For
-example, a manifest file can declare an activity as follows: </p>
-
-<pre>
-&lt;?xml version="1.0" encoding="utf-8"?&gt;
-&lt;manifest ... &gt;
-    &lt;application android:icon="@drawable/app_icon.png" ... &gt;
-        &lt;activity android:name="com.example.project.ExampleActivity"
-                  android:label="@string/example_label" ... &gt;
-        &lt;/activity&gt;
-        ...
-    &lt;/application&gt;
-&lt;/manifest&gt;</pre>
-
-<p>In the <code><a
-href="{@docRoot}guide/topics/manifest/application-element.html">&lt;application&gt;</a></code>
-element, the {@code android:icon} attribute points to resources for an icon that identifies the
-application.</p>
-
-<p>In the <code><a
-href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></code> element,
-the {@code android:name} attribute specifies the fully qualified class name of the {@link
-android.app.Activity} subclass and the {@code android:label} attributes specifies a string
-to use as the user-visible label for the activity.</p>
-
-<p>You must declare all application components this way:</p>
-<ul>
-  <li><code><a
-href="{@docRoot}guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></code> elements
-for activities</li>
-  <li><code><a
-href="{@docRoot}guide/topics/manifest/service-element.html">&lt;service&gt;</a></code> elements for
-services</li>
-  <li><code><a
-href="{@docRoot}guide/topics/manifest/receiver-element.html">&lt;receiver&gt;</a></code> elements
-for broadcast receivers</li>
-  <li><code><a
-href="{@docRoot}guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></code> elements
-for content providers</li>
-</ul>
-
-<p>Activities, services, and content providers that you include in your source but do not declare
-in the manifest are not visible to the system and, consequently, can never run.  However,
-broadcast
-receivers can be either declared in the manifest or created dynamically in code (as
-{@link android.content.BroadcastReceiver} objects) and registered with the system by calling
-{@link android.content.Context#registerReceiver registerReceiver()}.</p>
-
-<p>For more about how to structure the manifest file for your application, see the <a
-href="{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml File</a>
-documentation. </p>
-
-
-
-<h3 id="DeclaringComponentCapabilities">Declaring component capabilities</h3>
-
-<p>As discussed above, in <a href="#ActivatingComponents">Activating Components</a>, you can use an
-{@link android.content.Intent} to start activities, services, and broadcast receivers. You can do so
-by explicitly naming the target component (using the component class name) in the intent. However,
-the real power of intents lies in the concept of intent actions. With intent actions, you simply
-describe the type of action you want to perform (and optionally, the data upon which you’d like to
-perform the action) and allow the system to find a component on the device that can perform the
-action and start it. If there are multiple components that can perform the action described by the
-intent, then the user selects which one to use.</p>
-
-<p>The way the system identifies the components that can respond to an intent is by comparing the
-intent received to the <i>intent filters</i> provided in the manifest file of other applications on
-the device.</p>
-
-<p>When you declare a component in your application's manifest, you can optionally include
-intent filters that declare the capabilities of the component so it can respond to intents
-from other applications. You can declare an intent filter for your component by
-adding an <a href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code
-&lt;intent-filter&gt;}</a> element as a child of the component's declaration element.</p>
-
-<p>For example, an email application with an activity for composing a new email might declare an
-intent filter in its manifest entry to respond to "send" intents (in order to send email). An
-activity in your application can then create an intent with the “send” action ({@link
-android.content.Intent#ACTION_SEND}), which the system matches to the email application’s “send”
-activity and launches it when you invoke the intent with {@link android.app.Activity#startActivity
-startActivity()}.</p>
-
-<p>For more about creating intent filters, see the <a
-href="{@docRoot}guide/topics/intents/intents-filters.html">Intents and Intent Filters</a> document.
-</p>
-
-
-
-<h3 id="DeclaringRequirements">Declaring application requirements</h3>
-
-<p>There are a variety of devices powered by Android and not all of them provide the
-same features and capabilities. In order to prevent your application from being installed on devices
-that lack features needed by your application, it's important that you clearly define a profile for
-the types of devices your application supports by declaring device and software requirements in your
-manifest file. Most of these declarations are informational only and the system does not read
-them, but external services such as Android Market do read them in order to provide filtering
-for users when they search for applications from their device.</p>
-
-<p>For example, if your application requires a camera and uses APIs introduced in Android 2.1 (<a
-href="{@docRoot}guide/appendix/api-levels.html">API Level</a> 7), you should declare these as
-requirements in your manifest file. That way, devices that do <em>not</em> have a camera and have an
-Android version <em>lower</em> than 2.1 cannot install your application from Android Market.</p>
-
-<p>However, you can also declare that your applicaiton uses the camera, but does not
-<em>require</em> it. In that case, your application must perform a check at runtime to determine
-if the device has a camera and disable any features that use the camera if one is not available.</p>
-
-<p>Here are some of the important device characteristics that you should consider as you design and
-develop your application:</p>
-
-<dl>
-  <dt>Screen size and density</dt>
-  <dd>In order to categorize devices by their screen type, Android defines two characteristics for
-each device: screen size (the physical dimensions of the screen) and screen density (the physical
-density of the pixels on the screen, or dpi&mdash;dots per inch). To simplify all the different
-types of screen configurations, the Android system generalizes them into select groups that make
-them easier to target.
-<p>The screen sizes are: small, normal, large, and extra large.<br/>
-The screen densities are: low density, medium density, high density, and extra high density.</p>
-
-<p>By default, your application is compatible with all screen sizes and densities,
-because the Android system makes the appropriate adjustments to your UI layout and image
-resources. However, you should create specialized layouts for certain screen sizes and provide
-specialized images for certain densities, using alternative layout resources, and by declaring in
-your manifest exactly which screen sizes your application supports with the <a
-href="{@docRoot}guide/topics/manifest/supports-screens.html">{@code
-&lt;supports-screens&gt;}</a> element.</p>
-<p>For more information, see the <a
-href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple Screens</a>
-document.</p></dd>
-
-  <dt>Input configurations</dt>
-  <dd>Many devices provide a different type of user input mechanism, such as a hardware keyboard, a
-trackball, or a five-way navigation pad. If your application requires a particular kind of input
-hardware, then you should declare it in your manifest with the <a
-href="{@docRoot}guide/topics/manifest/uses-configuration-element.html">{@code
-&lt;uses-configuration&gt;}</a> element. However, it is rare that an application should require
-a certain input configuration.</dd>
-
-  <dt>Device features</dt>
-  <dd>There are many hardware and software features that may or may not exist on a given
-Android-powered device, such as a camera, a light sensor, bluetooth, a certain
-version of OpenGL, or the fidelity of the touchscreen. You should never assume that a certain
-feature is available on all Android-powered devices (other than the availability of the standard
-Android library), so you should declare any features used by your application with the <a
-href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code &lt;uses-feature&gt;}</a>
-element.</dd>
-
-  <dt>Platform Version</dt>
-  <dd>Different Android-powered devices often run different versions of the Android platform,
-such as Android 1.6 or Android 2.3. Each successive version often includes additional APIs not
-available in the previous version. In order to indicate which set of APIs are available, each
-platform version specifies an <a
-href="{@docRoot}guide/appendix/api-levels.html">API Level</a> (for example, Android 1.0 is API Level
-1 and Android 2.3 is API Level 9). If you use any APIs that were added to the platform after
-version 1.0, you should declare the minimum API Level in which those APIs were introduced using the
-<a href="{@docRoot}guide/topics/manifest/uses-sdk.html">{@code &lt;uses-sdk&gt;}</a> element.</dd>
-</dl>
-
-<p>It's important that you declare all such requirements for your application, because, when you
-distribute your application on Android Market, Market uses these declarations to filter which
-applications are available on each device. As such, your application should be available only to
-devices that meet all your application requirements.</p>
-
-<p>For more information about how Android Market filters applications based on these (and other)
-requirements, see the <a href="{@docRoot}guide/appendix/market-filters.html">Market Filters</a>
-document.</p>
-
-
-
-<h2 id="Resources">Application Resources</h2>
-
-<p>An Android application is composed of more than just code&mdash;it requires resources that are
-separate from the source code, such as images, audio files, and anything relating to the visual
-presentation of the application. For example, you should define animations, menus, styles, colors,
-and the layout of activity user interfaces with XML files. Using application resources makes it easy
-to update various characteristics of your application without modifying code and&mdash;by providing
-sets of alternative resources&mdash;enables you to optimize your application for a  variety of
-device configurations (such as different languages and screen sizes).</p>
-
-<p>For every resource that you include in your Android project, the SDK build tools define a unique
-integer ID, which you can use to reference the resource from your application code or from
-other resources defined in XML. For example, if your application contains an image file named {@code
-logo.png} (saved in the {@code res/drawable/} directory), the SDK tools generate a resource ID
-named {@code R.drawable.logo}, which you can use to reference the image and insert it in your
-user interface.</p>
-
-<p>One of the most important aspects of providing resources separate from your source code
-is the ability for you to provide alternative resources for different device
-configurations. For example, by defining UI strings in XML, you can translate the strings into other
-languages and save those strings in separate files. Then, based on a language <em>qualifier</em>
-that you append to the resource directory's name (such as {@code res/values-fr/} for French string
-values) and the user's language setting, the Android system applies the appropriate language strings
-to your UI.</p>
-
-<p>Android supports many different <em>qualifiers</em> for your alternative resources. The
-qualifier is a short string that you include in the name of your resource directories in order to
-define the device configuration for which those resources should be used. As another
-example, you should often create different layouts for your activities, depending on the
-device's screen orientation and size. For example, when the device screen is in portrait
-orientation (tall), you might want a layout with buttons to be vertical, but when the screen is in
-landscape orientation (wide), the buttons should be aligned horizontally. To change the layout
-depending on the orientation, you can define two different layouts and apply the appropriate
-qualifier to each layout's directory name. Then, the system automatically applies the appropriate
-layout depending on the current device orientation.</p>
-
-<p>For more about the different kinds of resources you can include in your application and how
-to create alternative resources for various device configurations, see the <a
-href="{@docRoot}guide/topics/resources/index.html">Application Resources</a> developer guide.</p>
-
-
-<h2>Beginner's Path</h2>
-
-<p>For a close look at implementing activities&mdash;the components your users use to
-interact with your application&mdash;continue with the <b><a
-href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a></b> document.</p>
-
diff --git a/docs/html/guide/topics/manifest/activity-element.jd b/docs/html/guide/topics/manifest/activity-element.jd
index 2648cb7..5e0b536 100644
--- a/docs/html/guide/topics/manifest/activity-element.jd
+++ b/docs/html/guide/topics/manifest/activity-element.jd
@@ -458,9 +458,7 @@
 
 <p>For more information on launch modes and their interaction with Intent
 flags, see the 
-<a href="{@docRoot}guide/topics/fundamentals.html#acttask">Activities and 
-Tasks</a> section of the 
-<a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>
+<a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back Stack</a>
 document.
 </p>
 </dd>
diff --git a/docs/html/guide/topics/network/sip.jd b/docs/html/guide/topics/network/sip.jd
new file mode 100644
index 0000000..276adb6
--- /dev/null
+++ b/docs/html/guide/topics/network/sip.jd
@@ -0,0 +1,490 @@
+page.title=Session Initiation Protocol
+@jd:body
+<div id="qv-wrapper">
+<div id="qv">
+    <h2>In this document</h2>
+    <ol>
+
+      <li><a href="#requirements">Requirements and Limitations</a></li>
+      <li><a href="#classes">Classes and Interfaces</a></li>
+      <li><a href="#manifest">Creating the Manifest</a></li>
+      <li><a href="#manager">Creating a SIP Manager</a></li>
+      <li><a href="#profiles">Registering with a SIP Server</a></li>
+      <li><a href="#audio">Making an Audio Call</a></li>
+      <li><a href="#receiving">Receiving Calls</a></li>   
+      <li><a href="#testing">Testing SIP Applications</a></li>
+    </ol>
+    
+  <h2>Key classes</h2>
+    <ol>
+      <li>{@link android.net.sip.SipManager}</li>
+      <li>{@link android.net.sip.SipProfile}</li>
+      <li>{@link android.net.sip.SipAudioCall}</li>
+
+    </ol>
+    
+   <h2>Related samples</h2>
+   <ol>
+     <li> <a href="{@docRoot}resources/samples/SipDemo/index.html"> SipDemo</a></li>
+   </ol>
+  </div>
+</div>
+
+<p>Android provides an API that supports the Session Initiation Protocol (SIP).
+This lets you add SIP-based internet telephony features to your applications.
+Android includes a full SIP protocol stack and integrated call management
+services that let applications easily set up outgoing and incoming voice calls,
+without having to manage sessions, transport-level communication, or audio
+record or playback directly.</p>
+
+<p>Here are examples of the types of applications that might use the SIP API:</p>
+<ul>
+  <li>Video conferencing.</li>
+  <li>Instant messaging.</li>
+</ul>
+<h2 id="requirements">Requirements and Limitations</h2>
+<p>Here are the requirements for developing a SIP application:</p>
+<ul>
+  
+  <li>You must have a mobile device that is running Android 2.3 or higher. </li>
+  
+  <li>SIP runs over a wireless data connection, so your device must have a data
+connection (with a mobile data service or Wi-Fi)</span>. This means that you
+can't test on AVD&#8212;you can only test on a physical device. For details, see
+<a href="#testing">Testing SIP Applications</a>.</li>
+
+  <li>Each participant in the application's communication session must have a
+SIP account. There are many different SIP providers that offer SIP accounts.</li>
+</ul>
+
+
+<h2 id="classes">SIP API Classes and Interfaces</h2>
+
+<p>Here is a summary of the classes and one interface
+(<code>SipRegistrationListener</code>) that are included in the Android SIP
+API:</p>
+
+<table>
+  <thead>
+    <tr>
+      <th>Class/Interface</th>
+      <th>Description</th>
+    </tr>
+  </thead>
+  <tbody>
+    <tr>
+      <td>{@link android.net.sip.SipAudioCall}</td>
+      <td>Handles an Internet audio call over SIP.</td>
+    </tr>
+    <tr>
+      <td>{@link android.net.sip.SipAudioCall.Listener}</td>
+      <td>Listener for events relating to a SIP call, such as when a call is being
+received ("on ringing") or a call is outgoing ("on calling").</td>
+    </tr>
+    <tr>
+      <td>{@link android.net.sip.SipErrorCode}</td>
+      <td>Defines error codes returned during SIP actions.</td>
+    </tr>
+    <tr>
+      <td>{@link android.net.sip.SipManager}</td>
+      <td>Provides APIs for SIP tasks, such as initiating SIP connections, and provides access
+to related SIP services.</td>
+    </tr>
+    <tr>
+      <td>{@link android.net.sip.SipProfile}</td>
+      <td>Defines a SIP profile, including a SIP account, domain and server information.
+</td>
+    </tr>
+    <tr>
+      <td>{@link android.net.sip.SipProfile.Builder}</td>
+      <td>Helper class for creating a SipProfile.</td>
+    </tr>
+    <tr>
+      <td>{@link android.net.sip.SipSession}</td>
+      <td>Represents a SIP session that is associated with a SIP dialog or a standalone transaction
+not within a dialog.</td>
+    </tr>
+    <tr>
+      <td>{@link android.net.sip.SipSession.Listener}</td>
+      <td>Listener for events relating to a SIP session, such as when a session is being registered
+("on registering") or a call is outgoing ("on calling"). </td>
+    </tr>
+    <tr>
+      <td>{@link android.net.sip.SipSession.State}</td>
+      <td>Defines SIP session states, such as "registering", "outgoing call", and "in call". </td>
+    </tr>
+    <tr>
+      <td>{@link android.net.sip.SipRegistrationListener}</td>
+      <td>An interface that is a listener for SIP registration events.</td>
+    </tr>
+  </tbody>
+</table>
+
+<h2 id="manifest">Creating the Manifest</h2>
+
+<p>If you are developing an application that uses the SIP API, remember that the
+feature is supported only on Android 2.3 (API level 9) and higher versions of
+the platform. Also, among devices running Android 2.3 (API level 9) or higher,
+not all devices will offer SIP support.</p>
+
+<p>To use SIP, add the following permissions to your application's manifest:</p>
+<ul>
+  <li><code>android.permission.USE_SIP</code></li>
+  <li><code>android.permission.INTERNET</code></li>
+</ul>
+
+<p> To ensure that your application can only be installed on devices that are
+capable of supporting SIP,  add the following to your application's
+manifest:</p>
+
+<ul>
+  <li><code>&lt;uses-sdk android:minSdkVersion=&quot;9&quot; /&gt;</code>. This 
+ indicates that your application requires   Android 2.3 or higher. For more
+information, see <a href="{@docRoot}guide/appendix/api-levels.html">API
+Levels</a> and the documentation for the <a
+href="{@docRoot}guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a
+> element.</li>
+</ul>
+
+<p>To control how your application is filtered from devices that do not support
+SIP (for example, in Android Market), add the following to your application's
+manifest:</p>
+
+<ul>
+
+  <li><code>&lt;uses-feature android:name=&quot;android.hardware.sip.voip&quot;
+/&gt;</code>. This states that your application uses the SIP API. The
+declaration should include an <code>android:required</code> attribute that
+indicates whether you want the application to be filtered from devices that do
+not offer SIP   support. Other <code>&lt;uses-feature&gt;</code> declarations
+may also be   needed, depending on your implementation. For more information,
+see the   documentation for the <a
+href="{@docRoot}guide/topics/manifest/uses-feature-element.html">&lt;uses-
+feature&gt;</a> element.</li>
+  
+</ul>
+<p>If your application is designed to receive calls, you must also define a receiver ({@link android.content.BroadcastReceiver} subclass) in the application's manifest: </p>
+
+<ul>
+  <li><code>&lt;receiver android:name=&quot;.IncomingCallReceiver&quot; android:label=&quot;Call Receiver&quot;/&gt;</code></li>
+</ul>
+<p>Here are excerpts from the <strong>SipDemo</strong> manifest:</p>
+
+
+
+<pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
+&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
+          package=&quot;com.example.android.sip&quot;&gt;
+  ...
+     &lt;receiver android:name=&quot;.IncomingCallReceiver&quot; android:label=&quot;Call Receiver&quot;/&gt;
+  ...
+  &lt;uses-sdk android:minSdkVersion=&quot;9&quot; /&gt;
+  &lt;uses-permission android:name=&quot;android.permission.USE_SIP&quot; /&gt;
+  &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
+  ...
+  &lt;uses-feature android:name=&quot;android.hardware.sip.voip&quot; android:required=&quot;true&quot; /&gt;
+  &lt;uses-feature android:name=&quot;android.hardware.wifi&quot; android:required=&quot;true&quot; /&gt;
+  &lt;uses-feature android:name=&quot;android.hardware.microphone&quot; android:required=&quot;true&quot; /&gt;
+&lt;/manifest&gt;
+</pre>
+
+
+<h2 id="manager">Creating a SipManager</h2>
+
+<p>To use the SIP API, your application must create a {@link
+android.net.sip.SipManager} object. The {@link android.net.sip.SipManager} takes
+care of the following in your application:</p>
+
+<ul>
+  <li>Initiating SIP sessions.</li>
+  <li>Initiating and receiving calls.</li>
+  <li>Registering and unregistering with a SIP provider.</li>
+  <li>Verifying session connectivity.</li>
+</ul>
+<p>You instantiate a new {@link android.net.sip.SipManager} as follows:</p>
+<pre>public SipManager mSipManager = null;
+...
+if(mSipManager == null) {
+    mSipManager = SipManager.newInstance(this);
+}</pre>
+<h2 id="profiles">Registering with a SIP Server</h2>
+
+<p>A typical Android SIP application involves one or more users, each of whom
+has a SIP account. In an Android SIP application, each SIP account  is
+represented by  a {@link android.net.sip.SipProfile} object.</p>
+
+<p>A {@link android.net.sip.SipProfile} defines a SIP profile, including a SIP
+account, and domain and server information. The profile associated with the SIP
+account on the device running the application is called the <em>local
+profile</em>. The profile that the session is connected to is called the
+<em>peer profile</em>. When your SIP application logs into the SIP server with
+the local {@link android.net.sip.SipProfile}, this effectively registers the
+device as the location to send SIP calls to for your SIP address.</p>
+
+<p>This section shows how to create a {@link android.net.sip.SipProfile},
+register it with a SIP server, and track registration events.</p>
+
+<p>You  create a {@link android.net.sip.SipProfile} object as follows:</p>
+<pre>
+public SipProfile mSipProfile = null;
+...
+
+SipProfile.Builder builder = new SipProfile.Builder(username, domain);
+builder.setPassword(password);
+mSipProfile = builder.build();</pre>
+
+<p>The following code excerpt opens the local profile for making calls and/or
+receiving generic SIP calls. The caller can  make subsequent calls through
+<code>mSipManager.makeAudioCall</code>. This excerpt also sets the action
+<code>android.SipDemo.INCOMING_CALL</code>, which will be used by an intent
+filter when the device receives a call (see <a href="#intent_filter">Setting up
+an intent filter to receive calls</a>). This is the registration step:</p>
+
+<pre>Intent intent = new Intent();
+intent.setAction(&quot;android.SipDemo.INCOMING_CALL&quot;);
+PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA);
+mSipManager.open(mSipProfile, pendingIntent, null);</pre>
+
+<p>Finally, this code sets a <code>SipRegistrationListener</code> on the {@link
+android.net.sip.SipManager}. This tracks whether the {@link
+android.net.sip.SipProfile} was successfully registered with your SIP service
+provider:<br>
+</p>
+
+<pre>mSipManager.setRegistrationListener(mSipProfile.getUriString(), new SipRegistrationListener() {
+
+public void onRegistering(String localProfileUri) {
+    updateStatus(&quot;Registering with SIP Server...&quot;);
+}
+
+public void onRegistrationDone(String localProfileUri, long expiryTime) {
+    updateStatus(&quot;Ready&quot;);
+}
+   
+public void onRegistrationFailed(String localProfileUri, int errorCode,
+    String errorMessage) {
+    updateStatus(&quot;Registration failed.  Please check settings.&quot;);
+}</pre>
+
+
+<p>When your application is done using a profile, it should close it to free
+associated objects into memory and unregister the device from the server. For
+example:</p>
+
+<pre>public void closeLocalProfile() {
+    if (mSipManager == null) {
+       return;
+    }
+    try {
+       if (mSipProfile != null) {
+          mSipManager.close(mSipProfile.getUriString());
+       }
+     } catch (Exception ee) {
+       Log.d(&quot;WalkieTalkieActivity/onDestroy&quot;, &quot;Failed to close local profile.&quot;, ee);
+     }
+}</pre>
+
+<h2 id="audio">Making an Audio Call</h2>
+<p>To make an audio call, you must have the following in place:</p>
+<ul>
+
+  <li>A {@link android.net.sip.SipProfile} that is making the call (the
+&quot;local profile&quot;), and a valid SIP address to receive the call (the
+&quot;peer profile&quot;). 
+  
+  <li>A {@link android.net.sip.SipManager} object. </li>
+</ul>
+
+<p>To make an audio call, you should set up a {@link
+android.net.sip.SipAudioCall.Listener}. Much of the client's interaction with
+the SIP stack happens through listeners. In this snippet, you see how the {@link
+android.net.sip.SipAudioCall.Listener} sets things up after the call is
+established:</p>
+
+<pre>
+SipAudioCall.Listener listener = new SipAudioCall.Listener() {
+  
+   &#64;Override
+   public void onCallEstablished(SipAudioCall call) {
+      call.startAudio();
+      call.setSpeakerMode(true);
+      call.toggleMute();
+         ...
+   }
+   
+   &#64;Override
+   public void onCallEnded(SipAudioCall call) {
+      // Do something.
+   }
+};</pre>
+
+<p>Once you've set up the {@link android.net.sip.SipAudioCall.Listener}, you can
+make the  call. The {@link android.net.sip.SipManager} method
+<code>makeAudioCall</code> takes the following parameters:</p>
+
+<ul>
+  <li>A local SIP profile (the caller).</li>
+  <li>A peer SIP profile (the user being called).</li>
+  
+  <li>A {@link android.net.sip.SipAudioCall.Listener} to listen to the call
+events from {@link android.net.sip.SipAudioCall}. This can be <code>null</code>,
+but as shown above, the listener is used to set things up once the call is
+established.</li>
+  
+  <li>The timeout value, in seconds.</li>
+</ul>
+<p>For example:</p>
+<pre> call = mSipManager.makeAudioCall(mSipProfile.getUriString(), sipAddress, listener, 30);</pre>
+
+<h2 id="receiving">Receiving Calls</h2>
+
+<p>To receive calls, a SIP application must include a subclass of {@link
+android.content.BroadcastReceiver} that has the ability to respond to an intent
+indicating that there is an incoming call. Thus, you must do the following in
+your application:</p>
+
+<ul>
+  <li>In <code>AndroidManifest.xml</code>, declare a
+<code>&lt;receiver&gt;</code>. In <strong>SipDemo</strong>, this is
+<code>&lt;receiver android:name=&quot;.IncomingCallReceiver&quot;
+android:label=&quot;Call Receiver&quot;/&gt;</code>.</li>
+  
+  <li>Implement the receiver, which is a subclass of {@link
+android.content.BroadcastReceiver}. In <strong>SipDemo</strong>, this is
+<code>IncomingCallReceiver</code>.</li>
+  
+  <li>Initialize the local profile ({@link android.net.sip.SipProfile}) with a
+pending intent that fires your receiver when someone calls the local profile.
+</li>
+  
+  <li>Set up an intent filter that filters by the action that represents an
+incoming call. In <strong>SipDemo</strong>, this action is
+<code>android.SipDemo.INCOMING_CALL</code>. </li>
+</ul>
+<h4 id="BroadcastReceiver">Subclassing BroadcastReceiver</h4>
+
+<p>To receive calls, your SIP application must subclass {@link
+android.content.BroadcastReceiver}. <span id="internal-source-marker_0.">The
+Android system handles incoming SIP calls and broadcasts an &quot;incoming
+call&quot;<code></code> intent  (as defined by the application) when it receives
+a call.</span> Here is the subclassed {@link android.content.BroadcastReceiver}
+code from <strong>SipDemo</strong>. To see the full example, go to <a
+href="{@docRoot}resources/samples/SipDemo/index.html">SipDemo sample</a>, which
+is included in the SDK samples. For information on downloading and installing
+the SDK samples, see <a
+href="{@docRoot}resources/samples/get.html">
+Getting the Samples</a>. </p>
+
+<pre>/*** Listens for incoming SIP calls, intercepts and hands them off to WalkieTalkieActivity.
+ */
+public class IncomingCallReceiver extends BroadcastReceiver {
+    /**
+     * Processes the incoming call, answers it, and hands it over to the
+     * WalkieTalkieActivity.
+     * @param context The context under which the receiver is running.
+     * @param intent The intent being received.
+     */
+    &#64;Override
+    public void onReceive(Context context, Intent intent) {
+        SipAudioCall incomingCall = null;
+        try {
+            SipAudioCall.Listener listener = new SipAudioCall.Listener() {
+                &#64;Override
+                public void onRinging(SipAudioCall call, SipProfile caller) {
+                    try {
+                        call.answerCall(30);
+                    } catch (Exception e) {
+                        e.printStackTrace();
+                    }
+                }
+            };
+            WalkieTalkieActivity wtActivity = (WalkieTalkieActivity) context;
+            incomingCall = wtActivity.mSipManager.takeAudioCall(intent, listener);
+            incomingCall.answerCall(30);
+            incomingCall.startAudio();
+            incomingCall.setSpeakerMode(true);
+            if(incomingCall.isMuted()) {
+                incomingCall.toggleMute();
+            }
+            wtActivity.call = incomingCall;
+            wtActivity.updateStatus(incomingCall);
+        } catch (Exception e) {
+            if (incomingCall != null) {
+                incomingCall.close();
+            }
+        }
+    }
+}
+</pre>
+
+<h4 id="intent_filter">Setting up an intent filter to receive calls</h4>
+
+<p>When the SIP service  receives a new call, it  sends out an intent with the
+action  string provided by the application. In SipDemo, this action string is
+<code>android.SipDemo.INCOMING_CALL</code>. </p>
+<p>This code excerpt from <strong>SipDemo</strong> shows how the {@link
+android.net.sip.SipProfile} object gets created with a pending intent based on
+the action string <code>android.SipDemo.INCOMING_CALL</code>. The
+<code>PendingIntent</code> object   will perform a broadcast when the {@link
+android.net.sip.SipProfile}  receives a call:</p> 
+
+<pre>
+public SipManager mSipManager = null;
+public SipProfile mSipProfile = null;
+...
+
+Intent intent = new Intent(); 
+intent.setAction(&quot;android.SipDemo.INCOMING_CALL&quot;); 
+PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA); 
+mSipManager.open(mSipProfile, pendingIntent, null);</pre>
+
+<p>The broadcast will be intercepted by the intent filter, which will then fire
+the receiver (<code>IncomingCallReceiver</code>). You can specify an intent
+filter in your application's manifest file, or do it in code as in the <strong>SipDemo</strong>
+sample application's <code>onCreate()</code> method
+of the application's <code>Activity</code>:</p>
+
+<pre>
+public class WalkieTalkieActivity extends Activity implements View.OnTouchListener {
+...
+    public IncomingCallReceiver callReceiver;
+    ...
+
+    &#64;Override
+    public void onCreate(Bundle savedInstanceState) {
+
+       IntentFilter filter = new IntentFilter();
+       filter.addAction(&quot;android.SipDemo.INCOMING_CALL&quot;);
+       callReceiver = new IncomingCallReceiver();
+       this.registerReceiver(callReceiver, filter);
+       ...
+    }
+    ...
+}
+</pre>
+
+
+<h2 id="testing">Testing SIP Applications</h2>
+
+<p>To test SIP applications, you need the following:</p>
+<ul>
+<li>A mobile device that is running Android 2.3 or higher. SIP runs over
+wireless, so you must test on an actual device. Testing on AVD won't work.</li>
+<li>A SIP account. There are many different SIP providers that offer SIP accounts.</li>
+<li>If you are placing a call, it must also be to a valid SIP account. </li>
+</ul>
+<p>To test a SIP application:</p>
+<ol>
+
+<li>On your device, connect to wireless (<strong>Settings > Wireless & networks
+> Wi-Fi > Wi-Fi settings</strong>)</li>
+<li>Set up your mobile device for testing, as described in <a
+href="{@docRoot}guide/developing/device.html">Developing on a Device</a>.</li>
+<li>Run your application on your mobile device, as described in <a
+href="{@docRoot}guide/developing/device.html">Developing on a Device</a>.</li>
+
+<li>If you are using Eclipse, you can view the application log output in Eclipse
+using LogCat (<strong>Window > Show View > Other > Android >
+LogCat</strong>).</li>
+</ol>
+
diff --git a/docs/html/guide/topics/resources/menu-resource.jd b/docs/html/guide/topics/resources/menu-resource.jd
index 33c782b..d09790b 100644
--- a/docs/html/guide/topics/resources/menu-resource.jd
+++ b/docs/html/guide/topics/resources/menu-resource.jd
@@ -12,9 +12,12 @@
   </div>
 </div>
 
-<p>A menu resource defines an application menu (Options Menu, Context Menu, or Sub Menu) that
+<p>A menu resource defines an application menu (Options Menu, Context Menu, or submenu) that
 can be inflated with {@link android.view.MenuInflater}.</p>
 
+<p>For a guide to using menus, see the <a href="{@docRoot}guide/topics/ui/menus.html">Creating
+Menus</a> document.</p>
+
 <dl class="xml">
 
 <dt>file location:</dt>
@@ -110,12 +113,12 @@
 href="{@docRoot}guide/developing/tools/proguard.html">ProGuard</a> (or a similar tool),
 be sure to exclude the method you specify in this attribute from renaming, because it can break the
 functionality.</p>
-          <p>Introduced in API Level HONEYCOMB.</p></dd>
+          <p>Introduced in API Level 11.</p></dd>
 
         <dt><code>android:showAsAction</code></dt>
           <dd><em>Keyword</em>. When and how this item should appear as an action item in the Action
 Bar. A menu item can appear as an action item only when the activity includes an {@link
-android.app.ActionBar} (introduced in API Level HONEYCOMB). Valid values:
+android.app.ActionBar} (introduced in API Level 11). Valid values:
           <table>
             <tr><th>Value</th><th>Description</th></tr>
             <tr><td><code>ifRoom</code></td><td>Only place this item in the Action Bar if
@@ -131,14 +134,14 @@
           </table>
           <p>See <a href="{@docRoot}guide/topics/ui/actionbar.html">Using the Action Bar</a> for
 more information.</p>
-          <p>Introduced in API Level HONEYCOMB.</p>
+          <p>Introduced in API Level 11.</p>
         </dd>
 
         <dt><code>android:actionViewLayout</code></dt>
           <dd><em>Layout resource</em>. A layout to use as the action view.
           <p>See <a href="{@docRoot}guide/topics/ui/actionbar.html">Using the Action Bar</a> for
 more information.</p>
-          <p>Introduced in API Level HONEYCOMB.</p></dd>
+          <p>Introduced in API Level 11.</p></dd>
 
         <dt><code>android:actionViewClassName</code></dt>
           <dd><em>Class name</em>. A fully-qualified class name for the {@link android.view.View}
@@ -149,7 +152,7 @@
 href="{@docRoot}guide/developing/tools/proguard.html">ProGuard</a> (or a similar tool),
 be sure to exclude the class you specify in this attribute from renaming, because it can break the
 functionality.</p>
-          <p>Introduced in API Level HONEYCOMB.</p></dd>
+          <p>Introduced in API Level 11.</p></dd>
 
 
         <dt><code>android:alphabeticShortcut</code></dt>
@@ -277,7 +280,7 @@
 }
 </pre>
 <p class="note"><strong>Note:</strong> The {@code android:showAsAction} attribute is
-available only on Android X.X (API Level HONEYCOMB) and greater.</p>
+available only on Android 3.0 (API Level 11) and greater.</p>
 </dd> <!-- end example -->
 
 
diff --git a/docs/html/guide/topics/resources/runtime-changes.jd b/docs/html/guide/topics/resources/runtime-changes.jd
index e685c9b..74a9073 100644
--- a/docs/html/guide/topics/resources/runtime-changes.jd
+++ b/docs/html/guide/topics/resources/runtime-changes.jd
@@ -31,7 +31,8 @@
 alternative resources.</p>
 
 <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.html#lcycles">Activity
+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
@@ -44,7 +45,7 @@
 <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.html#lcycles">Activity lifecycle</a>).</p>
+<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
diff --git a/docs/html/guide/topics/search/search-dialog.jd b/docs/html/guide/topics/search/search-dialog.jd
index ea8dc1c..6699fe1 100644
--- a/docs/html/guide/topics/search/search-dialog.jd
+++ b/docs/html/guide/topics/search/search-dialog.jd
@@ -423,8 +423,8 @@
 <p>If the current Activity is not the searchable Activity, then the normal Activity lifecycle
 events are triggered once the user executes a search (the current Activity receives {@link
 android.app.Activity#onPause()} and so forth, as
-described in <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Application
-Fundamentals</a>). If, however, the current Activity is the searchable Activity, then one of two
+described in <a href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activities</a>
+document). If, however, the current Activity is the searchable Activity, then one of two
 things happens:</p>
 
 <ol type="a">
diff --git a/docs/html/guide/topics/testing/service_testing.jd b/docs/html/guide/topics/testing/service_testing.jd
index 3979f3c..77884779 100644
--- a/docs/html/guide/topics/testing/service_testing.jd
+++ b/docs/html/guide/topics/testing/service_testing.jd
@@ -56,8 +56,8 @@
 </p>
 <p>
     This document describes techniques for testing Service objects. If you aren't familiar with the
-    Service class, please read <a href="{@docRoot}guide/topics/fundamentals.html">
-    Application Fundamentals</a>. If you aren't familiar with Android testing, please read
+    Service class, please read the <a href="{@docRoot}guide/topics/fundamentals/services.html">
+    Services</a> document. If you aren't familiar with Android testing, please read
     <a href="{@docRoot}guide/topics/testing/testing_android.html">Testing Fundamentals</a>,
     the introduction to the Android testing and instrumentation framework.
 </p>
diff --git a/docs/html/guide/topics/ui/declaring-layout.jd b/docs/html/guide/topics/ui/declaring-layout.jd
index c348767..2da022c 100644
--- a/docs/html/guide/topics/ui/declaring-layout.jd
+++ b/docs/html/guide/topics/ui/declaring-layout.jd
@@ -124,8 +124,9 @@
 </pre>
 
 <p>The <code>onCreate()</code> callback method in your Activity is called by the Android framework when
-your Activity is launched (see the discussion on Lifecycles, in the 
-<a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Application Fundamentals</a>, for more on this).</p>
+your Activity is launched (see the discussion about lifecycles, in the 
+<a href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activities</a>
+document).</p>
 
 
 <h2 id="attributes">Attributes</h2>
diff --git a/docs/html/guide/topics/ui/dialogs.jd b/docs/html/guide/topics/ui/dialogs.jd
index d50e1cb..c1272b6 100644
--- a/docs/html/guide/topics/ui/dialogs.jd
+++ b/docs/html/guide/topics/ui/dialogs.jd
@@ -301,7 +301,7 @@
 
 <p class="note"><strong>Note:</strong> To save the selection when the user leaves or
 pauses the Activity, you must properly save and restore the setting throughout
-the <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Activity Lifecycle</a>. 
+the <a href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">activity lifecycle</a>. 
 To permanently save the selections, even when the Activity process is completely shutdown, 
 you need to save the settings
 with one of the <a href="{@docRoot}guide/topics/data/data-storage.html">Data
diff --git a/docs/html/guide/topics/ui/menus.jd b/docs/html/guide/topics/ui/menus.jd
index d1c0ff8..984bf8f 100644
--- a/docs/html/guide/topics/ui/menus.jd
+++ b/docs/html/guide/topics/ui/menus.jd
@@ -7,11 +7,11 @@
 <div id="qv">
   <h2>In this document</h2>
   <ol>
-    <li><a href="#xml">Defining Menus</a></li>
+    <li><a href="#xml">Creating a Menu Resource</a></li>
     <li><a href="#Inflating">Inflating a Menu Resource</a>
     <li><a href="#options-menu">Creating an Options Menu</a>
       <ol>
-        <li><a href="#ChangingTheMenu">Changing the menu when it opens</a></li>
+        <li><a href="#ChangingTheMenu">Changing menu items at runtime</a></li>
       </ol>
     </li>
     <li><a href="#context-menu">Creating a Context Menu</a></li>
@@ -21,7 +21,7 @@
         <li><a href="#groups">Menu groups</a></li>
         <li><a href="#checkable">Checkable menu items</a></li>
         <li><a href="#shortcuts">Shortcut keys</a></li>
-        <li><a href="#intents">Intents for menu items</a></li>
+        <li><a href="#intents">Dynamically adding menu intents</a></li>
       </ol>
     </li>
   </ol>
@@ -42,52 +42,60 @@
 </div>
 </div>
 
-<p>Menus are an important part of an application that provide a familiar interface for the user
-to access application functions and settings. Android offers an easy programming interface
-for you to provide application menus in your application.</p>
+<p>Menus are an important part of an activity's user interface, which provide users a familiar
+way to perform actions. Android offers a simple framework for you to add standard
+menus to your application.</p>
 
-<p>Android provides three types of application menus:</p>
+<p>There are three types of application menus:</p>
 <dl>
   <dt><strong>Options Menu</strong></dt>
-    <dd>The primary collection of menu items for an Activity that is associated with the device MENU
-key. To provide instant access to select menu items, you can place some items in the <a
-href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>, if available.</dd>
+    <dd>The primary collection of menu items for an activity, which appears when the user touches
+the MENU button. When your application is running on Android 3.0 or later, you can provide
+quick access to select menu items by placing them directly in the <a
+href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>, as "action items."</dd>
   <dt><strong>Context Menu</strong></dt>
-    <dd>A floating list of menu items that appears when the user performs a long-press on a View.
+    <dd>A floating list of menu items that appears when the user touches and holds a view
+that's registered to provide a context menu.
 </dd>
   <dt><strong>Submenu</strong></dt>
-    <dd>A floating list of menu items that the user opens by pressing a menu item in the Options
-Menu or a context menu. A submenu item cannot support a nested submenu. </dd>
+    <dd>A floating list of menu items that appears when the user touches a menu item that contains
+a nested menu.</dd>
 </dl>
 
+<p>This document shows you how to create each type of menu, using XML to define the content of
+the menu and callback methods in your activity to respond when the user selects an item.</p>
 
 
-<h2 id="xml">Defining Menus</h2>
+
+<h2 id="xml">Creating a Menu Resource</h2>
 
 <p>Instead of instantiating a {@link android.view.Menu} in your application code, you should
 define a menu and all its items in an XML <a
 href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>, then inflate the menu
-resource (load it as a programmable object) in your application code. Defining your menus in XML is
-a good practice because it separates your interface design from your application code (the same as
-when you <a href="{@docRoot}guide/topics/ui/declaring-layout.html">define your Activity
-layout</a>).</p>
+resource (load it as a programmable object) in your application code. Using a menu resource to
+define your menu is a good practice because it separates the content for the menu from your
+application code. It's also easier to visualize the structure and content of a menu in XML.</p>
 
-<p>To define a menu, create an XML file inside your project's <code>res/menu/</code>
+<p>To create a menu resource, create an XML file inside your project's <code>res/menu/</code>
 directory and build the menu with the following elements:</p>
 <dl>
   <dt><code>&lt;menu></code></dt>
-    <dd>Creates a {@link android.view.Menu}, which is a container for menu items. It must be
-the root node and holds one or more of the following elements. You can also nest this element
-in an {@code &lt;item&gt;} to create a submenu.</dd>
+    <dd>Defines a {@link android.view.Menu}, which is a container for menu items. A
+<code>&lt;menu></code> element must be the root node for the file and can hold one or more
+<code>&lt;item></code> and <code>&lt;group></code> elements.</dd>
+
   <dt><code>&lt;item></code></dt>
-    <dd>Creates a {@link android.view.MenuItem}, which represents a single item in a menu.</dd>
+    <dd>Creates a {@link android.view.MenuItem}, which represents a single item in a menu. This
+element may contain a nested <code>&lt;menu></code> element in order to create a submenu.</dd>
+    
   <dt><code>&lt;group></code></dt>
     <dd>An optional, invisible container for {@code &lt;item&gt;} elements. It allows you to
-categorize menu items so they share properties such as active state and visibility. See <a
-href="#groups">Menu groups</a>.</dd>
+categorize menu items so they share properties such as active state and visibility. See the
+section about <a href="#groups">Menu groups</a>.</dd>
 </dl>
 
-<p>For example, here is a file in <code>res/menu/</code> named <code>game_menu.xml</code>:</p>
+
+<p>Here's an example menu named <code>game_menu.xml</code>:</p>
 <pre>
 &lt;?xml version="1.0" encoding="utf-8"?&gt;
 &lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt;
@@ -100,28 +108,33 @@
 &lt;/menu&gt;
 </pre>
 
-<p>This example defines a menu with two menu items. Each item includes the attributes:</p>
+<p>This example defines a menu with two items. Each item includes the attributes:</p>
 <dl>
   <dt>{@code android:id}</dt>
-    <dd>A resource ID that's unique to the item so that the application can recognize the item when
-the user selects it.</dd>
+    <dd>A resource ID that's unique to the item, which allows the application can recognize the item
+when the user selects it.</dd>
   <dt>{@code android:icon}</dt>
-    <dd>A drawable resource that is the icon visible to the user.</dd>
+    <dd>A reference to a drawable to use as the item's icon.</dd>
   <dt>{@code android:title}</dt>
-    <dd>A string resource that is the title visible to the user.</dd>
+    <dd>A reference to a string to use as the item's title.</dd>
 </dl>
 
-<p>For more about the XML syntax and attributes for a menu resource, see the <a
+<p>There are many more attributes you can include in an {@code &lt;item&gt;}, including some that
+ specify how the item may appear in the <a
+href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>. For more information about the XML
+syntax and attributes for a menu resource, see the <a
 href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a> reference.</p>
 
 
+
 <h2 id="Inflating">Inflating a Menu Resource</h2>
 
-<p>You can inflate your menu resource (convert the XML resource into a programmable object) using
+<p>From your application code, you can inflate a menu resource (convert the XML resource into a
+programmable object) using
 {@link android.view.MenuInflater#inflate(int,Menu) MenuInflater.inflate()}. For
-example, the following code inflates the <code>game_menu.xml</code> file defined above during the
-{@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} callback method, to be
-used for the Options Menu:</p>
+example, the following code inflates the <code>game_menu.xml</code> file defined above, during the
+{@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} callback method, to
+use the menu as the activity's Options Menu:</p>
 
 <pre>
 &#64;Override
@@ -133,59 +146,47 @@
 </pre>
 
 <p>The {@link android.app.Activity#getMenuInflater()} method returns a {@link
-android.view.MenuInflater} for the Activity. With this object, you can call {@link
+android.view.MenuInflater} for the activity. With this object, you can call {@link
 android.view.MenuInflater#inflate(int,Menu) inflate()}, which inflates a menu resource into a
 {@link android.view.Menu} object. In this example, the menu resource defined by
 <code>game_menu.xml</code>
 is inflated into the {@link android.view.Menu} that was passed into {@link
 android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()}. (This callback method for
-creating an option menu is discussed more in the next section.)</p>
+the Options Menu is discussed more in the next section.)</p>
 
 
 
 <h2 id="options-menu">Creating an Options Menu</h2>
 
 <div class="figure" style="width:200px">
-  <img src="{@docRoot}images/options_menu.png" height="300" alt="" />
-  <p class="img-caption"><strong>Figure 1.</strong> Screenshot of an Options Menu.</p>
+  <img src="{@docRoot}images/options_menu.png" height="333" alt="" />
+  <p class="img-caption"><strong>Figure 1.</strong> Screenshot of the Options Menu in the
+Browser.</p>
 </div>
 
-
-<p>The Options Menu is where you should include basic application functions and necessary navigation
+<p>The Options Menu is where you should include basic activity actions and necessary navigation
 items (for example, a button to open the application settings). Items in the Options Menu are
-accessible in two distinct ways: in the Action Bar and in the menu revealed by the MENU
-key.</p>
+accessible in two distinct ways: the MENU button or in the <a
+href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> (on devices running Android 3.0
+or higher).</p>
 
-<p>The Action Bar is an optional widget that appears at the top of the activity in place of the
-title bar. It can display several menu items that you choose from the Options Menu, but items in
-the Action Bar display only an icon (no title text). Users can reveal the other menu items in the
-Options Menu with the MENU key.</p>
+<p>When running on a device with Android 2.3 and lower, the Options Menu appears at the bottom of
+the screen, as shown in figure 1. When opened, the first visible portion of the Options Menu is
+the icon menu. It holds the first six menu items. If you add more than six items to the
+Options Menu, Android places the sixth item and those after it into the overflow menu, which the
+user can open by touching the "More" menu item.</p>
 
-<p>If you include the Action Bar in your activity, the menu items that are not placed in the Action
-Bar can appear in two different styles:</p>
-<dl>
-  <dt>Action Bar Menu</dt>
-    <dd>If the device has an extra-large screen ({@code xlarge}), then all items in the Options Menu
-that are not placed in the Action Bar are placed into a drop-down list at the right side of the
-Action Bar, with icons and title text. The user can reveal the drop-down list by pressing the
-drop-down icon in the Action Bar or the MENU key.</dd>
-  <dt>Standard Options Menu</dt>
-    <dd>If the device <em>does not</em> have an extra-large screen, then all items in the Options
-Menu that are not placed in the Action Bar are placed into the Standard Options Menu at the bottom
-of the activity. The user can reveal the standard Options Menu by pressing the MENU key.
-    <p>The first visible portion of the Standard Options Menu is called the Icon Menu.
-It holds the first six menu items (excluding any added to the Action Bar), with icons and title
-text. If there are more than six items, Android adds a "More" item as the sixth menu item and places
-the remaining items into the Expanded Menu, which the user can open by selecting "More". The
-Expanded Menu displays menu items only by their title text (no icon)</p>
-    </dd>
-</dl>
+<p>On Android 3.0 and higher, items from the Options Menu is placed in the Action Bar, which appears
+at the top of the activity in place of the traditional title bar. By default all items from the
+Options Menu are placed in the overflow menu, which the user can open by touching the menu icon
+on the right side of the Action Bar. However, you can place select menu items directly in the
+Action Bar as "action items," for instant access, as shown in figure 2.</p>
 
-<p>When the user opens the Options Menu for the first time, Android calls your Activity's
-{@link android.app.Activity#onCreateOptionsMenu(Menu)
-onCreateOptionsMenu()} method. Override this method in your Activity
-and populate the {@link android.view.Menu} that is passed into the method. Populate the
-{@link android.view.Menu} by inflating a menu resource as described in <a
+<p>When the Android system creates the Options Menu for the first time, it calls your
+activity's {@link android.app.Activity#onCreateOptionsMenu(Menu)
+onCreateOptionsMenu()} method. Override this method in your activity
+and populate the {@link android.view.Menu} that is passed into the method,
+{@link android.view.Menu} by inflating a menu resource as described above in <a
 href="#Inflating">Inflating a Menu Resource</a>. For example:</p>
 
 <pre>
@@ -197,17 +198,31 @@
 }
 </pre>
 
-<p>(You can also populate the menu in code, using {@link android.view.Menu#add(int,int,int,int)
-add()} to add items to the {@link android.view.Menu}.)</p>
+<div class="figure" style="width:500px">
+<img src="{@docRoot}images/ui/actionbar.png" height="34" alt="" />
+<p class="img-caption"><strong>Figure 2.</strong> Screenshot of the Action Bar in the Email
+application, with two action items from the Options Menu, plus the overflow menu.</p>
+</div>
 
-<p>When the user selects a menu item from the Options Menu (including items selected from the
-Action Bar), the system calls your Activity's
+<p>You can also populate the menu in code, using {@link android.view.Menu#add(int,int,int,int)
+add()} to add items to the {@link android.view.Menu}.</p>
+
+<p class="note"><strong>Note:</strong> On Android 2.3 and lower, the system calls {@link
+android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} to create the Options Menu
+when the user opens it for the first time, but on Android 3.0 and greater, the system creates it as
+soon as the activity is created, in order to populate the Action Bar.</p>
+
+
+<h3 id="RespondingOptionsMenu">Responding to user action</h3>
+
+<p>When the user selects a menu item from the Options Menu (including action items in the
+Action Bar), the system calls your activity's
 {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}
 method. This method passes the
 {@link android.view.MenuItem} that the user selected. You can identify the menu item by calling
 {@link android.view.MenuItem#getItemId()}, which returns the unique ID for the menu
-item (defined by the {@code android:id} attribute in the menu resource or with an integer passed
-to the {@link android.view.Menu#add(int,int,int,int) add()} method). You can match this ID
+item (defined by the {@code android:id} attribute in the menu resource or with an integer
+given to the {@link android.view.Menu#add(int,int,int,int) add()} method). You can match this ID
 against known menu items and perform the appropriate action. For example:</p>
 
 <pre>
@@ -229,45 +244,67 @@
 
 <p>In this example, {@link android.view.MenuItem#getItemId()} queries the ID for the selected menu
 item and the switch statement compares the ID against the resource IDs that were assigned to menu
-items in the XML resource. When a switch case successfully handles the item, it
-returns "true" to indicate that the item selection was handled. Otherwise, the default statement
-passes the menu item to the super class in
+items in the XML resource. When a switch case successfully handles the menu item, it
+returns {@code true} to indicate that the item selection was handled. Otherwise, the default
+statement passes the menu item to the super class, in
 case it can handle the item selected. (If you've directly extended the {@link android.app.Activity}
-class, then the super class returns "false", but it's a good practice to
-pass unhandled menu items to the super class instead of directly returning "false".)</p>
+class, then the super class returns {@code false}, but it's a good practice to
+pass unhandled menu items to the super class instead of directly returning {@code false}.)</p>
+
+<p>Additionally, Android 3.0 adds the ability for you to define the on-click behavior for a menu
+item in the <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a> XML,
+using the {@code android:onClick} attribute. So you don't need to implement {@link
+android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}. Using the {@code
+android:onClick} attribute, you can specify a method to call when the user selects the menu item.
+Your activity must then implement the method specified in the {@code android:onClick} attribute so 
+that it accepts a single {@link android.view.MenuItem} parameter&mdash;when the system calls this
+method, it passes the menu item selected.</p>
 
 <p class="note"><strong>Tip:</strong> If your application contains multiple activities and
 some of them provide the same Options Menu, consider creating
-an Activity that implements nothing except the {@link android.app.Activity#onCreateOptionsMenu(Menu)
+an activity that implements nothing except the {@link android.app.Activity#onCreateOptionsMenu(Menu)
 onCreateOptionsMenu()} and {@link android.app.Activity#onOptionsItemSelected(MenuItem)
-onOptionsItemSelected()} methods. Then extend this class for each Activity that should share the
+onOptionsItemSelected()} methods. Then extend this class for each activity that should share the
 same Options Menu. This way, you have to manage only one set of code for handling menu
 actions and each descendant class inherits the menu behaviors.<br/><br/>
 If you want to add menu items to one of your descendant activities,
 override {@link android.app.Activity#onCreateOptionsMenu(Menu)
-onCreateOptionsMenu()} in that Activity. Call {@code super.onCreateOptionsMenu(menu)} so the
+onCreateOptionsMenu()} in that activity. Call {@code super.onCreateOptionsMenu(menu)} so the
 original menu items are created, then add new menu items with {@link
 android.view.Menu#add(int,int,int,int) menu.add()}. You can also override the super class's
 behavior for individual menu items.</p>
 
 
-<h3 id="ChangingTheMenu">Changing the menu when it opens</h3>
+<h3 id="ChangingTheMenu">Changing menu items at runtime</h3>
 
-<p>The {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} method is
-called only the first time the Options Menu is opened. The system keeps and re-uses the {@link
-android.view.Menu} you define in this method until your Activity is destroyed. If you want to change
-the Options Menu each time it opens, you must override the
+<p>Once the activity is created, the {@link android.app.Activity#onCreateOptionsMenu(Menu)
+onCreateOptionsMenu()} method is
+called only once, as described above. The system keeps and re-uses the {@link
+android.view.Menu} you define in this method until your activity is destroyed. If you want to change
+the Options Menu any time after it's first created, you must override the
 {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()} method. This passes
 you the {@link android.view.Menu} object as it currently exists. This is useful if you'd like to
 remove, add, disable, or enable menu items depending on the current state of your application.</p>
 
+<p>On Android 2.3 and lower, the system calls {@link android.app.Activity#onPrepareOptionsMenu(Menu)
+onPrepareOptionsMenu()} each time the user opens the Options Menu.</p>
+
+<p>On Android 3.0 and higher, you must call {@link android.app.Activity#invalidateOptionsMenu
+invalidateOptionsMenu()} when you want to update the menu, because the menu is always open. The
+system will then call {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}
+so you can update the menu items.</p>
+
 <p class="note"><strong>Note:</strong> 
 You should never change items in the Options Menu based on the {@link android.view.View} currently
-in focus. When in touch mode (when the user is not using a trackball or d-pad), Views
+in focus. When in touch mode (when the user is not using a trackball or d-pad), views
 cannot take focus, so you should never use focus as the basis for modifying
 items in the Options Menu. If you want to provide menu items that are context-sensitive to a {@link
 android.view.View}, use a <a href="#context-menu">Context Menu</a>.</p>
 
+<p>If you're developing for Android 3.0 or higher, be sure to also read <a
+href="{@docRoot}guide/topics/ui/actionbar.html">Using the Action Bar</a>.</p>
+
+
 
 
 <h2 id="context-menu">Creating a Context Menu</h2>
@@ -287,7 +324,7 @@
 <div class="sidebox-wrapper">
 <div class="sidebox">
 <h3>Register a ListView</h3>
-<p>If your Activity uses a {@link android.widget.ListView} and
+<p>If your activity uses a {@link android.widget.ListView} and
 you want all list items to provide a context menu, register all items for a context
 menu by passing the {@link android.widget.ListView} to {@link
 android.app.Activity#registerForContextMenu(View) registerForContextMenu()}. For
@@ -301,7 +338,7 @@
 pass it the {@link android.view.View} you want to give a context menu. When this View then
 receives a long-press, it displays a context menu.</p>
 
-<p>To define the context menu's appearance and behavior, override your Activity's context menu
+<p>To define the context menu's appearance and behavior, override your activity's context menu
 callback methods, {@link android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo)
 onCreateContextMenu()} and
 {@link android.app.Activity#onContextItemSelected(MenuItem) onContextItemSelected()}.</p>
@@ -325,7 +362,7 @@
 parameters include the {@link android.view.View}
 that the user selected and a {@link android.view.ContextMenu.ContextMenuInfo} object that provides
 additional information about the item selected. You might use these parameters to determine
-which context menu should be created, but in this example, all context menus for the Activity are
+which context menu should be created, but in this example, all context menus for the activity are
 the same.</p>
 
 <p>Then when the user selects an item from the context menu, the system calls {@link
@@ -387,9 +424,9 @@
           android:icon="@drawable/file"
           android:title="@string/file" &gt;
         &lt;!-- "file" submenu --&gt;
-        &lt;menu"&gt;
-            &lt;item android:id="@+id/new"
-                  android:title="@string/new" /&gt;
+        &lt;menu&gt;
+            &lt;item android:id="@+id/create_new"
+                  android:title="@string/create_new" /&gt;
             &lt;item android:id="@+id/open"
                   android:title="@string/open" /&gt;
         &lt;/menu&gt;
@@ -456,8 +493,9 @@
 <h3 id="checkable">Checkable menu items</h3>
 
 <div class="figure" style="width:200px">
-  <img src="{@docRoot}images/radio_buttons.png" height="300" alt="" />
-  <p class="img-caption"><strong>Figure 2.</strong> Screenshot of checkable menu items</p>
+  <img src="{@docRoot}images/radio_buttons.png" height="333" alt="" />
+  <p class="img-caption"><strong>Figure 3.</strong> Screenshot of a submenu with checkable
+items.</p>
 </div>
 
 <p>A menu can be useful as an interface for turning options on and off, using a checkbox for
@@ -525,7 +563,7 @@
 
 <p>If you don't set the checked state this way, then the visible state of the item (the checkbox or
 radio button) will not
-change when the user selects it. When you do set the state, the Activity preserves the checked state
+change when the user selects it. When you do set the state, the activity preserves the checked state
 of the item so that when the user opens the menu later, the checked state that you
 set is visible.</p>
 
@@ -538,7 +576,8 @@
 
 <h3 id="shortcuts">Shortcut keys</h3>
 
-<p>You can add quick-access shortcut keys using letters and/or numbers to menu items with the
+<p>To facilitate quick access to items in the Options Menu when the user's device has a hardware
+keyboard, you can add quick-access shortcut keys using letters and/or numbers, with the
 {@code android:alphabeticShortcut} and {@code android:numericShortcut} attributes in the {@code
 &lt;item&gt;} element. You can also use the methods {@link
 android.view.MenuItem#setAlphabeticShortcut(char)} and {@link
@@ -546,57 +585,46 @@
 case sensitive.</p>
 
 <p>For example, if you apply the "s" character as an alphabetic shortcut to a "save" menu item, then
-when the menu is open (or while the user holds the MENU key) and the user presses the "s" key,
+when the menu is open (or while the user holds the MENU button) and the user presses the "s" key,
 the "save" menu item is selected.</p>
 
 <p>This shortcut key is displayed as a tip in the menu item, below the menu item name
 (except for items in the Icon Menu, which are displayed only if the user holds the MENU
-key).</p>
+button).</p>
 
 <p class="note"><strong>Note:</strong> Shortcut keys for menu items only work on devices with a
 hardware keyboard. Shortcuts cannot be added to items in a Context Menu.</p>
 
 
-<h3 id="intents">Intents for menu items</h3>
 
-<p>Sometimes you'll want a menu item to launch an Activity using an Intent (whether it's an
-Activity in your application or another application). When you know the Intent you want to use and
-have a specific menu item that should initiate the Intent, you can execute the Intent with {@link
-android.app.Activity#startActivity(Intent) startActivity()} during the appropriate on-item-selected
-callback method (such as the {@link android.app.Activity#onOptionsItemSelected(MenuItem)
-onOptionsItemSelected()} callback).</p>
+<h3 id="intents">Dynamically adding menu intents</h3>
+
+<p>Sometimes you'll want a menu item to launch an activity using an {@link android.content.Intent}
+(whether it's an activity in your application or another application). When you know the intent you
+want to use and have a specific menu item that should initiate the intent, you can execute the
+intent with {@link android.app.Activity#startActivity(Intent) startActivity()} during the
+appropriate on-item-selected callback method (such as the {@link
+android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} callback).</p>
 
 <p>However, if you are not certain that the user's device
-contains an application that handles the Intent, then adding a menu item that executes the
-Intent can result in a non-functioning menu item, because the Intent might not resolve to an
-Activity that accepts it. To solve this, Android lets you dynamically add menu items to your menu
-when Android finds activities on the device that handle your Intent.</p>
+contains an application that handles the intent, then adding a menu item that invokes it can result
+in a non-functioning menu item, because the intent might not resolve to an
+activity. To solve this, Android lets you dynamically add menu items to your menu
+when Android finds activities on the device that handle your intent.</p>
 
-<p>If you're not familiar with creating Intents, read the <a
-href="/guide/topics/intents/intents-filters.html">Intents and Intent Filters</a>.</p>
-
-
-<h4>Dynamically adding Intents</h4>
-
-<p>When you don't know if the user's device has an application that handles a specific Intent,
-you can define the Intent and let Android search the device for activities that accept the Intent.
-When it finds activies that handle the Intent, it adds a menu item for
-each one to your menu and attaches the appropriate Intent to open the Activity when the user
-selects it.</p>
-
-<p>To add menu items based on available activities that accept an Intent:</p>
+<p>To add menu items based on available activities that accept an intent:</p>
 <ol>
   <li>Define an
-Intent with the category {@link android.content.Intent#CATEGORY_ALTERNATIVE} and/or
+intent with the category {@link android.content.Intent#CATEGORY_ALTERNATIVE} and/or
 {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE}, plus any other requirements.</li>
   <li>Call {@link
 android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[])
-Menu.addIntentOptions()}. Android then searches for any applications that can perform the Intent
+Menu.addIntentOptions()}. Android then searches for any applications that can perform the intent
 and adds them to your menu.</li>
 </ol>
 
 <p>If there are no applications installed
-that satisfy the Intent, then no menu items are added.</p>
+that satisfy the intent, then no menu items are added.</p>
 
 <p class="note"><strong>Note:</strong>
 {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} is used to handle the currently
@@ -621,7 +649,7 @@
          R.id.intent_group,  // Menu group to which new items will be added
          0,      // Unique item ID (none)
          0,      // Order for the items (none)
-         this.getComponentName(),   // The current Activity name
+         this.getComponentName(),   // The current activity name
          null,   // Specific items to place first (none)
          intent, // Intent created above that describes our requirements
          0,      // Additional flags to control items (none)
@@ -630,8 +658,8 @@
     return true;
 }</pre>
 
-<p>For each Activity found that provides an Intent filter matching the Intent defined, a menu
-item is added, using the value in the Intent filter's <code>android:label</code> as the
+<p>For each activity found that provides an intent filter matching the intent defined, a menu
+item is added, using the value in the intent filter's <code>android:label</code> as the
 menu item title and the application icon as the menu item icon. The
 {@link android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[])
 addIntentOptions()} method returns the number of menu items added.</p>
@@ -642,14 +670,14 @@
 argument.</p>
 
 
-<h4>Allowing your Activity to be added to menus</h4>
+<h4>Allowing your activity to be added to other menus</h4>
 
-<p>You can also offer the services of your Activity to other applications, so your
+<p>You can also offer the services of your activity to other applications, so your
 application can be included in the menu of others (reverse the roles described above).</p>
 
-<p>To be included in other application menus, you need to define an Intent
+<p>To be included in other application menus, you need to define an intent
 filter as usual, but be sure to include the {@link android.content.Intent#CATEGORY_ALTERNATIVE}
-and/or {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} values for the Intent filter
+and/or {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} values for the intent filter
 category. For example:</p>
 <pre>
 &lt;intent-filter label="Resize Image">
@@ -660,7 +688,7 @@
 &lt;/intent-filter>
 </pre>
 
-<p>Read more about writing Intent filters in the
+<p>Read more about writing intent filters in the
 <a href="/guide/topics/intents/intents-filters.html">Intents and Intent Filters</a> document.</p>
 
 <p>For a sample application using this technique, see the 
diff --git a/docs/html/guide/topics/ui/themes.jd b/docs/html/guide/topics/ui/themes.jd
index de699f2..57c9f2e 100644
--- a/docs/html/guide/topics/ui/themes.jd
+++ b/docs/html/guide/topics/ui/themes.jd
@@ -17,6 +17,7 @@
       <ol>
         <li><a href="#ApplyAStyle">Apply a style to a View</a></li>
         <li><a href="#ApplyATheme">Apply a theme to an Activity or application</a></li>
+        <li><a href="#SelectATheme">Select a theme based on platform version</a></li>
       </ol>
     </li>
     <li><a href="#PlatformStyles">Using Platform Styles and Themes</a></li>
@@ -303,21 +304,57 @@
 </pre>
 
 <p>If you like a theme, but want to tweak it, just add the theme as the <code>parent</code>
-of your custom theme. For example, you can modify the traditional dialog theme to use your own
-background image like this:</p>
+of your custom theme. For example, you can modify the traditional light theme to use your own
+color like this:</p>
 <pre>
-&lt;style name="CustomDialogTheme" parent="@android:style/Theme.Dialog">
-    &lt;item name="android:windowBackground">@drawable/custom_dialog_background&lt;/item>
+&lt;color name="custom_theme_color">#b0b0ff&lt;/color>
+&lt;style name="CustomTheme" parent="android:Theme.Light">
+    &lt;item name="android:windowBackground">@color/custom_theme_color&lt;/item>
+    &lt;item name="android:colorBackground">@color/custom_theme_color&lt;/item>
 &lt;/style>
 </pre>
 
-<p>Now use {@code CustomDialogTheme} instead of {@code Theme.Dialog} inside the Android
+<p>(Note that the color needs to supplied as a separate resource here because
+the <code>android:windowBackground</code> attribute only supports a reference to
+another resource; unlike <code>android:colorBackground</code>, it can not be given
+a color literal.)</p>
+
+<p>Now use {@code CustomTheme} instead of {@code Theme.Light} inside the Android
 Manifest:</p>
 
 <pre>
-&lt;activity android:theme="@style/CustomDialogTheme">
+&lt;activity android:theme="@style/CustomTheme">
 </pre>
 
+<h3 id="SelectATheme">Select a theme based on platform version</h3>
+
+<p>Newer versions of Android have additional themes available to applications,
+and you may want to use these while running on those platforms while still being
+compatible with older versions.  You can accomplish this through a custom theme
+that uses resource selection to switch between different parent themes.</p>
+
+<p>For example, here is the declaration for a custom theme which is simply
+the standard platforms default light theme.  It would go in an XML file under
+<code>res/values</code> (typically <code>res/values/styles.xml</code>):
+<pre>
+&lt;style name="LightThemeSelector" parent="android:Theme.Light">
+&lt;/style>
+</pre>
+
+<p>To have this theme use the newer "holo" theme when the application is running
+on {@link android.os.Build.VERSION_CODES#HONEYCOMB}, you can place another
+declaration for it in a file in <code>res/values-11</code>:</p>
+<pre>
+&lt;style name="LightThemeSelector" parent="android:Theme.Holo.Light">
+&lt;/style>
+</pre>
+
+<p>Now use this theme like you would any other, and your application will
+automatically switch to the holo theme if running on
+{@link android.os.Build.VERSION_CODES#HONEYCOMB} or later.</p>
+
+<p>A list of the standard attributes that you can use in themes can be
+found at {@link android.R.styleable#Theme R.styleable.Theme}.</p>
 
 <!-- This currently has some bugs
 
diff --git a/docs/html/guide/tutorials/notepad/notepad-ex3.jd b/docs/html/guide/tutorials/notepad/notepad-ex3.jd
index 573500f..557738e 100644
--- a/docs/html/guide/tutorials/notepad/notepad-ex3.jd
+++ b/docs/html/guide/tutorials/notepad/notepad-ex3.jd
@@ -203,7 +203,8 @@
     have to store enough state to come back up later, preferably in the same
     state it was in when it was killed.</p>
     <p>
-    Android has a <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">well-defined life
+    Activities have a <a
+href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">well-defined life
 cycle</a>.
     Lifecycle events can happen even if you are not handing off control to
     another Activity explicitly. For example, perhaps a call comes in to the
diff --git a/docs/html/images/options_menu.png b/docs/html/images/options_menu.png
index ecb9394..6c49906 100755
--- a/docs/html/images/options_menu.png
+++ b/docs/html/images/options_menu.png
Binary files differ
diff --git a/docs/html/images/radio_buttons.png b/docs/html/images/radio_buttons.png
index b755e42..415ccca 100755
--- a/docs/html/images/radio_buttons.png
+++ b/docs/html/images/radio_buttons.png
Binary files differ
diff --git a/docs/html/resources/dashboard/platform-versions.jd b/docs/html/resources/dashboard/platform-versions.jd
index 21d1ffb..d745cea 100644
--- a/docs/html/resources/dashboard/platform-versions.jd
+++ b/docs/html/resources/dashboard/platform-versions.jd
@@ -52,7 +52,7 @@
 <div class="dashboard-panel">
 
 <img alt="" height="250" width="460"
-src="http://chart.apis.google.com/chart?&cht=p&chs=460x250&chd=t:4.7,7.9,35.2,51.8,0.4&chl=Android%201.5|Android%201.6|Android%202.1|Android%202.2|Android%202.3&chco=c4df9b,6fad0c" />
+src="http://chart.apis.google.com/chart?&cht=p&chs=460x250&chd=t:3.9,6.3,31.4,57.6,0.8&chl=Android%201.5|Android%201.6|Android%202.1|Android%202.2|Android%202.3&chco=c4df9b,6fad0c" />
 
 <table>
 <tr>
@@ -60,14 +60,14 @@
   <th>API Level</th>
   <th>Distribution</th>
 </tr>
-<tr><td>Android 1.5</td><td>3</td><td>4.7%</td></tr> 
-<tr><td>Android 1.6</td><td>4</td><td>7.9%</td></tr> 
-<tr><td>Android 2.1</td><td>7</td><td>35.2%</td></tr> 
-<tr><td>Android 2.2</td><td>8</td><td>51.8%</td></tr> 
-<tr><td>Android 2.3</td><td>9</td><td>0.4%</td></tr> 
+<tr><td>Android 1.5</td><td>3</td><td>3.9%</td></tr> 
+<tr><td>Android 1.6</td><td>4</td><td>6.3%</td></tr> 
+<tr><td>Android 2.1</td><td>7</td><td>31.4%</td></tr> 
+<tr><td>Android 2.2</td><td>8</td><td>57.6%</td></tr> 
+<tr><td>Android 2.3</td><td>9</td><td>0.8%</td></tr> 
 </table>
 
-<p><em>Data collected during two weeks ending on January 4, 2011</em></p>
+<p><em>Data collected during two weeks ending on February 2, 2011</em></p>
 <!--
 <p style="font-size:.9em">* <em>Other: 0.1% of devices running obsolete versions</em></p>
 -->
@@ -96,9 +96,9 @@
 <div class="dashboard-panel">
 
 <img alt="" height="250" width="660" style="padding:5px;background:#fff"
-src="http://chart.apis.google.com/chart?&cht=lc&chs=660x250&chxt=x,x,y,r&chxr=0,0,12|1,0,12|2,0,100|3,0,100&chxl=0%3A%7C07/01%7C07/15%7C08/01%7C08/15%7C09/01%7C09/15%7C10/01%7C10/15%7C11/01%7C11/15%7C12/01%7C12/15%7C01/01%7C1%3A%7C2010%7C%7C%7C%7C%7C%7C%7C%7C%7C%7C%7C%7C2011%7C2%3A%7C0%25%7C25%25%7C50%25%7C75%25%7C100%25%7C3%3A%7C0%25%7C25%25%7C50%25%7C75%25%7C100%25&chxp=0,0,1,2,3,4,5,6,7,8,9,10,11,12&chxtc=0,5&chd=t:99.7,99.8,99.8,99.7,99.8,99.9,99.9,99.9,100.0,99.9,99.8,99.7,99.6|78.4,80.9,84.3,86.5,87.9,89.2,90.2,91.1,92.0,92.7,93.4,94.1,94.8|54.9,58.8,64.0,68.1,70.3,72.1,73.8,75.3,77.4,79.6,82.2,84.4,86.8|1.8,3.3,4.3,11.3,27.8,32.1,33.4,34.5,37.1,40.5,44.3,47.7,51.4&chm=tAndroid 1.5,7caa36,0,0,15,,t::-5|b,c3df9b,0,1,0|tAndroid 1.6,5b831d,1,0,15,,t::-5|b,aadb5e,1,2,0|tAndroid 2.1,38540b,2,0,15,,t::-5|b,91da1e,2,3,0|tAndroid 2.2,131d02,3,3,15,,t::-5|B,6fad0c,3,4,0&chg=7,25&chdl=Android 1.5|Android 1.6|Android 2.1|Android 2.2&chco=add274,94d134,73ad18,507d08" />
+src="http://chart.apis.google.com/chart?&cht=lc&chs=660x250&chxt=x,x,y,r&chxr=0,0,12|1,0,12|2,0,100|3,0,100&chxl=0%3A%7C08/01%7C08/15%7C09/01%7C09/15%7C10/01%7C10/15%7C11/01%7C11/15%7C12/01%7C12/15%7C01/01%7C01/15%7C02/01%7C1%3A%7C2010%7C%7C%7C%7C%7C%7C%7C%7C%7C%7C2011%7C%7C2011%7C2%3A%7C0%25%7C25%25%7C50%25%7C75%25%7C100%25%7C3%3A%7C0%25%7C25%25%7C50%25%7C75%25%7C100%25&chxp=0,0,1,2,3,4,5,6,7,8,9,10,11,12&chxtc=0,5&chd=t:99.8,99.7,99.8,99.9,99.9,99.9,100.0,99.9,99.8,99.7,99.6,99.4,99.1|84.3,86.5,87.9,89.2,90.2,91.1,92.0,92.7,93.4,94.1,94.8,95.1,95.2|64.0,68.1,70.3,72.1,73.8,75.3,77.4,79.6,82.2,84.4,86.8,87.8,88.9|4.3,11.3,27.8,32.1,33.4,34.5,37.1,40.5,44.3,47.7,51.4,53.8,57.5&chm=tAndroid 1.5,7caa36,0,0,15,,t::-5|b,c3df9b,0,1,0|tAndroid 1.6,5b831d,1,0,15,,t::-5|b,aadb5e,1,2,0|tAndroid 2.1,38540b,2,0,15,,t::-5|b,91da1e,2,3,0|tAndroid 2.2,131d02,3,1,15,,t::-5|B,6fad0c,3,4,0&chg=7,25&chdl=Android 1.5|Android 1.6|Android 2.1|Android 2.2&chco=add274,94d134,73ad18,507d08" />
 
-<p><em>Last historical dataset collected during two weeks ending on January 4, 2011</em></p>
+<p><em>Last historical dataset collected during two weeks ending on February 2, 2011</em></p>
 
 
 </div><!-- end dashboard-panel -->
diff --git a/docs/html/resources/faq/commontasks.jd b/docs/html/resources/faq/commontasks.jd
index 807df08..a5f5177 100644
--- a/docs/html/resources/faq/commontasks.jd
+++ b/docs/html/resources/faq/commontasks.jd
@@ -124,8 +124,9 @@
 <h2>Implementing Activity Callbacks</h2>
 <p>Android calls a number of callbacks to let you draw your screen, store data before
     pausing, and refresh data after closing. You must implement at least some of
-    these methods. See <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Lifecycles</a>
-    discussion in Application Fundamentals to learn when and in what order these methods 
+    these methods. Read the <a
+href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activities</a>
+    document to learn when and in what order these methods 
     are called. Here are some of the standard types of screen classes that Android provides:</p>
 <ul>
     <li>{@link android.app.Activity android.app.Activity} - This is a standard screen,
@@ -150,9 +151,9 @@
 <p>When you open a new screen you can decide whether to make it transparent or floating,
     or full-screen. The choice of new screen affects the event sequence of events
     in the old screen (if the new screen obscures the old screen, a different
-    series of events is called in the old screen). See <a
-    href="{@docRoot}guide/topics/fundamentals.html#lcycles">Lifecycles</a> discussion
-    in Application Fundamentals for details. </p> 
+    series of events is called in the old screen). See the <a
+    href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">Activities</a> document for
+details. </p> 
 <p>Transparent or floating windows are implemented in three
     standard ways: </p>
 <ul>
@@ -309,7 +310,8 @@
     the application is finalized. See the topics for {@link android.app.Activity#onSaveInstanceState} and
     {@link android.app.Activity#onCreate} for
     examples of storing and retrieving state.</p>
-<p>Read more about the lifecycle of an application in <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p>
+<p>Read more about the lifecycle of an activity in <a
+href="{@docRoot}guide/topics/fundamentals/activities.html">Activities</a> document.</p>
 <h3>Storing and Retrieving Larger or More Complex Persistent Data<a name="storingandretrieving" id="storingandretrieving"></a></h3>
 <p>Your application can store files or complex collection objects, and reserve them
     for private use by itself or other activities in the application, or it can expose
diff --git a/docs/html/resources/resources-data.js b/docs/html/resources/resources-data.js
index 11964da..5a3145b 100644
--- a/docs/html/resources/resources-data.js
+++ b/docs/html/resources/resources-data.js
@@ -180,7 +180,7 @@
     }
   },
   {
-    tags: ['article', 'ui', 'newfeature'],
+    tags: ['article', 'ui'],
     path: 'articles/live-folders.html',
     title: {
       en: 'Live Folders'
@@ -190,7 +190,7 @@
     }
   },
   {
-    tags: ['article', 'ui', 'newfeature'],
+    tags: ['article', 'ui'],
     path: 'articles/live-wallpapers.html',
     title: {
       en: 'Live Wallpapers'
@@ -250,7 +250,7 @@
     }
   },
   {
-    tags: ['article', 'newfeature'],
+    tags: ['article'],
     path: 'articles/ui-1.5.html',
     title: {
       en: 'UI Framework Changes in Android 1.5'
@@ -260,7 +260,7 @@
     }
   },
   {
-    tags: ['article', 'newfeature'],
+    tags: ['article'],
     path: 'articles/ui-1.6.html',
     title: {
       en: 'UI Framework Changes in Android 1.6'
@@ -435,13 +435,13 @@
     }
   },
   {
-    tags: ['sample', 'new'],
-    path: 'samples/Honeycomb-Gallery/index.html',
+    tags: ['sample', 'new', 'newfeature', 'ui'],
+    path: 'samples/HoneycombGallery/index.html',
     title: {
       en: 'Honeycomb Gallery'
     },
     description: {
-      en: 'An image gallery application using Honeycomb-specific APIs.'
+      en: 'An image gallery application using APIs that are new in Android 3.0 (a.k.a. Honeycomb).'
     }
   },
   {
diff --git a/docs/html/resources/samples/images/hcgallery.png b/docs/html/resources/samples/images/hcgallery.png
index 9a80fd7..42b0183 100644
--- a/docs/html/resources/samples/images/hcgallery.png
+++ b/docs/html/resources/samples/images/hcgallery.png
Binary files differ
diff --git a/docs/html/resources/tutorials/notepad/notepad-ex3.jd b/docs/html/resources/tutorials/notepad/notepad-ex3.jd
index 573500f..557738e 100644
--- a/docs/html/resources/tutorials/notepad/notepad-ex3.jd
+++ b/docs/html/resources/tutorials/notepad/notepad-ex3.jd
@@ -203,7 +203,8 @@
     have to store enough state to come back up later, preferably in the same
     state it was in when it was killed.</p>
     <p>
-    Android has a <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">well-defined life
+    Activities have a <a
+href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">well-defined life
 cycle</a>.
     Lifecycle events can happen even if you are not handing off control to
     another Activity explicitly. For example, perhaps a call comes in to the
diff --git a/docs/html/resources/tutorials/testing/activity_test.jd b/docs/html/resources/tutorials/testing/activity_test.jd
index afb9e3c..c94e8ab 100644
--- a/docs/html/resources/tutorials/testing/activity_test.jd
+++ b/docs/html/resources/tutorials/testing/activity_test.jd
@@ -787,8 +787,8 @@
 <p>
   <strong>Note:</strong> If you would like to learn more about the difference between losing
   focus/pausing and killing an application,
-  refer to the <a href="{@docRoot}guide/topics/fundamentals.html#actlife">Activity Lifecycle</a>
-  section.
+  read about the <a href="{@docRoot}guide/topics/fundamentals/activities.html#Lifecycle">activity
+lifecycle</a>.
 </p>
 <p>
   The first test verifies that the spinner selection is maintained after the entire application is shut down and then restarted. The test uses instrumentation to
diff --git a/docs/html/sdk/1.6_r1/upgrading.jd b/docs/html/sdk/1.6_r1/upgrading.jd
index ebe6a95..49535c9 100644
--- a/docs/html/sdk/1.6_r1/upgrading.jd
+++ b/docs/html/sdk/1.6_r1/upgrading.jd
@@ -1,6 +1,5 @@
 page.title=Upgrading the SDK
 sdk.version=1.6
-sdk.preview=0
 @jd:body
 
 
diff --git a/docs/html/sdk/android-3.0-highlights.jd b/docs/html/sdk/android-3.0-highlights.jd
index ed49307..0378c35 100644
--- a/docs/html/sdk/android-3.0-highlights.jd
+++ b/docs/html/sdk/android-3.0-highlights.jd
@@ -129,7 +129,7 @@
 
 <p style="margin-top:1em;margin-bottom:.75em;"><strong>Camera and Gallery</strong></p>
 
-<p>The Camera application has been redesigned to take advantage of a larger screen for quick access to exposure, focus, flash, zoom, front-facing camera, and more. To let users capture scenes in new ways, it adds built-in support for time-lapse video recording.  Gallery application lets users view albums and other collections in full-screen mode, with easy access to thumbnails for other photos in the collection. </p>
+<p>The Camera application has been redesigned to take advantage of a larger screen for quick access to exposure, focus, flash, zoom, front-facing camera, and more. To let users capture scenes in new ways, it adds built-in support for time-lapse video recording. The Gallery application lets users view albums and other collections in full-screen mode, with easy access to thumbnails for other photos in the collection. </p>
 
 <p style="margin-top:1em;margin-bottom:.75em;"><strong>Contacts</strong></p>
 
diff --git a/docs/html/sdk/ndk/index.jd b/docs/html/sdk/ndk/index.jd
index 2c3fd6a..2f53305 100644
--- a/docs/html/sdk/ndk/index.jd
+++ b/docs/html/sdk/ndk/index.jd
@@ -1,16 +1,16 @@
 ndk=true
 
-ndk.win_download=android-ndk-r5-windows.zip
-ndk.win_bytes=62217450
-ndk.win_checksum=59cbb02d91d74e9c5c7278d94c989e80
+ndk.win_download=android-ndk-r5b-windows.zip
+ndk.win_bytes=61299831
+ndk.win_checksum=87745ada305ab639399161ab4faf684c
 
-ndk.mac_download=android-ndk-r5-darwin-x86.tar.bz2
+ndk.mac_download=android-ndk-r5b-darwin-x86.tar.bz2
 ndk.mac_bytes=50210863
-ndk.mac_checksum=9dee8e4cb529a5619e9b8d1707478c32
+ndk.mac_checksum=019a14622a377b3727ec789af6707037
 
-ndk.linux_download=android-ndk-r5-linux-x86.tar.bz2
-ndk.linux_bytes=44362746
-ndk.linux_checksum=49d5c35ec02bafc074842542c58b7eb3
+ndk.linux_download=android-ndk-r5b-linux-x86.tar.bz2
+ndk.linux_bytes=44138539
+ndk.linux_checksum=4c0045ddc2bfd657be9d5177d0e0b7e7
 
 page.title=Android NDK
 @jd:body
diff --git a/graphics/java/android/graphics/Canvas.java b/graphics/java/android/graphics/Canvas.java
index c1deed3..136e9b4 100644
--- a/graphics/java/android/graphics/Canvas.java
+++ b/graphics/java/android/graphics/Canvas.java
@@ -104,7 +104,7 @@
     public Canvas() {
         // 0 means no native bitmap
         mNativeCanvas = initRaster(0);
-        mFinalizer = new CanvasFinalizer(0);
+        mFinalizer = new CanvasFinalizer(mNativeCanvas);
     }
 
     /**
diff --git a/libs/gui/SurfaceTexture.cpp b/libs/gui/SurfaceTexture.cpp
index 6466f2b3..223cf09 100644
--- a/libs/gui/SurfaceTexture.cpp
+++ b/libs/gui/SurfaceTexture.cpp
@@ -77,7 +77,8 @@
 
 SurfaceTexture::SurfaceTexture(GLuint tex) :
     mBufferCount(MIN_BUFFER_SLOTS), mCurrentTexture(INVALID_BUFFER_SLOT),
-    mLastQueued(INVALID_BUFFER_SLOT), mTexName(tex) {
+    mCurrentTransform(0), mLastQueued(INVALID_BUFFER_SLOT),
+    mLastQueuedTransform(0), mNextTransform(0), mTexName(tex) {
     LOGV("SurfaceTexture::SurfaceTexture");
     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
         mSlots[i].mEglImage = EGL_NO_IMAGE_KHR;
diff --git a/libs/hwui/Caches.cpp b/libs/hwui/Caches.cpp
index ebf7aa0..4f5edd5 100644
--- a/libs/hwui/Caches.cpp
+++ b/libs/hwui/Caches.cpp
@@ -76,8 +76,14 @@
     LOGD("  PathCache            %8d / %8d", pathCache.getSize(), pathCache.getMaxSize());
     LOGD("  CircleShapeCache     %8d / %8d",
             circleShapeCache.getSize(), circleShapeCache.getMaxSize());
+    LOGD("  OvalShapeCache       %8d / %8d",
+            ovalShapeCache.getSize(), ovalShapeCache.getMaxSize());
     LOGD("  RoundRectShapeCache  %8d / %8d",
             roundRectShapeCache.getSize(), roundRectShapeCache.getMaxSize());
+    LOGD("  RectShapeCache       %8d / %8d",
+            rectShapeCache.getSize(), rectShapeCache.getMaxSize());
+    LOGD("  ArcShapeCache        %8d / %8d",
+            arcShapeCache.getSize(), arcShapeCache.getMaxSize());
     LOGD("  TextDropShadowCache  %8d / %8d", dropShadowCache.getSize(),
             dropShadowCache.getMaxSize());
     for (uint32_t i = 0; i < fontRenderer.getFontRendererCount(); i++) {
@@ -94,6 +100,11 @@
     total += gradientCache.getSize();
     total += pathCache.getSize();
     total += dropShadowCache.getSize();
+    total += roundRectShapeCache.getSize();
+    total += circleShapeCache.getSize();
+    total += ovalShapeCache.getSize();
+    total += rectShapeCache.getSize();
+    total += arcShapeCache.getSize();
     for (uint32_t i = 0; i < fontRenderer.getFontRendererCount(); i++) {
         total += fontRenderer.getFontRendererSize(i);
     }
diff --git a/libs/hwui/DisplayListRenderer.cpp b/libs/hwui/DisplayListRenderer.cpp
index cfc853c..d5d2ba0 100644
--- a/libs/hwui/DisplayListRenderer.cpp
+++ b/libs/hwui/DisplayListRenderer.cpp
@@ -22,62 +22,6 @@
 namespace uirenderer {
 
 ///////////////////////////////////////////////////////////////////////////////
-// Defines
-///////////////////////////////////////////////////////////////////////////////
-
-#define PATH_HEAP_SIZE 64
-
-///////////////////////////////////////////////////////////////////////////////
-// Helpers
-///////////////////////////////////////////////////////////////////////////////
-
-PathHeap::PathHeap(): mHeap(PATH_HEAP_SIZE * sizeof(SkPath)) {
-}
-
-PathHeap::PathHeap(SkFlattenableReadBuffer& buffer): mHeap(PATH_HEAP_SIZE * sizeof(SkPath)) {
-    int count = buffer.readS32();
-
-    mPaths.setCount(count);
-    SkPath** ptr = mPaths.begin();
-    SkPath* p = (SkPath*) mHeap.allocThrow(count * sizeof(SkPath));
-
-    for (int i = 0; i < count; i++) {
-        new (p) SkPath;
-        p->unflatten(buffer);
-        *ptr++ = p;
-        p++;
-    }
-}
-
-PathHeap::~PathHeap() {
-    SkPath** iter = mPaths.begin();
-    SkPath** stop = mPaths.end();
-    while (iter < stop) {
-        (*iter)->~SkPath();
-        iter++;
-    }
-}
-
-int PathHeap::append(const SkPath& path) {
-    SkPath* p = (SkPath*) mHeap.allocThrow(sizeof(SkPath));
-    new (p) SkPath(path);
-    *mPaths.append() = p;
-    return mPaths.count();
-}
-
-void PathHeap::flatten(SkFlattenableWriteBuffer& buffer) const {
-    int count = mPaths.count();
-
-    buffer.write32(count);
-    SkPath** iter = mPaths.begin();
-    SkPath** stop = mPaths.end();
-    while (iter < stop) {
-        (*iter)->flatten(buffer);
-        iter++;
-    }
-}
-
-///////////////////////////////////////////////////////////////////////////////
 // Display list
 ///////////////////////////////////////////////////////////////////////////////
 
@@ -124,6 +68,10 @@
 }
 
 DisplayList::~DisplayList() {
+    clearResources();
+}
+
+void DisplayList::clearResources() {
     sk_free((void*) mReader.base());
 
     Caches& caches = Caches::getInstance();
@@ -143,20 +91,22 @@
     }
     mPaints.clear();
 
+    for (size_t i = 0; i < mPaths.size(); i++) {
+        delete mPaths.itemAt(i);
+    }
+    mPaths.clear();
+    for (size_t i = 0; i < mOriginalPaths.size(); i++) {
+        caches.resourceCache.decrementRefcount(mOriginalPaths.itemAt(i));
+    }
+    mOriginalPaths.clear();
+
     for (size_t i = 0; i < mMatrices.size(); i++) {
         delete mMatrices.itemAt(i);
     }
     mMatrices.clear();
-
-    if (mPathHeap) {
-        for (int i = 0; i < mPathHeap->count(); i++) {
-            caches.pathCache.removeDeferred(&(*mPathHeap)[i]);
-        }
-        mPathHeap->safeUnref();
-    }
 }
 
-void DisplayList::initFromDisplayListRenderer(const DisplayListRenderer& recorder) {
+void DisplayList::initFromDisplayListRenderer(const DisplayListRenderer& recorder, bool reusing) {
     const SkWriter32& writer = recorder.writeStream();
     init();
 
@@ -164,17 +114,16 @@
         return;
     }
 
+    if (reusing) {
+        // re-using display list - clear out previous allocations
+        clearResources();
+    }
+
     size_t size = writer.size();
     void* buffer = sk_malloc_throw(size);
     writer.flatten(buffer);
     mReader.setMemory(buffer, size);
 
-    mRCPlayback.reset(&recorder.mRCRecorder);
-    mRCPlayback.setupBuffer(mReader);
-
-    mTFPlayback.reset(&recorder.mTFRecorder);
-    mTFPlayback.setupBuffer(mReader);
-
     Caches& caches = Caches::getInstance();
 
     const Vector<SkBitmap*> &bitmapResources = recorder.getBitmapResources();
@@ -196,19 +145,25 @@
         mPaints.add(paints.itemAt(i));
     }
 
+    const Vector<SkPath*> &paths = recorder.getPaths();
+    for (size_t i = 0; i < paths.size(); i++) {
+        mPaths.add(paths.itemAt(i));
+    }
+
+    const Vector<SkPath*> &originalPaths = recorder.getOriginalPaths();
+    for (size_t i = 0; i < originalPaths.size(); i++) {
+        SkPath* path = originalPaths.itemAt(i);
+        mOriginalPaths.add(path);
+        caches.resourceCache.incrementRefcount(path);
+    }
+
     const Vector<SkMatrix*> &matrices = recorder.getMatrices();
     for (size_t i = 0; i < matrices.size(); i++) {
         mMatrices.add(matrices.itemAt(i));
     }
-
-    mPathHeap = recorder.mPathHeap;
-    if (mPathHeap) {
-        mPathHeap->safeRef();
-    }
 }
 
 void DisplayList::init() {
-    mPathHeap = NULL;
 }
 
 bool DisplayList::replay(OpenGLRenderer& renderer, uint32_t level) {
@@ -557,9 +512,7 @@
 // Base structure
 ///////////////////////////////////////////////////////////////////////////////
 
-DisplayListRenderer::DisplayListRenderer():
-        mHeap(HEAP_BLOCK_SIZE), mWriter(MIN_WRITER_SIZE) {
-    mPathHeap = NULL;
+DisplayListRenderer::DisplayListRenderer(): mWriter(MIN_WRITER_SIZE) {
     mDisplayList = NULL;
 }
 
@@ -568,16 +521,7 @@
 }
 
 void DisplayListRenderer::reset() {
-    if (mPathHeap) {
-        mPathHeap->unref();
-        mPathHeap = NULL;
-    }
-
     mWriter.reset();
-    mHeap.reset();
-
-    mRCRecorder.reset();
-    mTFRecorder.reset();
 
     Caches& caches = Caches::getInstance();
     for (size_t i = 0; i < mBitmapResources.size(); i++) {
@@ -586,6 +530,12 @@
     }
     mBitmapResources.clear();
 
+    for (size_t i = 0; i < mOriginalPaths.size(); i++) {
+        SkPath* resource = mOriginalPaths.itemAt(i);
+        caches.resourceCache.decrementRefcount(resource);
+    }
+    mOriginalPaths.clear();
+
     for (size_t i = 0; i < mShaders.size(); i++) {
        caches.resourceCache.decrementRefcount(mShaders.itemAt(i));
     }
@@ -594,6 +544,8 @@
 
     mPaints.clear();
     mPaintMap.clear();
+    mPaths.clear();
+    mPathMap.clear();
     mMatrices.clear();
 }
 
@@ -605,7 +557,7 @@
     if (mDisplayList == NULL) {
         mDisplayList = new DisplayList(*this);
     } else {
-        mDisplayList->initFromDisplayListRenderer(*this);
+        mDisplayList->initFromDisplayListRenderer(*this, true);
     }
     return mDisplayList;
 }
diff --git a/libs/hwui/DisplayListRenderer.h b/libs/hwui/DisplayListRenderer.h
index a6d2bfe..f39f37f 100644
--- a/libs/hwui/DisplayListRenderer.h
+++ b/libs/hwui/DisplayListRenderer.h
@@ -38,7 +38,6 @@
 ///////////////////////////////////////////////////////////////////////////////
 
 #define MIN_WRITER_SIZE 16384
-#define HEAP_BLOCK_SIZE 4096
 
 // Debug
 #if DEBUG_DISPLAY_LIST
@@ -48,31 +47,6 @@
 #endif
 
 ///////////////////////////////////////////////////////////////////////////////
-// Helpers
-///////////////////////////////////////////////////////////////////////////////
-
-class PathHeap: public SkRefCnt {
-public:
-    PathHeap();
-    PathHeap(SkFlattenableReadBuffer& buffer);
-    ~PathHeap();
-
-    int append(const SkPath& path);
-
-    int count() const { return mPaths.count(); }
-
-    SkPath& operator[](int index) const {
-        return *mPaths[index];
-    }
-
-    void flatten(SkFlattenableWriteBuffer& buffer) const;
-
-private:
-    SkChunkAlloc mHeap;
-    SkTDArray<SkPath*> mPaths;
-};
-
-///////////////////////////////////////////////////////////////////////////////
 // Display list
 ///////////////////////////////////////////////////////////////////////////////
 
@@ -128,13 +102,15 @@
 
     static const char* OP_NAMES[];
 
-    void initFromDisplayListRenderer(const DisplayListRenderer& recorder);
+    void initFromDisplayListRenderer(const DisplayListRenderer& recorder, bool reusing = false);
 
     bool replay(OpenGLRenderer& renderer, uint32_t level = 0);
 
 private:
     void init();
 
+    void clearResources();
+
     class TextContainer {
     public:
         size_t length() const {
@@ -174,7 +150,7 @@
     }
 
     SkPath* getPath() {
-        return &(*mPathHeap)[getInt() - 1];
+        return (SkPath*) getInt();
     }
 
     SkPaint* getPaint() {
@@ -209,19 +185,16 @@
         text->mText = (const char*) mReader.skip(length);
     }
 
-    PathHeap* mPathHeap;
-
     Vector<SkBitmap*> mBitmapResources;
     Vector<SkiaColorFilter*> mFilterResources;
 
     Vector<SkPaint*> mPaints;
+    Vector<SkPath*> mPaths;
+    Vector<SkPath*> mOriginalPaths;
     Vector<SkMatrix*> mMatrices;
     Vector<SkiaShader*> mShaders;
 
     mutable SkFlattenableReadBuffer mReader;
-
-    SkRefCntPlayback mRCPlayback;
-    SkTypefacePlayback mTFPlayback;
 };
 
 ///////////////////////////////////////////////////////////////////////////////
@@ -317,6 +290,14 @@
         return mPaints;
     }
 
+    const Vector<SkPath*>& getPaths() const {
+        return mPaths;
+    }
+
+    const Vector<SkPath*>& getOriginalPaths() const {
+        return mOriginalPaths;
+    }
+
     const Vector<SkMatrix*>& getMatrices() const {
         return mMatrices;
     }
@@ -385,11 +366,27 @@
         mWriter.writePad(text, byteLength);
     }
 
-    inline void addPath(const SkPath* path) {
-        if (mPathHeap == NULL) {
-            mPathHeap = new PathHeap();
+    inline void addPath(SkPath* path) {
+        if (!path) {
+            addInt((int) NULL);
+            return;
         }
-        addInt(mPathHeap->append(*path));
+
+        SkPath* pathCopy = mPathMap.valueFor(path);
+        if (pathCopy == NULL || pathCopy->getGenerationID() != path->getGenerationID()) {
+            if (pathCopy == NULL) {
+                pathCopy = path;
+                mOriginalPaths.add(path);
+                Caches& caches = Caches::getInstance();
+                caches.resourceCache.incrementRefcount(path);
+            } else {
+                pathCopy = new SkPath(*path);
+                mPaths.add(pathCopy);
+            }
+            mPathMap.add(path, pathCopy);
+        }
+
+        addInt((int) pathCopy);
     }
 
     inline void addPaint(SkPaint* paint) {
@@ -457,25 +454,23 @@
         caches.resourceCache.incrementRefcount(colorFilter);
     }
 
-    SkChunkAlloc mHeap;
-
     Vector<SkBitmap*> mBitmapResources;
     Vector<SkiaColorFilter*> mFilterResources;
 
     Vector<SkPaint*> mPaints;
     DefaultKeyedVector<SkPaint*, SkPaint*> mPaintMap;
 
+    Vector<SkPath*> mOriginalPaths;
+    Vector<SkPath*> mPaths;
+    DefaultKeyedVector<SkPath*, SkPath*> mPathMap;
+
     Vector<SkiaShader*> mShaders;
     DefaultKeyedVector<SkiaShader*, SkiaShader*> mShaderMap;
 
     Vector<SkMatrix*> mMatrices;
 
-    PathHeap* mPathHeap;
     SkWriter32 mWriter;
 
-    SkRefCntRecorder mRCRecorder;
-    SkRefCntRecorder mTFRecorder;
-
     DisplayList *mDisplayList;
 
     int mRestoreSaveCount;
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index 90d6ea1..8ee7ec3 100644
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -1217,17 +1217,18 @@
 #if RENDER_LAYERS_AS_REGIONS
         // Mark the current layer dirty where we are going to draw the patch
         if (hasLayer() && mesh->hasEmptyQuads) {
+            const float offsetX = left + mSnapshot->transform->getTranslateX();
+            const float offsetY = top + mSnapshot->transform->getTranslateY();
             const size_t count = mesh->quads.size();
             for (size_t i = 0; i < count; i++) {
                 const Rect& bounds = mesh->quads.itemAt(i);
                 if (pureTranslate) {
-                    const float x = (int) floorf(bounds.left + 0.5f);
-                    const float y = (int) floorf(bounds.top + 0.5f);
-                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight(),
-                            *mSnapshot->transform);
+                    const float x = (int) floorf(bounds.left + offsetX + 0.5f);
+                    const float y = (int) floorf(bounds.top + offsetY + 0.5f);
+                    dirtyLayer(x, y, x + bounds.getWidth(), y + bounds.getHeight());
                 } else {
-                    dirtyLayer(bounds.left, bounds.top, bounds.right, bounds.bottom,
-                            *mSnapshot->transform);
+                    dirtyLayer(left + bounds.left, top + bounds.top,
+                            left + bounds.right, top + bounds.bottom, *mSnapshot->transform);
                 }
             }
         }
diff --git a/libs/hwui/PathCache.cpp b/libs/hwui/PathCache.cpp
index 28c302e..0f22bea 100644
--- a/libs/hwui/PathCache.cpp
+++ b/libs/hwui/PathCache.cpp
@@ -65,7 +65,6 @@
 
 PathTexture* PathCache::get(SkPath* path, SkPaint* paint) {
     PathCacheEntry entry(path, paint);
-
     PathTexture* texture = mCache.get(entry);
 
     if (!texture) {
diff --git a/libs/hwui/ResourceCache.cpp b/libs/hwui/ResourceCache.cpp
index 70d117a..87fdfb5 100644
--- a/libs/hwui/ResourceCache.cpp
+++ b/libs/hwui/ResourceCache.cpp
@@ -65,6 +65,10 @@
     incrementRefcount((void*)bitmapResource, kBitmap);
 }
 
+void ResourceCache::incrementRefcount(SkPath* pathResource) {
+    incrementRefcount((void*)pathResource, kPath);
+}
+
 void ResourceCache::incrementRefcount(SkiaShader* shaderResource) {
     shaderResource->getSkShader()->safeRef();
     incrementRefcount((void*) shaderResource, kShader);
@@ -94,6 +98,10 @@
     decrementRefcount((void*) bitmapResource);
 }
 
+void ResourceCache::decrementRefcount(SkPath* pathResource) {
+    decrementRefcount((void*) pathResource);
+}
+
 void ResourceCache::decrementRefcount(SkiaShader* shaderResource) {
     shaderResource->getSkShader()->safeUnref();
     decrementRefcount((void*) shaderResource);
@@ -122,6 +130,24 @@
     }
 }
 
+void ResourceCache::destructor(SkPath* resource) {
+    Mutex::Autolock _l(mLock);
+    ResourceReference* ref = mCache->indexOfKey(resource) >= 0 ? mCache->valueFor(resource) : NULL;
+    if (ref == NULL) {
+        // If we're not tracking this resource, just delete it
+        if (Caches::hasInstance()) {
+            Caches::getInstance().pathCache.removeDeferred(resource);
+        }
+        delete resource;
+        return;
+    }
+    ref->destroyed = true;
+    if (ref->refCount == 0) {
+        deleteResourceReference(resource, ref);
+        return;
+    }
+}
+
 void ResourceCache::destructor(SkBitmap* resource) {
     Mutex::Autolock _l(mLock);
     ResourceReference* ref = mCache->indexOfKey(resource) >= 0 ? mCache->valueFor(resource) : NULL;
@@ -192,6 +218,15 @@
                 delete bitmap;
             }
             break;
+            case kPath:
+            {
+                SkPath* path = (SkPath*)resource;
+                if (Caches::hasInstance()) {
+                    Caches::getInstance().pathCache.removeDeferred(path);
+                }
+                delete path;
+            }
+            break;
             case kShader:
             {
                 SkiaShader* shader = (SkiaShader*)resource;
diff --git a/libs/hwui/ResourceCache.h b/libs/hwui/ResourceCache.h
index 1bb4390..2a38910 100644
--- a/libs/hwui/ResourceCache.h
+++ b/libs/hwui/ResourceCache.h
@@ -32,6 +32,7 @@
     kBitmap,
     kShader,
     kColorFilter,
+    kPath,
 };
 
 class ResourceReference {
@@ -53,15 +54,18 @@
 public:
     ResourceCache();
     ~ResourceCache();
+    void incrementRefcount(SkPath* resource);
     void incrementRefcount(SkBitmap* resource);
     void incrementRefcount(SkiaShader* resource);
     void incrementRefcount(SkiaColorFilter* resource);
     void incrementRefcount(const void* resource, ResourceType resourceType);
     void decrementRefcount(void* resource);
     void decrementRefcount(SkBitmap* resource);
+    void decrementRefcount(SkPath* resource);
     void decrementRefcount(SkiaShader* resource);
     void decrementRefcount(SkiaColorFilter* resource);
     void recycle(SkBitmap* resource);
+    void destructor(SkPath* resource);
     void destructor(SkBitmap* resource);
     void destructor(SkiaShader* resource);
     void destructor(SkiaColorFilter* resource);
diff --git a/libs/hwui/Snapshot.h b/libs/hwui/Snapshot.h
index 595ad4e..bd70319 100644
--- a/libs/hwui/Snapshot.h
+++ b/libs/hwui/Snapshot.h
@@ -150,6 +150,10 @@
                 break;
             case SkRegion::kIntersect_Op:
                 clipped = clipRect->intersect(r);
+                if (!clipped) {
+                    clipRect->setEmpty();
+                    clipped = true;
+                }
                 break;
             case SkRegion::kUnion_Op:
                 clipped = clipRect->unionWith(r);
diff --git a/libs/hwui/TextDropShadowCache.h b/libs/hwui/TextDropShadowCache.h
index 8cefc8c..ffccfa2 100644
--- a/libs/hwui/TextDropShadowCache.h
+++ b/libs/hwui/TextDropShadowCache.h
@@ -32,7 +32,7 @@
 namespace uirenderer {
 
 struct ShadowText {
-    ShadowText(): radius(0), len(0), hash(0), textSize(0.0f), typeface(NULL) {
+    ShadowText(): radius(0), len(0), textSize(0.0f), typeface(NULL) {
     }
 
     ShadowText(SkPaint* paint, uint32_t radius, uint32_t len, const char* srcText):
@@ -42,20 +42,11 @@
 
         textSize = paint->getTextSize();
         typeface = paint->getTypeface();
-
-        hash = 0;
-        uint32_t multiplier = 1;
-        const char* text = str.string();
-        for (uint32_t i = 0; i < len; i++) {
-            hash += text[i] * multiplier;
-            uint32_t shifted = multiplier << 5;
-            multiplier = shifted - multiplier;
-        }
     }
 
     ShadowText(const ShadowText& shadow):
-            radius(shadow.radius), len(shadow.len), hash(shadow.hash),
-            textSize(shadow.textSize), typeface(shadow.typeface), str(shadow.str) {
+            radius(shadow.radius), len(shadow.len), textSize(shadow.textSize),
+            typeface(shadow.typeface), str(shadow.str) {
     }
 
     ~ShadowText() {
@@ -63,20 +54,17 @@
 
     uint32_t radius;
     uint32_t len;
-    uint32_t hash;
     float textSize;
     SkTypeface* typeface;
     String8 str;
 
     bool operator<(const ShadowText& rhs) const {
-        LTE_INT(hash) {
-            LTE_INT(len) {
-                LTE_INT(radius) {
-                    LTE_FLOAT(textSize) {
-                        if (typeface < rhs.typeface) return true;
-                        else if (typeface == rhs.typeface) {
-                            return str.compare(rhs.str) < 0;
-                        }
+        LTE_INT(len) {
+            LTE_INT(radius) {
+                LTE_FLOAT(textSize) {
+                    if (typeface < rhs.typeface) return true;
+                    else if (typeface == rhs.typeface) {
+                        return str.compare(rhs.str) < 0;
                     }
                 }
             }
diff --git a/libs/rs/java/Balls/AndroidManifest.xml b/libs/rs/java/Balls/AndroidManifest.xml
index 2fffc5f..f3384ec 100644
--- a/libs/rs/java/Balls/AndroidManifest.xml
+++ b/libs/rs/java/Balls/AndroidManifest.xml
@@ -1,6 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.android.balls">
+    <uses-sdk android:minSdkVersion="11" />
     <application 
         android:label="Balls"
         android:icon="@drawable/test_pattern">
diff --git a/libs/rs/java/Fountain/AndroidManifest.xml b/libs/rs/java/Fountain/AndroidManifest.xml
index 951c451..5126e5c 100644
--- a/libs/rs/java/Fountain/AndroidManifest.xml
+++ b/libs/rs/java/Fountain/AndroidManifest.xml
@@ -1,6 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.android.fountain">
+    <uses-sdk android:minSdkVersion="11" />
     <application 
         android:label="Fountain"
         android:icon="@drawable/test_pattern">
diff --git a/libs/rs/java/ImageProcessing/AndroidManifest.xml b/libs/rs/java/ImageProcessing/AndroidManifest.xml
index d6a2db4..0fcbf1e 100644
--- a/libs/rs/java/ImageProcessing/AndroidManifest.xml
+++ b/libs/rs/java/ImageProcessing/AndroidManifest.xml
@@ -3,8 +3,8 @@
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.android.rs.image">
 
-    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    
+    <uses-sdk android:minSdkVersion="11" />
     <application android:label="Image Processing">
         <activity android:name="ImageProcessingActivity"
                   android:screenOrientation="portrait">
diff --git a/libs/rs/java/Samples/AndroidManifest.xml b/libs/rs/java/Samples/AndroidManifest.xml
index 9646a77..8dad161 100644
--- a/libs/rs/java/Samples/AndroidManifest.xml
+++ b/libs/rs/java/Samples/AndroidManifest.xml
@@ -1,6 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.android.samples">
+    <uses-sdk android:minSdkVersion="11" />
     <application android:label="Samples"
     android:icon="@drawable/test_pattern">
         <activity android:name="RsList"
diff --git a/libs/rs/java/Samples/src/com/android/samples/rsbench.rs b/libs/rs/java/Samples/src/com/android/samples/rsbench.rs
index 905f34b..a1368e6 100644
--- a/libs/rs/java/Samples/src/com/android/samples/rsbench.rs
+++ b/libs/rs/java/Samples/src/com/android/samples/rsbench.rs
@@ -297,7 +297,7 @@
     if (buffer == 0) {
         rsgProgramVertexLoadModelMatrix(matrix);
     } else {
-        rsAllocationMarkDirty(rsGetAllocation(buffer));
+        rsgAllocationSyncAll(rsGetAllocation(buffer));
     }
 }
 
@@ -409,7 +409,7 @@
     gVSConstants->light1_Diffuse = 1.0f;
     gVSConstants->light1_Specular = 0.7f;
     gVSConstants->light1_CosinePower = 25.0f;
-    rsAllocationMarkDirty(rsGetAllocation(gVSConstants));
+    rsgAllocationSyncAll(rsGetAllocation(gVSConstants));
 
     // Update fragment shader constants
     // Set light 0 colors
@@ -418,7 +418,7 @@
     // Set light 1 colors
     gFSConstants->light1_DiffuseColor = light1DiffCol;
     gFSConstants->light1_SpecularColor = light1SpecCol;
-    rsAllocationMarkDirty(rsGetAllocation(gFSConstants));
+    rsgAllocationSyncAll(rsGetAllocation(gFSConstants));
 
     // Set light 0 properties for per pixel lighting
     gFSConstPixel->light0_Posision = light0Pos;
@@ -434,7 +434,7 @@
     gFSConstPixel->light1_CosinePower = 25.0f;
     gFSConstPixel->light1_DiffuseColor = light1DiffCol;
     gFSConstPixel->light1_SpecularColor = light1SpecCol;
-    rsAllocationMarkDirty(rsGetAllocation(gFSConstPixel));
+    rsgAllocationSyncAll(rsGetAllocation(gFSConstPixel));
 }
 
 static void displayCustomShaderSamples(int numMeshes) {
diff --git a/libs/rs/java/Samples/src/com/android/samples/rsrenderstates.rs b/libs/rs/java/Samples/src/com/android/samples/rsrenderstates.rs
index 42be4d8..9019533 100644
--- a/libs/rs/java/Samples/src/com/android/samples/rsrenderstates.rs
+++ b/libs/rs/java/Samples/src/com/android/samples/rsrenderstates.rs
@@ -526,7 +526,7 @@
     // Setup the projectioni matrix
     float aspect = (float)rsgGetWidth() / (float)rsgGetHeight();
     rsMatrixLoadPerspective(&gVSConstants->proj, 30.0f, aspect, 0.1f, 100.0f);
-    rsAllocationMarkDirty(rsGetAllocation(gFSConstants));
+    rsgAllocationSyncAll(rsGetAllocation(gFSConstants));
 
     rsgBindProgramVertex(gProgVertexCube);
 
diff --git a/libs/rs/rsScriptC_Lib.cpp b/libs/rs/rsScriptC_Lib.cpp
index 8a85f6e..80da8ae 100644
--- a/libs/rs/rsScriptC_Lib.cpp
+++ b/libs/rs/rsScriptC_Lib.cpp
@@ -856,6 +856,8 @@
     { "__modsi3", (void *)&SC_modsi3, true },
     { "__udivsi3", (void *)&SC_udivsi3, true },
     { "__umodsi3", (void *)&SC_umodsi3, true },
+    { "memset", (void *)&memset, true },
+    { "memcpy", (void *)&memcpy, true },
 
     // allocation
     { "_Z19rsAllocationGetDimX13rs_allocation", (void *)&SC_allocGetDimX, true },
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index 051a0fc..5a59ef6 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -48,7 +48,7 @@
     private final Context mContext;
     private final Handler mHandler;
     private long mVolumeKeyUpTime;
-
+    private int  mVolumeControlStream = -1;
     private static String TAG = "AudioManager";
     private static boolean DEBUG = false;
     private static boolean localLOGV = DEBUG || android.util.Config.LOGV;
@@ -263,6 +263,13 @@
     public static final int FLAG_VIBRATE = 1 << 4;
 
     /**
+     * forces use of specified stream
+     * @hide
+     */
+    public static final int FLAG_FORCE_STREAM = 1 << 5;
+
+
+    /**
      * Ringer mode that will be silent and will not vibrate. (This overrides the
      * vibrate setting.)
      *
@@ -392,12 +399,17 @@
                  * Adjust the volume in on key down since it is more
                  * responsive to the user.
                  */
+                int flags = FLAG_SHOW_UI | FLAG_VIBRATE;
+                if (mVolumeControlStream != -1) {
+                    stream = mVolumeControlStream;
+                    flags |= FLAG_FORCE_STREAM;
+                }
                 adjustSuggestedStreamVolume(
                         keyCode == KeyEvent.KEYCODE_VOLUME_UP
                                 ? ADJUST_RAISE
                                 : ADJUST_LOWER,
                         stream,
-                        FLAG_SHOW_UI | FLAG_VIBRATE);
+                        flags);
                 break;
             case KeyEvent.KEYCODE_VOLUME_MUTE:
                 // TODO: Actually handle MUTE.
@@ -416,10 +428,15 @@
                  * Play a sound. This is done on key up since we don't want the
                  * sound to play when a user holds down volume down to mute.
                  */
+                int flags = FLAG_PLAY_SOUND;
+                if (mVolumeControlStream != -1) {
+                    stream = mVolumeControlStream;
+                    flags |= FLAG_FORCE_STREAM;
+                }
                 adjustSuggestedStreamVolume(
                         ADJUST_SAME,
                         stream,
-                        FLAG_PLAY_SOUND);
+                        flags);
 
                 mVolumeKeyUpTime = SystemClock.uptimeMillis();
                 break;
@@ -683,6 +700,17 @@
     }
 
     /**
+     * forces the stream controlled by hard volume keys
+     * specifying streamType == -1 releases control to the
+     * logic.
+     *
+     * @hide
+     */
+    public void forceVolumeControlStream(int streamType) {
+        mVolumeControlStream = streamType;
+    }
+
+    /**
      * Returns whether a particular type should vibrate according to user
      * settings and the current ringer mode.
      * <p>
diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java
index e18220a..6c85490 100644
--- a/media/java/android/media/AudioService.java
+++ b/media/java/android/media/AudioService.java
@@ -417,6 +417,9 @@
                  (1 << AudioSystem.STREAM_SYSTEM)|(1 << AudioSystem.STREAM_SYSTEM_ENFORCED)|
                  (1 << AudioSystem.STREAM_MUSIC)));
 
+        if (!mVoiceCapable) {
+            mRingerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC);
+        }
         mMuteAffectedStreams = System.getInt(cr,
                 System.MUTE_STREAMS_AFFECTED,
                 ((1 << AudioSystem.STREAM_MUSIC)|(1 << AudioSystem.STREAM_RING)|(1 << AudioSystem.STREAM_SYSTEM)));
@@ -461,7 +464,12 @@
     /** @see AudioManager#adjustVolume(int, int, int) */
     public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
 
-        int streamType = getActiveStreamType(suggestedStreamType);
+        int streamType;
+        if ((flags & AudioManager.FLAG_FORCE_STREAM) != 0) {
+            streamType = suggestedStreamType;
+        } else {
+            streamType = getActiveStreamType(suggestedStreamType);
+        }
 
         // Don't play sound on other streams
         if (streamType != AudioSystem.STREAM_RING && (flags & AudioManager.FLAG_PLAY_SOUND) != 0) {
@@ -1940,7 +1948,7 @@
                     // Force creation of new IAudioflinger interface
                     if (!mMediaServerOk) {
                         Log.e(TAG, "Media server died.");
-                        AudioSystem.isStreamActive(AudioSystem.STREAM_MUSIC, 0);
+                        AudioSystem.isMicrophoneMuted();
                         sendMsg(mAudioHandler, MSG_MEDIA_SERVER_DIED, SHARED_MSG, SENDMSG_NOOP, 0, 0,
                                 null, 500);
                     }
@@ -2025,6 +2033,10 @@
                 int ringerModeAffectedStreams = Settings.System.getInt(mContentResolver,
                         Settings.System.MODE_RINGER_STREAMS_AFFECTED,
                         0);
+                if (!mVoiceCapable) {
+                    ringerModeAffectedStreams |= (1 << AudioSystem.STREAM_MUSIC);
+                }
+
                 if (ringerModeAffectedStreams != mRingerModeAffectedStreams) {
                     /*
                      * Ensure all stream types that should be affected by ringer mode
diff --git a/media/java/android/media/videoeditor/MediaArtistNativeHelper.java b/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
index 297c4df..8214e7f 100644
--- a/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
+++ b/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
@@ -23,7 +23,6 @@
 import java.util.Iterator;
 import java.util.List;
 import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
 
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
@@ -58,6 +57,10 @@
     private static final Paint sResizePaint = new Paint(Paint.FILTER_BITMAP_FLAG);
 
     private final VideoEditor mVideoEditor;
+    /*
+     *  Semaphore to control preview calls
+     */
+    private final Semaphore mLock;
 
     private EditSettings mStoryBoardSettings;
 
@@ -79,11 +82,6 @@
 
     private int mProgressToApp;
 
-    /*
-     *  Semaphore to control preview calls
-     */
-    private final Semaphore mLock = new Semaphore(1, true);
-
     private String mRenderPreviewOverlayFile;
     private int mRenderPreviewRenderingMode;
 
@@ -1775,9 +1773,10 @@
      *
      * @param projectPath The path where the VideoEditor stores all files
      *        related to the project
+     * @param lock The semaphore
      * @param veObj The video editor reference
      */
-    public MediaArtistNativeHelper(String projectPath, VideoEditor veObj) {
+    public MediaArtistNativeHelper(String projectPath, Semaphore lock, VideoEditor veObj) {
         mProjectPath = projectPath;
         if (veObj != null) {
             mVideoEditor = veObj;
@@ -1785,8 +1784,11 @@
             mVideoEditor = null;
             throw new IllegalArgumentException("video editor object is null");
         }
-        if (mStoryBoardSettings == null)
+        if (mStoryBoardSettings == null) {
             mStoryBoardSettings = new EditSettings();
+        }
+
+        mLock = lock;
 
         _init(mProjectPath, "null");
         mAudioTrackPCMFilePath = null;
@@ -1932,16 +1934,8 @@
     /**
      * Release the native helper object
      */
-    void releaseNativeHelper() {
-        try {
-            release();
-        } catch (IllegalStateException ex) {
-            Log.e(TAG, "Illegal State exeption caught in releaseNativeHelper");
-            throw ex;
-        } catch (RuntimeException ex) {
-            Log.e(TAG, "Runtime exeption caught in releaseNativeHelper");
-            throw ex;
-        }
+    void releaseNativeHelper() throws InterruptedException {
+        release();
     }
 
     /**
@@ -2561,6 +2555,14 @@
 
         final List<Effect> effects = m.getAllEffects();
         final List<Overlay> overlays = m.getAllOverlays();
+
+        for (Overlay overlay : overlays) {
+            effectSettings[i] = getOverlaySettings((OverlayFrame)overlay);
+            adjustEffectsStartTimeAndDuration(effectSettings[i], beginCutTime, endCutTime);
+            effectSettings[i].startTime += storyBoardTime;
+            i++;
+        }
+
         for (Effect effect : effects) {
             if (effect instanceof EffectColor) {
                 effectSettings[i] = getEffectSettings((EffectColor)effect);
@@ -2570,12 +2572,6 @@
             }
         }
 
-        for (Overlay overlay : overlays) {
-            effectSettings[i] = getOverlaySettings((OverlayFrame)overlay);
-            adjustEffectsStartTimeAndDuration(effectSettings[i], beginCutTime, endCutTime);
-            effectSettings[i].startTime += storyBoardTime;
-            i++;
-        }
         return i;
     }
 
@@ -2990,27 +2986,28 @@
                         }
                     }
                 }
-            }
-            if (!mErrorFlagSet) {
-                mPreviewEditSettings.videoFrameSize = findVideoResolution(mVideoEditor
-                        .getAspectRatio(), maxHeight);
-                populateBackgroundMusicProperties(mediaBGMList);
 
-                /** call to native populate settings */
-                try {
-                    nativePopulateSettings(mPreviewEditSettings, mClipProperties, mAudioSettings);
-                } catch (IllegalArgumentException ex) {
-                    Log.e(TAG, "Illegal argument exception in nativePopulateSettings");
-                    throw ex;
-                } catch (IllegalStateException ex) {
-                    Log.e(TAG, "Illegal state exception in nativePopulateSettings");
-                    throw ex;
-                } catch (RuntimeException ex) {
-                    Log.e(TAG, "Runtime exception in nativePopulateSettings");
-                    throw ex;
+                if (!mErrorFlagSet) {
+                    mPreviewEditSettings.videoFrameSize = findVideoResolution(mVideoEditor
+                            .getAspectRatio(), maxHeight);
+                    populateBackgroundMusicProperties(mediaBGMList);
+
+                    /** call to native populate settings */
+                    try {
+                        nativePopulateSettings(mPreviewEditSettings, mClipProperties, mAudioSettings);
+                    } catch (IllegalArgumentException ex) {
+                        Log.e(TAG, "Illegal argument exception in nativePopulateSettings");
+                        throw ex;
+                    } catch (IllegalStateException ex) {
+                        Log.e(TAG, "Illegal state exception in nativePopulateSettings");
+                        throw ex;
+                    } catch (RuntimeException ex) {
+                        Log.e(TAG, "Runtime exception in nativePopulateSettings");
+                        throw ex;
+                    }
+                    mInvalidatePreviewArray = false;
+                    mProcessingState  = PROCESSING_NONE;
                 }
-                mInvalidatePreviewArray = false;
-                mProcessingState  = PROCESSING_NONE;
             }
             if (mErrorFlagSet) {
                 mErrorFlagSet = false;
@@ -3735,18 +3732,15 @@
      */
     Bitmap getPixels(String inputFile, int width, int height, long timeMS) {
         if (inputFile == null) {
-            throw new IllegalArgumentException();
+            throw new IllegalArgumentException("Invalid input file");
         }
 
-        int newWidth = 0;
-        int newHeight = 0;
-        Bitmap tempBitmap = null;
-
         /* Make width and height as even */
-        newWidth = (width + 1) & 0xFFFFFFFE;
-        newHeight = (height + 1) & 0xFFFFFFFE;
+        final int newWidth = (width + 1) & 0xFFFFFFFE;
+        final int newHeight = (height + 1) & 0xFFFFFFFE;
 
         /* Create a temp bitmap for resized thumbnails */
+        Bitmap tempBitmap = null;
         if ((newWidth != width) || (newHeight != height)) {
              tempBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
         }
@@ -3770,6 +3764,7 @@
         if (tempBitmap != null) {
             tempBitmap.recycle();
         }
+
         return bitmap;
     }
 
@@ -3787,17 +3782,15 @@
      *
      * @return The frames as bitmaps in bitmap array
      **/
-    public Bitmap[] getPixelsList(String filename, int width, int height, long startMs, long endMs,
+    Bitmap[] getPixelsList(String filename, int width, int height, long startMs, long endMs,
             int thumbnailCount) {
         int[] rgb888 = null;
         int thumbnailSize = 0;
-        int newWidth = 0;
-        int newHeight = 0;
         Bitmap tempBitmap = null;
 
         /* Make width and height as even */
-        newWidth = (width + 1) & 0xFFFFFFFE;
-        newHeight = (height + 1) & 0xFFFFFFFE;
+        final int newWidth = (width + 1) & 0xFFFFFFFE;
+        final int newHeight = (height + 1) & 0xFFFFFFFE;
         thumbnailSize = newWidth * newHeight * 4;
 
         /* Create a temp bitmap for resized thumbnails */
@@ -3820,7 +3813,8 @@
                 bitmaps = new Bitmap[MAX_THUMBNAIL_PERMITTED];
                 thumbnailCount = MAX_THUMBNAIL_PERMITTED;
             } catch (Throwable ex) {
-                throw new RuntimeException("Memory allocation fails, thumbnail count too large: "+thumbnailCount);
+                throw new RuntimeException("Memory allocation fails, thumbnail count too large: "
+                        + thumbnailCount);
             }
         }
         IntBuffer tmpBuffer = IntBuffer.allocate(thumbnailSize);
@@ -3848,6 +3842,7 @@
         if (tempBitmap != null) {
             tempBitmap.recycle();
         }
+
         return bitmaps;
     }
 
@@ -3908,7 +3903,7 @@
      *
      * @throws InterruptedException
      */
-    void lock() throws InterruptedException {
+    private void lock() throws InterruptedException {
         if (Log.isLoggable(TAG, Log.DEBUG)) {
             Log.d(TAG, "lock: grabbing semaphore", new Throwable());
         }
@@ -3919,30 +3914,9 @@
     }
 
     /**
-     * Tries to grab the semaphore with a specified time out which arbitrates access to the editor
-     *
-     * @param timeoutMs time out in ms.
-     *
-     * @return true if the semaphore is acquired, false otherwise
-     * @throws InterruptedException
-     */
-    boolean lock(long timeoutMs) throws InterruptedException {
-        if (Log.isLoggable(TAG, Log.DEBUG)) {
-            Log.d(TAG, "lock: grabbing semaphore with timeout " + timeoutMs, new Throwable());
-        }
-
-        boolean acquireSem = mLock.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS);
-        if (Log.isLoggable(TAG, Log.DEBUG)) {
-            Log.d(TAG, "lock: grabbed semaphore status " + acquireSem);
-        }
-
-        return acquireSem;
-    }
-
-    /**
      * Release the semaphore which arbitrates access to the editor
      */
-    void unlock() {
+    private void unlock() {
         if (Log.isLoggable(TAG, Log.DEBUG)) {
             Log.d(TAG, "unlock: releasing semaphore");
         }
diff --git a/media/java/android/media/videoeditor/MediaProperties.java b/media/java/android/media/videoeditor/MediaProperties.java
index a2e01f6..34186e9 100755
--- a/media/java/android/media/videoeditor/MediaProperties.java
+++ b/media/java/android/media/videoeditor/MediaProperties.java
@@ -198,6 +198,11 @@
     public static final int FILE_UNSUPPORTED = 255;
 
     /**
+     * Undefined video codec profiles
+     */
+    public static final int UNDEFINED_VIDEO_PROFILE = 255;
+
+    /**
      * The array of the supported file formats
      */
     private static final int[] SUPPORTED_VIDEO_FILE_FORMATS = new int[] {
diff --git a/media/java/android/media/videoeditor/MediaVideoItem.java b/media/java/android/media/videoeditor/MediaVideoItem.java
index bbadd62..d3505849 100755
--- a/media/java/android/media/videoeditor/MediaVideoItem.java
+++ b/media/java/android/media/videoeditor/MediaVideoItem.java
@@ -139,6 +139,11 @@
                 throw new IllegalArgumentException("Unsupported Video Codec Format in Input File");
         }
 
+        /* Check if the profile is unsupported. */
+        if (properties.profileAndLevel == MediaProperties.UNDEFINED_VIDEO_PROFILE) {
+            throw new IllegalArgumentException("Unsupported Video Codec Profile in Input File");
+        }
+
         mWidth = properties.width;
         mHeight = properties.height;
         mAspectRatio = mMANativeHelper.getAspectRatio(properties.width,
diff --git a/media/java/android/media/videoeditor/Transition.java b/media/java/android/media/videoeditor/Transition.java
index 4d1bafb..95f002c 100755
--- a/media/java/android/media/videoeditor/Transition.java
+++ b/media/java/android/media/videoeditor/Transition.java
@@ -288,6 +288,16 @@
         List<EffectSettings> effectSettings = new ArrayList<EffectSettings>();
         EffectSettings tmpEffectSettings;
 
+        overlays = m.getAllOverlays();
+        for (Overlay overlay : overlays) {
+            tmpEffectSettings = mNativeHelper.getOverlaySettings((OverlayFrame)overlay);
+            mNativeHelper.adjustEffectsStartTimeAndDuration(tmpEffectSettings,
+                    clipSettings.beginCutTime, clipSettings.endCutTime);
+            if (tmpEffectSettings.duration != 0) {
+                effectSettings.add(tmpEffectSettings);
+            }
+        }
+
         effects = m.getAllEffects();
         for (Effect effect : effects) {
             if (effect instanceof EffectColor) {
@@ -303,15 +313,7 @@
                 }
             }
         }
-        overlays = m.getAllOverlays();
-        for (Overlay overlay : overlays) {
-            tmpEffectSettings = mNativeHelper.getOverlaySettings((OverlayFrame)overlay);
-            mNativeHelper.adjustEffectsStartTimeAndDuration(tmpEffectSettings,
-                    clipSettings.beginCutTime, clipSettings.endCutTime);
-            if (tmpEffectSettings.duration != 0) {
-                effectSettings.add(tmpEffectSettings);
-            }
-        }
+
          return effectSettings;
     }
 
diff --git a/media/java/android/media/videoeditor/VideoEditorImpl.java b/media/java/android/media/videoeditor/VideoEditorImpl.java
index 33a8654..3019057 100755
--- a/media/java/android/media/videoeditor/VideoEditorImpl.java
+++ b/media/java/android/media/videoeditor/VideoEditorImpl.java
@@ -27,6 +27,9 @@
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 import org.xmlpull.v1.XmlSerializer;
@@ -118,11 +121,12 @@
     /*
      *  Instance variables
      */
-    private long mDurationMs;
+    private final Semaphore mLock;
     private final String mProjectPath;
     private final List<MediaItem> mMediaItems = new ArrayList<MediaItem>();
     private final List<AudioTrack> mAudioTracks = new ArrayList<AudioTrack>();
     private final List<Transition> mTransitions = new ArrayList<Transition>();
+    private long mDurationMs;
     private int mAspectRatio;
 
     /*
@@ -138,7 +142,8 @@
      *        related to the project
      */
     public VideoEditorImpl(String projectPath) throws IOException {
-        mMANativeHelper = new MediaArtistNativeHelper(projectPath, this);
+        mLock = new Semaphore(1, true);
+        mMANativeHelper = new MediaArtistNativeHelper(projectPath, mLock, this);
         mProjectPath = projectPath;
         final File projectXml = new File(projectPath, PROJECT_FILENAME);
         if (projectXml.exists()) {
@@ -417,15 +422,20 @@
 
         boolean semAcquireDone = false;
         try {
-            mMANativeHelper.lock();
+            lock();
             semAcquireDone = true;
+
+            if (mMANativeHelper == null) {
+                throw new IllegalStateException("The video editor is not initialized");
+            }
+
             mMANativeHelper.export(filename, mProjectPath, height,bitrate,
                                mMediaItems, mTransitions, mAudioTracks, listener);
         } catch (InterruptedException  ex) {
             Log.e(TAG, "Sem acquire NOT successful in export");
         } finally {
             if (semAcquireDone) {
-                mMANativeHelper.unlock();
+                unlock();
             }
         }
     }
@@ -436,9 +446,13 @@
     public void generatePreview(MediaProcessingProgressListener listener) {
         boolean semAcquireDone = false;
         try {
-            mMANativeHelper.lock();
+            lock();
             semAcquireDone = true;
 
+            if (mMANativeHelper == null) {
+                throw new IllegalStateException("The video editor is not initialized");
+            }
+
             if ((mMediaItems.size() > 0) || (mAudioTracks.size() > 0)) {
                 mMANativeHelper.previewStoryBoard(mMediaItems, mTransitions, mAudioTracks,
                         listener);
@@ -447,7 +461,7 @@
             Log.e(TAG, "Sem acquire NOT successful in previewStoryBoard");
         } finally {
             if (semAcquireDone) {
-                mMANativeHelper.unlock();
+                unlock();
             }
         }
     }
@@ -675,11 +689,26 @@
      */
     public void release() {
         stopPreview();
-        mMediaItems.clear();
-        mAudioTracks.clear();
-        mTransitions.clear();
-        mMANativeHelper.releaseNativeHelper();
-        mMANativeHelper = null;
+
+        boolean semAcquireDone = false;
+        try {
+            lock();
+            semAcquireDone = true;
+
+            if (mMANativeHelper != null) {
+                mMediaItems.clear();
+                mAudioTracks.clear();
+                mTransitions.clear();
+                mMANativeHelper.releaseNativeHelper();
+                mMANativeHelper = null;
+            }
+        } catch (Exception  ex) {
+            Log.e(TAG, "Sem acquire NOT successful in export", ex);
+        } finally {
+            if (semAcquireDone) {
+                unlock();
+            }
+        }
     }
 
     /*
@@ -854,11 +883,15 @@
 
         boolean semAcquireDone = false;
         try {
-            semAcquireDone = mMANativeHelper.lock(ENGINE_ACCESS_MAX_TIMEOUT_MS);
+            semAcquireDone = lock(ENGINE_ACCESS_MAX_TIMEOUT_MS);
             if (semAcquireDone == false) {
                 throw new IllegalStateException("Timeout waiting for semaphore");
             }
 
+            if (mMANativeHelper == null) {
+                throw new IllegalStateException("The video editor is not initialized");
+            }
+
             if (mMediaItems.size() > 0) {
                 final Rect frame = surfaceHolder.getSurfaceFrame();
                 result = mMANativeHelper.renderPreviewFrame(surface,
@@ -871,7 +904,7 @@
             throw new IllegalStateException("The thread was interrupted");
         } finally {
             if (semAcquireDone) {
-                mMANativeHelper.unlock();
+                unlock();
             }
         }
         return result;
@@ -1568,11 +1601,15 @@
         boolean semAcquireDone = false;
         if (!mPreviewInProgress) {
             try{
-                semAcquireDone = mMANativeHelper.lock(ENGINE_ACCESS_MAX_TIMEOUT_MS);
+                semAcquireDone = lock(ENGINE_ACCESS_MAX_TIMEOUT_MS);
                 if (semAcquireDone == false) {
                     throw new IllegalStateException("Timeout waiting for semaphore");
                 }
 
+                if (mMANativeHelper == null) {
+                    throw new IllegalStateException("The video editor is not initialized");
+                }
+
                 if (mMediaItems.size() > 0) {
                     mPreviewInProgress = true;
                     mMANativeHelper.previewStoryBoard(mMediaItems, mTransitions,
@@ -1581,7 +1618,7 @@
                                      callbackAfterFrameCount, listener);
                 }
                 /**
-                 *  release on complete by calling stopPreview
+                 *  Release The lock on complete by calling stopPreview
                  */
             } catch (InterruptedException ex) {
                 Log.w(TAG, "The thread was interrupted", new Throwable());
@@ -1605,7 +1642,7 @@
                  */
                 } finally {
                     mPreviewInProgress = false;
-                    mMANativeHelper.unlock();
+                    unlock();
                 }
             return result;
         }
@@ -1791,4 +1828,50 @@
             Log.w(TAG, "Native helper was not ready!");
         }
     }
+
+    /**
+     * Grab the semaphore which arbitrates access to the editor
+     *
+     * @throws InterruptedException
+     */
+    private void lock() throws InterruptedException {
+        if (Log.isLoggable(TAG, Log.DEBUG)) {
+            Log.d(TAG, "lock: grabbing semaphore", new Throwable());
+        }
+        mLock.acquire();
+        if (Log.isLoggable(TAG, Log.DEBUG)) {
+            Log.d(TAG, "lock: grabbed semaphore");
+        }
+    }
+
+    /**
+     * Tries to grab the semaphore with a specified time out which arbitrates access to the editor
+     *
+     * @param timeoutMs time out in ms.
+     *
+     * @return true if the semaphore is acquired, false otherwise
+     * @throws InterruptedException
+     */
+    private boolean lock(long timeoutMs) throws InterruptedException {
+        if (Log.isLoggable(TAG, Log.DEBUG)) {
+            Log.d(TAG, "lock: grabbing semaphore with timeout " + timeoutMs, new Throwable());
+        }
+
+        boolean acquireSem = mLock.tryAcquire(timeoutMs, TimeUnit.MILLISECONDS);
+        if (Log.isLoggable(TAG, Log.DEBUG)) {
+            Log.d(TAG, "lock: grabbed semaphore status " + acquireSem);
+        }
+
+        return acquireSem;
+    }
+
+    /**
+     * Release the semaphore which arbitrates access to the editor
+     */
+    private void unlock() {
+        if (Log.isLoggable(TAG, Log.DEBUG)) {
+            Log.d(TAG, "unlock: releasing semaphore");
+        }
+        mLock.release();
+    }
 }
diff --git a/media/java/android/mtp/MtpPropertyGroup.java b/media/java/android/mtp/MtpPropertyGroup.java
index 57e2304..2e80fe8 100644
--- a/media/java/android/mtp/MtpPropertyGroup.java
+++ b/media/java/android/mtp/MtpPropertyGroup.java
@@ -60,11 +60,10 @@
     private String[]             mColumns;
 
     private static final String ID_WHERE = Files.FileColumns._ID + "=?";
-    private static final String ID_FORMAT_WHERE = ID_WHERE + " AND "
-                                            + Files.FileColumns.FORMAT + "=?";
+    private static final String FORMAT_WHERE = Files.FileColumns.FORMAT + "=?";
+    private static final String ID_FORMAT_WHERE = ID_WHERE + " AND " + FORMAT_WHERE;
     private static final String PARENT_WHERE = Files.FileColumns.PARENT + "=?";
-    private static final String PARENT_FORMAT_WHERE = PARENT_WHERE + " AND "
-                                            + Files.FileColumns.FORMAT + "=?";
+    private static final String PARENT_FORMAT_WHERE = PARENT_WHERE + " AND " + FORMAT_WHERE;
     // constructs a property group for a list of properties
     public MtpPropertyGroup(MtpDatabase database, IContentProvider provider, String volume,
             int[] properties) {
@@ -292,25 +291,37 @@
         String where;
         String[] whereArgs;
         if (format == 0) {
-            whereArgs = new String[] { Integer.toString(handle) };
-            if (depth == 1) {
-                where = PARENT_WHERE;
+            if (handle == 0xFFFFFFFF) {
+                // select all objects
+                where = null;
+                whereArgs = null;
             } else {
-                where = ID_WHERE;
+                whereArgs = new String[] { Integer.toString(handle) };
+                if (depth == 1) {
+                    where = PARENT_WHERE;
+                } else {
+                    where = ID_WHERE;
+                }
             }
         } else {
-            whereArgs = new String[] { Integer.toString(handle), Integer.toString(format) };
-            if (depth == 1) {
-                where = PARENT_FORMAT_WHERE;
+            if (handle == 0xFFFFFFFF) {
+                // select all objects with given format
+                where = FORMAT_WHERE;
+                whereArgs = new String[] { Integer.toString(format) };
             } else {
-                where = ID_FORMAT_WHERE;
+                whereArgs = new String[] { Integer.toString(handle), Integer.toString(format) };
+                if (depth == 1) {
+                    where = PARENT_FORMAT_WHERE;
+                } else {
+                    where = ID_FORMAT_WHERE;
+                }
             }
         }
 
         Cursor c = null;
         try {
             // don't query if not necessary
-            if (depth > 0 || mColumns.length > 1) {
+            if (depth > 0 || handle == 0xFFFFFFFF || mColumns.length > 1) {
                 c = mProvider.query(mUri, mColumns, where, whereArgs, null);
                 if (c == null) {
                     return new MtpPropertyList(0, MtpConstants.RESPONSE_INVALID_OBJECT_HANDLE);
@@ -318,6 +329,7 @@
             }
 
             int count = (c == null ? 1 : c.getCount());
+            Log.d(TAG, "count: " + count);
             MtpPropertyList result = new MtpPropertyList(count * mProperties.length,
                     MtpConstants.RESPONSE_OK);
 
@@ -326,9 +338,7 @@
                 if (c != null) {
                     c.moveToNext();
                 }
-                if (depth == 1) {
-                    handle = (int)c.getLong(0);
-                }
+                handle = (int)c.getLong(0);
 
                 // iterate over all properties in the query for the given object
                 for (int propertyIndex = 0; propertyIndex < mProperties.length; propertyIndex++) {
diff --git a/media/jni/mediaeditor/VideoBrowserMain.c b/media/jni/mediaeditor/VideoBrowserMain.c
index f54a16e..bb13fba 100755
--- a/media/jni/mediaeditor/VideoBrowserMain.c
+++ b/media/jni/mediaeditor/VideoBrowserMain.c
@@ -246,9 +246,13 @@
                     pContext->m_pCodecLoaderContext = M4OSA_NULL;
                     decoderType = M4DECODER_kVideoTypeMPEG4;
 
-                    err = VideoEditorVideoDecoder_getInterface_MPEG4(
-                        &decoderType, &pContext->m_pDecoder);
-
+#ifdef USE_SOFTWARE_DECODER
+                        err = VideoEditorVideoDecoder_getSoftwareInterface_MPEG4(
+                            &decoderType, &pContext->m_pDecoder);
+#else
+                        err = VideoEditorVideoDecoder_getInterface_MPEG4(
+                            &decoderType, &pContext->m_pDecoder);
+#endif
                     CHECK_ERR(videoBrowserCreate, err) ;
 
                     err = pContext->m_pDecoder->m_pFctCreate(
@@ -267,8 +271,14 @@
                     pContext->m_pCodecLoaderContext = M4OSA_NULL;
 
                     decoderType = M4DECODER_kVideoTypeAVC;
-                    err = VideoEditorVideoDecoder_getInterface_H264(
-                        &decoderType, &pContext->m_pDecoder);
+
+#ifdef USE_SOFTWARE_DECODER
+                        err = VideoEditorVideoDecoder_getSoftwareInterface_H264(
+                            &decoderType, &pContext->m_pDecoder);
+#else
+                        err = VideoEditorVideoDecoder_getInterface_H264(
+                            &decoderType, &pContext->m_pDecoder);
+#endif
                    CHECK_ERR(videoBrowserCreate, err) ;
 
                     err = pContext->m_pDecoder->m_pFctCreate(
diff --git a/media/jni/mediaeditor/VideoEditorPropertiesMain.cpp b/media/jni/mediaeditor/VideoEditorPropertiesMain.cpp
index 35c14b6..014cd95 100755
--- a/media/jni/mediaeditor/VideoEditorPropertiesMain.cpp
+++ b/media/jni/mediaeditor/VideoEditorPropertiesMain.cpp
@@ -195,13 +195,31 @@
                         &gotten, pEnv,(M4NO_ERROR != result),
                         "Invalid File or File not found");
 
-                if (pClipProperties->uiVideoWidth >= 1920)
+                /**
+                 * Max resolution supported is 1280 x 720.
+                 */
+                if ( (pClipProperties->uiVideoWidth > 1280)
+                    || (pClipProperties->uiVideoHeight > 720) )
                 {
-                    result = M4MCS_ERR_INPUT_FILE_CONTAINS_NO_SUPPORTED_STREAM;
+                    result = M4MCS_ERR_INVALID_INPUT_VIDEO_FRAME_SIZE;
                     videoEditJava_checkAndThrowIllegalArgumentException(
                             &gotten, pEnv, (M4NO_ERROR != result),
-                            "HD Content (1080p) is not supported");
+                            "Unsupported input video frame size");
                 }
+
+#ifdef USE_SOFTWARE_DECODER
+                /**
+                 * Input clip with non-multiples of 16 is not supported.
+                 */
+                if ( (pClipProperties->uiVideoWidth %16)
+                    || (pClipProperties->uiVideoHeight %16) )
+                {
+                    result = M4MCS_ERR_INPUT_VIDEO_SIZE_NON_X16;
+                    videoEditJava_checkAndThrowIllegalArgumentException(
+                            &gotten, pEnv, (M4NO_ERROR != result),
+                            "non x16 input video frame size is not supported");
+                }
+#endif /* USE_SOFTWARE_DECODER */
             }
 
             // Check if the properties could be retrieved.
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
index a777558..5a43c6a 100644
--- a/media/libstagefright/AwesomePlayer.cpp
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -765,6 +765,8 @@
 }
 
 status_t AwesomePlayer::play_l() {
+    mFlags &= ~SEEK_PREVIEW;
+
     if (mFlags & PLAYING) {
         return OK;
     }
@@ -1078,6 +1080,11 @@
 
         notifyListener_l(MEDIA_SEEK_COMPLETE);
         mSeekNotificationSent = true;
+
+        if ((mFlags & PREPARED) && mVideoSource != NULL) {
+            mFlags |= SEEK_PREVIEW;
+            postVideoEvent_l();
+        }
     }
 
     return OK;
@@ -1180,7 +1187,7 @@
 }
 
 void AwesomePlayer::finishSeekIfNecessary(int64_t videoTimeUs) {
-    if (!mSeeking) {
+    if (!mSeeking || (mFlags & SEEK_PREVIEW)) {
         return;
     }
 
@@ -1227,7 +1234,8 @@
             mVideoBuffer = NULL;
         }
 
-        if (mCachedSource != NULL && mAudioSource != NULL) {
+        if (mCachedSource != NULL && mAudioSource != NULL
+                && !(mFlags & SEEK_PREVIEW)) {
             // We're going to seek the video source first, followed by
             // the audio source.
             // In order to avoid jumps in the DataSource offset caused by
@@ -1321,43 +1329,38 @@
         mTimeSourceDeltaUs = realTimeUs - mediaTimeUs;
     }
 
-    int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs;
-
-    int64_t latenessUs = nowUs - timeUs;
-
-    if (wasSeeking) {
+    if (!wasSeeking && mRTPSession == NULL) {
         // Let's display the first frame after seeking right away.
-        latenessUs = 0;
-    }
-
-    if (mRTPSession != NULL) {
         // We'll completely ignore timestamps for gtalk videochat
         // and we'll play incoming video as fast as we get it.
-        latenessUs = 0;
-    }
 
-    if (latenessUs > 40000) {
-        // We're more than 40ms late.
-        LOGV("we're late by %lld us (%.2f secs)", latenessUs, latenessUs / 1E6);
-        if ( mSinceLastDropped > FRAME_DROP_FREQ)
-        {
-            LOGV("we're late by %lld us (%.2f secs) dropping one after %d frames", latenessUs, latenessUs / 1E6, mSinceLastDropped);
-            mSinceLastDropped = 0;
-            mVideoBuffer->release();
-            mVideoBuffer = NULL;
+        int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs;
 
-            postVideoEvent_l();
+        int64_t latenessUs = nowUs - timeUs;
+
+        if (latenessUs > 40000) {
+            // We're more than 40ms late.
+            LOGV("we're late by %lld us (%.2f secs)", latenessUs, latenessUs / 1E6);
+            if ( mSinceLastDropped > FRAME_DROP_FREQ)
+            {
+                LOGV("we're late by %lld us (%.2f secs) dropping one after %d frames", latenessUs, latenessUs / 1E6, mSinceLastDropped);
+                mSinceLastDropped = 0;
+                mVideoBuffer->release();
+                mVideoBuffer = NULL;
+
+                postVideoEvent_l();
+                return;
+            }
+        }
+
+        if (latenessUs < -10000) {
+            // We're more than 10ms early.
+
+            postVideoEvent_l(10000);
             return;
         }
     }
 
-    if (latenessUs < -10000) {
-        // We're more than 10ms early.
-
-        postVideoEvent_l(10000);
-        return;
-    }
-
     if (mVideoRendererIsPreview || mVideoRenderer == NULL) {
         mVideoRendererIsPreview = false;
 
@@ -1372,6 +1375,11 @@
     mVideoBuffer->release();
     mVideoBuffer = NULL;
 
+    if (wasSeeking && (mFlags & SEEK_PREVIEW)) {
+        mFlags &= ~SEEK_PREVIEW;
+        return;
+    }
+
     postVideoEvent_l();
 }
 
diff --git a/media/libstagefright/include/AwesomePlayer.h b/media/libstagefright/include/AwesomePlayer.h
index 41ef181..3021359 100644
--- a/media/libstagefright/include/AwesomePlayer.h
+++ b/media/libstagefright/include/AwesomePlayer.h
@@ -119,6 +119,10 @@
         // sufficient data to begin playback and finish the preparation phase
         // for good.
         PREPARING_CONNECTED = 2048,
+
+        // We're triggering a single video event to display the first frame
+        // after the seekpoint.
+        SEEK_PREVIEW        = 4096,
     };
 
     mutable Mutex mLock;
diff --git a/media/tests/MediaFrameworkTest/AndroidManifest.xml b/media/tests/MediaFrameworkTest/AndroidManifest.xml
index 2253eb2..c9d2628b 100644
--- a/media/tests/MediaFrameworkTest/AndroidManifest.xml
+++ b/media/tests/MediaFrameworkTest/AndroidManifest.xml
@@ -58,4 +58,9 @@
          android:label="Media Power tests InstrumentationRunner">
      </instrumentation>
 
+     <instrumentation android:name=".MediaPlayerStressTestRunner"
+         android:targetPackage="com.android.mediaframeworktest"
+         android:label="Media Power tests InstrumentationRunner">
+     </instrumentation>
+
 </manifest>
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaPlayerStressTestRunner.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaPlayerStressTestRunner.java
new file mode 100755
index 0000000..5438061
--- /dev/null
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaPlayerStressTestRunner.java
@@ -0,0 +1,38 @@
+/*
+ * 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.mediaframeworktest;
+
+import android.test.InstrumentationTestRunner;
+import android.test.InstrumentationTestSuite;
+import com.android.mediaframeworktest.stress.MediaPlayerStressTest;
+
+import junit.framework.TestSuite;
+
+public class MediaPlayerStressTestRunner extends InstrumentationTestRunner {
+
+    @Override
+    public TestSuite getAllTests() {
+        TestSuite suite = new InstrumentationTestSuite(this);
+        suite.addTestSuite(MediaPlayerStressTest.class);
+        return suite;
+    }
+
+    @Override
+    public ClassLoader getLoader() {
+        return MediaPlayerStressTestRunner.class.getClassLoader();
+    }
+}
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java
index 3e46e27..0b0d0ce 100755
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaRecorderStressTestRunner.java
@@ -21,7 +21,6 @@
 import android.test.InstrumentationTestRunner;
 import android.test.InstrumentationTestSuite;
 import com.android.mediaframeworktest.stress.MediaRecorderStressTest;
-import com.android.mediaframeworktest.stress.MediaPlayerStressTest;
 
 import junit.framework.TestSuite;
 
@@ -42,7 +41,6 @@
     public TestSuite getAllTests() {
         TestSuite suite = new InstrumentationTestSuite(this);
         suite.addTestSuite(MediaRecorderStressTest.class);
-        suite.addTestSuite(MediaPlayerStressTest.class);
         return suite;
     }
 
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CodecTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CodecTest.java
index 2eea206..cad7e53 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CodecTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/CodecTest.java
@@ -45,7 +45,7 @@
  
  */  
 public class CodecTest {    
-    private static String TAG = "MediaPlayerApiTest";
+    private static String TAG = "CodecTest";
     private static MediaPlayer mMediaPlayer;
     private MediaPlayer.OnPreparedListener mOnPreparedListener;
     
@@ -58,7 +58,13 @@
     private static final Object videoSizeChanged = new Object();
     private static final Object onCompletion = new Object();
     private static boolean onPrepareSuccess = false;
-    private static boolean onCompleteSuccess = false;
+    public static boolean onCompleteSuccess = false;
+    public static boolean mPlaybackError = false;
+    public static boolean mIsMediaInfoUnknown = false;
+    public static boolean mIsMediaInfoVideoTrackLagging = false;
+    public static boolean mIsMediaInfoBadInterleaving = false;
+    public static boolean mIsMediaInfoNotSeekable = false;
+    public static boolean mIsMediaInfoMetdataUpdate = false;
 
     public static String printCpuInfo(){      
         String cm = "dumpsys cpuinfo";
@@ -747,13 +753,52 @@
         }
     };
 
+    static MediaPlayer.OnErrorListener mOnErrorListener = new MediaPlayer.OnErrorListener() {
+        public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
+            mPlaybackError = true;
+            mp.reset();
+            return true;
+        }
+    };
+
+    static MediaPlayer.OnInfoListener mInfoListener = new MediaPlayer.OnInfoListener() {
+        public boolean onInfo(MediaPlayer mp, int what, int extra) {
+            switch (what){
+                case MediaPlayer.MEDIA_INFO_UNKNOWN:
+                    mIsMediaInfoUnknown = true;
+                    break;
+                case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
+                    mIsMediaInfoVideoTrackLagging = true;
+                    break;
+                case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
+                    mIsMediaInfoBadInterleaving = true;
+                    break;
+                case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
+                    mIsMediaInfoNotSeekable = true;
+                    break;
+                case MediaPlayer.MEDIA_INFO_METADATA_UPDATE:
+                    mIsMediaInfoMetdataUpdate = true;
+                    break;
+            }
+            return true;
+        }
+    };
+
     // For each media file, forward twice and backward once, then play to the end
     public static boolean playMediaSamples(String filePath) throws Exception {
         int duration = 0;
         int curPosition = 0;
         int nextPosition = 0;
         int waittime = 0;
-        Random r = new Random();
+        onCompleteSuccess = false;
+        mIsMediaInfoUnknown = false;
+        mIsMediaInfoVideoTrackLagging = false;
+        mIsMediaInfoBadInterleaving = false;
+        mIsMediaInfoNotSeekable = false;
+        mIsMediaInfoMetdataUpdate = false;
+        mPlaybackError = false;
+        String testResult;
+
         initializeMessageLooper();
         synchronized (lock) {
             try {
@@ -765,37 +810,18 @@
         }
         try {
             mMediaPlayer.setOnCompletionListener(mCompletionListener);
+            mMediaPlayer.setOnErrorListener(mOnErrorListener);
             Log.v(TAG, "playMediaSamples: sample file name " + filePath);
             mMediaPlayer.setDataSource(filePath);
             mMediaPlayer.setDisplay(MediaFrameworkTest.mSurfaceView.getHolder());
             mMediaPlayer.prepare();
             duration = mMediaPlayer.getDuration();
-            Log.v(TAG, "playMediaSamples: duration = " + duration);
             // start to play
             mMediaPlayer.start();
-            // randomly play for time within (0, duration/3)
-            Thread.sleep(r.nextInt(duration/3));
-            mMediaPlayer.pause();
-            Log.v(TAG, "playMediaSamples: current position after pause: "
-                        + mMediaPlayer.getCurrentPosition());
-            // seek to position (0, 2/3*duration)
-            nextPosition = mMediaPlayer.getCurrentPosition() + r.nextInt(duration/3);
-            mMediaPlayer.seekTo(nextPosition);
-            Log.v(TAG, "playMediaSamples: current position after the first seek:"
-                        + mMediaPlayer.getCurrentPosition());
-            // play for another short time
-            mMediaPlayer.start();
-            Thread.sleep(r.nextInt(duration/6));
-            Log.v(TAG, "playMediaSamples: position after the second play:"
-                        + mMediaPlayer.getCurrentPosition());
-            // seek to a random position (0, duration)
-            mMediaPlayer.seekTo(r.nextInt(duration));
-            Log.v(TAG, "playMediaSamples: current position after the second seek:"
-                        + mMediaPlayer.getCurrentPosition());
             waittime = duration - mMediaPlayer.getCurrentPosition();
             synchronized(onCompletion){
                 try {
-                    onCompletion.wait(waittime + 30000);
+                    onCompletion.wait(waittime + 2000);
                 }catch (Exception e) {
                     Log.v(TAG, "playMediaSamples are interrupted");
                     return false;
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaPlayerApiTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaPlayerApiTest.java
index 64ffa4e..d22025c 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaPlayerApiTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaPlayerApiTest.java
@@ -483,29 +483,4 @@
             CodecTest.prepareAsyncCallback(MediaNames.STREAM_H264_480_360_1411k, true);
         assertTrue("StreamH264PrepareAsyncCallback", onPrepareSuccess);
     }
-
-    //Provide a tool to play all kinds of media files in a directory
-    @Suppress
-    @LargeTest
-    public void testMediaSamples() throws Exception {
-        // load directory files
-        boolean onCompleteSuccess = false;
-        File dir = new File(MediaNames.MEDIA_SAMPLE_POOL);
-        String[] children = dir.list();
-        if (children == null) {
-            Log.v("MediaPlayerApiTest:testMediaSamples", "dir is empty");
-            return;
-        } else {
-            for (int i = 0; i < children.length; i++) {
-                //Get filename of directory
-                String filename = children[i];
-                Log.v("MediaPlayerApiTest",
-                    "testMediaSamples: file to be played: "
-                    + dir + "/" + filename);
-                onCompleteSuccess =
-                    CodecTest.playMediaSamples(dir + "/" + filename);
-                assertTrue("testMediaSamples", onCompleteSuccess);
-            }
-       }
-    }
 }
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/stress/MediaPlayerStressTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/stress/MediaPlayerStressTest.java
index 95b7386..b694d16 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/stress/MediaPlayerStressTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/stress/MediaPlayerStressTest.java
@@ -18,6 +18,9 @@
 
 import com.android.mediaframeworktest.MediaFrameworkTest;
 
+import android.app.Activity;
+import android.app.Instrumentation;
+import android.content.Intent;
 import android.hardware.Camera;
 import android.media.MediaPlayer;
 import android.media.MediaRecorder;
@@ -27,121 +30,132 @@
 import android.view.SurfaceHolder;
 
 import com.android.mediaframeworktest.MediaNames;
+import com.android.mediaframeworktest.functional.CodecTest;
 
-import java.util.Random;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.Writer;
+
+import android.test.AndroidTestCase;
+import android.test.InstrumentationTestCase;
 
 /**
  * Junit / Instrumentation test case for the media player
  */
-public class MediaPlayerStressTest extends ActivityInstrumentationTestCase2<MediaFrameworkTest> {    
+public class MediaPlayerStressTest extends InstrumentationTestCase {
     private String TAG = "MediaPlayerStressTest";
-    private MediaRecorder mRecorder;
-    private Camera mCamera;
-
-    private static final int NUMBER_OF_RANDOM_REPOSITION_AND_PLAY = 10;
-    private static final int NUMBER_OF_RANDOM_REPOSITION_AND_PLAY_SHORT = 5;
-    private static final int NUMBER_OF_STRESS_LOOPS = 500;
-    private static final int PLAYBACK_END_TOLERANCE = 30000;
-    private static final int WAIT_UNTIL_PLAYBACK_FINISH = 515000 ;
 
     public MediaPlayerStressTest() {
-        super("com.android.mediaframeworktest", MediaFrameworkTest.class);
     }
 
     protected void setUp() throws Exception {
-        getActivity();
         super.setUp();
     }
 
-    @LargeTest
-    public void testStressHWDecoderRelease() throws Exception {
-        SurfaceHolder mSurfaceHolder;
-        long randomseed = System.currentTimeMillis(); 
-        Random generator = new Random(randomseed);
-        Log.v(TAG, "Random seed: " + randomseed);
-        int video_duration = MediaNames.STREAM_H264_480_360_1411k_DURATION;
-        int random_play_time;
+    private int mTotalPlaybackError = 0;
+    private int mTotalComplete = 0;
+    private int mTotalInfoUnknown = 0;
+    private int mTotalVideoTrackLagging = 0;
+    private int mTotalBadInterleaving = 0;
+    private int mTotalNotSeekable = 0;
+    private int mTotalMetaDataUpdate = 0;
 
-        mSurfaceHolder = MediaFrameworkTest.mSurfaceView.getHolder();
-        try {
-            //assertTrue(MediaFrameworkTest.checkStreamingServer());
-            for (int i = 0; i < NUMBER_OF_STRESS_LOOPS; i++) {
-                MediaPlayer mp = new MediaPlayer();
-                mp.setDataSource(MediaNames.STREAM_H264_480_360_1411k);
-                mp.setDisplay(MediaFrameworkTest.mSurfaceView.getHolder());
-                mp.prepare();
-                mp.start();
-                // seek and play
-                for (int j = 0; j < generator.nextInt(10); j++) {
-                    random_play_time =
-                        generator.nextInt(MediaNames.STREAM_H264_480_360_1411k_DURATION / 2);
-                    Log.v(TAG, "Play time = " + random_play_time);
-                    Thread.sleep(random_play_time);
-                    int seek_time = MediaNames.STREAM_H264_480_360_1411k_DURATION / 2;
-                    Log.v(TAG, "Seek time = " + seek_time);
-                    mp.seekTo(seek_time);
-                }
-                mp.release();
-            }
+    private void writeTestOutput(String filename, Writer output) throws Exception{
+        output.write("File Name: " + filename);
+        output.write(" Complete: " + CodecTest.onCompleteSuccess);
+        output.write(" Error: " + CodecTest.mPlaybackError);
+        output.write(" Unknown Info: " + CodecTest.mIsMediaInfoUnknown);
+        output.write(" Track Lagging: " +  CodecTest.mIsMediaInfoVideoTrackLagging);
+        output.write(" BadInterleaving: " + CodecTest.mIsMediaInfoBadInterleaving);
+        output.write(" Not Seekable: " + CodecTest.mIsMediaInfoNotSeekable);
+        output.write(" Info Meta data update: " + CodecTest.mIsMediaInfoMetdataUpdate);
+        output.write("\n");
+    }
 
-        } catch (Exception e) {
-            Log.v(TAG, e.toString());
-            assertTrue("testStressHWDecoderRelease", false);
+    private void writeTestSummary(Writer output) throws Exception{
+        output.write("Total Result:\n");
+        output.write(" Complete: " + mTotalComplete);
+        output.write(" Error: " + mTotalPlaybackError);
+        output.write(" Unknown Info: " + mTotalInfoUnknown);
+        output.write(" Track Lagging: " + mTotalVideoTrackLagging );
+        output.write(" BadInterleaving: " + mTotalBadInterleaving);
+        output.write(" Not Seekable: " + mTotalNotSeekable);
+        output.write(" Info Meta data update: " + mTotalMetaDataUpdate);
+        output.write("\n");
+    }
+
+    private void updateTestResult(){
+        if (CodecTest.onCompleteSuccess){
+            mTotalComplete++;
+        }
+        else if (CodecTest.mPlaybackError){
+            mTotalPlaybackError++;
+        }
+        else if (CodecTest.mIsMediaInfoUnknown){
+            mTotalInfoUnknown++;
+        }
+        else if (CodecTest.mIsMediaInfoVideoTrackLagging){
+            mTotalVideoTrackLagging++;
+        }
+        else if (CodecTest.mIsMediaInfoBadInterleaving){
+            mTotalBadInterleaving++;
+        }
+        else if (CodecTest.mIsMediaInfoNotSeekable){
+            mTotalNotSeekable++;
+        }
+        else if (CodecTest.mIsMediaInfoMetdataUpdate){
+            mTotalMetaDataUpdate++;
         }
     }
 
+    //Test that will start the playback for all the videos
+    //under the samples folder
     @LargeTest
-    public void testStressGetCurrentPosition() throws Exception {
-        SurfaceHolder mSurfaceHolder;
-        long randomseed = System.currentTimeMillis(); 
-        Random generator = new Random(randomseed);
-        Log.v(TAG, "Random seed: " + randomseed);
-        int video_duration = MediaNames.VIDEO_H263_AMR_DURATION;
-        int random_play_time = 0;
-        int random_seek_time = 0;
-        int random_no_of_seek = 0;
+    public void testVideoPlayback() throws Exception {
+        String fileWithError = "Filename:\n";
+        File playbackOutput = new File("/sdcard/PlaybackTestResult.txt");
+        Writer output = new BufferedWriter(new FileWriter(playbackOutput, true));
 
-        mSurfaceHolder = MediaFrameworkTest.mSurfaceView.getHolder();
-        try {
-            for (int i = 0; i < NUMBER_OF_STRESS_LOOPS; i++) {
-                MediaPlayer mp = new MediaPlayer();
-                mp.setDataSource(MediaNames.VIDEO_H263_AMR);
-                mp.setDisplay(MediaFrameworkTest.mSurfaceView.getHolder());
-                mp.prepare();
-                mp.start();
-                random_no_of_seek = generator.nextInt(10);
-                // make sure the seek at least run once.
-                if (random_no_of_seek == 0) {
-                    random_no_of_seek = 1;
+        boolean testResult = true;
+        // load directory files
+        boolean onCompleteSuccess = false;
+        File dir = new File(MediaNames.MEDIA_SAMPLE_POOL);
+
+        Instrumentation inst = getInstrumentation();
+        Intent intent = new Intent();
+
+        intent.setClass(getInstrumentation().getTargetContext(), MediaFrameworkTest.class);
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+        String[] children = dir.list();
+        if (children == null) {
+            Log.v("MediaPlayerApiTest:testMediaSamples", "dir is empty");
+            return;
+        } else {
+            for (int i = 0; i < children.length; i++) {
+                Activity act = inst.startActivitySync(intent);
+                //Get filename of directory
+                String filename = children[i];
+                onCompleteSuccess =
+                    CodecTest.playMediaSamples(dir + "/" + filename);
+                if (!onCompleteSuccess){
+                    //Don't fail the test right away, print out the failure file.
+                    fileWithError += filename + '\n';
+                    Log.v(TAG, "Failure File : " + fileWithError);
+                    testResult = false;
                 }
-                Log.v(TAG, "random_seek = " + random_no_of_seek);
-                // Play for 10 seconds then random seekTo
-                for (int j = 0; j < random_no_of_seek; j++) {
-                    random_play_time =
-                        generator.nextInt(video_duration / 100);
-                    Log.v(TAG, "Play time = " + random_play_time);
-                    Thread.sleep(random_play_time);
-                    random_seek_time =
-                        generator.nextInt(video_duration / 2);
-                    Log.v(TAG, "Seek time = " + random_seek_time);
-                    mp.seekTo(random_seek_time);
-                }
-                //Seek to 10s from the end of the video
-                mp.seekTo(video_duration - 10000);
-                //After reposition, play 30 seconds the video should be finished.
-                Thread.sleep(PLAYBACK_END_TOLERANCE);
-                Log.v(TAG, "CurrentPosition = " + mp.getCurrentPosition());
-                if ( mp.isPlaying() || mp.getCurrentPosition()
-                        > (video_duration)){
-                    assertTrue("Current PlayTime greater than duration", false);
-                }
-                mp.release();
+                Thread.sleep(3000);
+                //Call onCreat to recreate the surface
+                act.finish();
+                //Write test result to an output file
+                writeTestOutput(filename,output);
+                //Get the summary
+                updateTestResult();
             }
-
-        } catch (Exception e) {
-            Log.v(TAG, e.toString());
-            assertTrue("testStressGetCurrentPosition", false);
-        }
+            writeTestSummary(output);
+            output.close();
+            assertTrue("testMediaSamples", testResult);
+       }
     }
-}
-
+}
\ No newline at end of file
diff --git a/opengl/java/android/opengl/GLUtils.java b/opengl/java/android/opengl/GLUtils.java
index 2f17072..f30a4cd4 100644
--- a/opengl/java/android/opengl/GLUtils.java
+++ b/opengl/java/android/opengl/GLUtils.java
@@ -47,6 +47,9 @@
         if (bitmap == null) {
             throw new NullPointerException("getInternalFormat can't be used with a null Bitmap");
         }
+        if (bitmap.isRecycled()) {
+            throw new IllegalArgumentException("bitmap is recycled");
+        }
         int result = native_getInternalFormat(bitmap);
         if (result < 0) {
             throw new IllegalArgumentException("Unknown internalformat");
@@ -66,6 +69,9 @@
         if (bitmap == null) {
             throw new NullPointerException("getType can't be used with a null Bitmap");
         }
+        if (bitmap.isRecycled()) {
+            throw new IllegalArgumentException("bitmap is recycled");
+        }
         int result = native_getType(bitmap);
         if (result < 0) {
             throw new IllegalArgumentException("Unknown type");
@@ -100,6 +106,9 @@
         if (bitmap == null) {
             throw new NullPointerException("texImage2D can't be used with a null Bitmap");
         }
+        if (bitmap.isRecycled()) {
+            throw new IllegalArgumentException("bitmap is recycled");
+        }
         if (native_texImage2D(target, level, internalformat, bitmap, -1, border)!=0) {
             throw new IllegalArgumentException("invalid Bitmap format");
         }
@@ -123,6 +132,9 @@
         if (bitmap == null) {
             throw new NullPointerException("texImage2D can't be used with a null Bitmap");
         }
+        if (bitmap.isRecycled()) {
+            throw new IllegalArgumentException("bitmap is recycled");
+        }
         if (native_texImage2D(target, level, internalformat, bitmap, type, border)!=0) {
             throw new IllegalArgumentException("invalid Bitmap format");
         }
@@ -177,6 +189,9 @@
         if (bitmap == null) {
             throw new NullPointerException("texSubImage2D can't be used with a null Bitmap");
         }
+        if (bitmap.isRecycled()) {
+            throw new IllegalArgumentException("bitmap is recycled");
+        }
         int type = getType(bitmap);
         if (native_texSubImage2D(target, level, xoffset, yoffset, bitmap, -1, type)!=0) {
             throw new IllegalArgumentException("invalid Bitmap format");
@@ -199,6 +214,9 @@
         if (bitmap == null) {
             throw new NullPointerException("texSubImage2D can't be used with a null Bitmap");
         }
+        if (bitmap.isRecycled()) {
+            throw new IllegalArgumentException("bitmap is recycled");
+        }
         if (native_texSubImage2D(target, level, xoffset, yoffset, bitmap, format, type)!=0) {
             throw new IllegalArgumentException("invalid Bitmap format");
         }
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_bluetooth.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_bluetooth.png
index fe9be2c..c9704fc 100644
--- a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_bluetooth.png
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_bluetooth.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_bluetooth_connected.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_bluetooth_connected.png
index f9b3966..b37dd9f 100644
--- a/packages/SystemUI/res/drawable-hdpi/stat_sys_data_bluetooth_connected.png
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_data_bluetooth_connected.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_bluetooth.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_bluetooth.png
index 45a97fd..f615835 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_bluetooth.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_bluetooth.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_bluetooth_connected.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_bluetooth_connected.png
index 306afd0..f784e7e 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_data_bluetooth_connected.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_data_bluetooth_connected.png
Binary files differ
diff --git a/packages/SystemUI/res/layout-xlarge/status_bar_notification_area.xml b/packages/SystemUI/res/layout-xlarge/status_bar_notification_area.xml
index a892cd9..6e3b0d7 100644
--- a/packages/SystemUI/res/layout-xlarge/status_bar_notification_area.xml
+++ b/packages/SystemUI/res/layout-xlarge/status_bar_notification_area.xml
@@ -75,7 +75,7 @@
             android:id="@+id/clock"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:layout_marginBottom="2dip"
+            android:layout_marginBottom="3dip"
             android:layout_marginLeft="4dip"
             android:layout_marginRight="4dip"
             >
diff --git a/packages/SystemUI/res/values-es-rUS-xlarge/strings.xml b/packages/SystemUI/res/values-es-rUS-xlarge/strings.xml
index f29259a..22c8002 100644
--- a/packages/SystemUI/res/values-es-rUS-xlarge/strings.xml
+++ b/packages/SystemUI/res/values-es-rUS-xlarge/strings.xml
@@ -13,4 +13,10 @@
     <string name="status_bar_settings_signal_meter_disconnected" msgid="4866302415753953027">"Sin conexión a Internet"</string>
     <!-- XL xlarge -->
     <string name="status_bar_settings_signal_meter_wifi_nossid" msgid="3832182580451976589">"Wi-Fi conectado"</string>
+
+    <!-- manually translated -->
+    <string name="gps_notification_searching_text">Buscando señal de GPS</string>
+
+    <!-- manually translated -->
+    <string name="gps_notification_found_text">Ubicación establecida por el GPS</string>
 </resources>
diff --git a/packages/SystemUI/res/values-xlarge/colors.xml b/packages/SystemUI/res/values-xlarge/colors.xml
index 1fd396d..a7a70c3 100644
--- a/packages/SystemUI/res/values-xlarge/colors.xml
+++ b/packages/SystemUI/res/values-xlarge/colors.xml
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
     <drawable name="status_bar_background">#000000</drawable>
-    <drawable name="notification_icon_area_smoke">#CC000000</drawable>
+    <drawable name="notification_icon_area_smoke">#aa000000</drawable>
 </resources>
 
diff --git a/packages/SystemUI/res/values-xlarge/strings.xml b/packages/SystemUI/res/values-xlarge/strings.xml
index f7b642d..dfd5851 100644
--- a/packages/SystemUI/res/values-xlarge/strings.xml
+++ b/packages/SystemUI/res/values-xlarge/strings.xml
@@ -38,4 +38,9 @@
     <!-- Separator for PLMN and SPN in network name. -->
     <string name="status_bar_network_name_separator" translatable="false">" – "</string>
 
+    <!-- Notification text: when GPS is getting a fix [CHAR LIMIT=50] -->
+    <string name="gps_notification_searching_text">Searching for GPS</string>
+
+    <!-- Notification text: when GPS has found a fix [CHAR LIMIT=50] -->
+    <string name="gps_notification_found_text">Location set by GPS</string>
 </resources>
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/LocationController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/LocationController.java
new file mode 100644
index 0000000..bb326fe
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/LocationController.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.policy;
+
+import java.util.ArrayList;
+
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.location.LocationManager;
+import android.provider.Settings;
+import android.util.Slog;
+import android.view.View;
+import android.widget.ImageView;
+
+// private NM API
+import android.app.INotificationManager;
+import com.android.internal.statusbar.StatusBarNotification;
+
+import com.android.systemui.R;
+
+public class LocationController extends BroadcastReceiver {
+    private static final String TAG = "StatusBar.LocationController";
+
+    private static final int GPS_NOTIFICATION_ID = 374203-122084;
+
+    private Context mContext;
+
+    private INotificationManager mNotificationService;
+
+    public LocationController(Context context) {
+        mContext = context;
+
+        IntentFilter filter = new IntentFilter();
+        filter.addAction(LocationManager.GPS_ENABLED_CHANGE_ACTION);
+        filter.addAction(LocationManager.GPS_FIX_CHANGE_ACTION);
+        context.registerReceiver(this, filter);
+
+        NotificationManager nm = (NotificationManager)context.getSystemService(
+                Context.NOTIFICATION_SERVICE);
+        mNotificationService = nm.getService();
+    }
+
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        final String action = intent.getAction();
+        final boolean enabled = intent.getBooleanExtra(LocationManager.EXTRA_GPS_ENABLED, false);
+
+        boolean visible;
+        int iconId, textResId;
+
+        if (action.equals(LocationManager.GPS_FIX_CHANGE_ACTION) && enabled) {
+            // GPS is getting fixes
+            iconId = com.android.internal.R.drawable.stat_sys_gps_on;
+            textResId = R.string.gps_notification_found_text;
+            visible = true;
+        } else if (action.equals(LocationManager.GPS_ENABLED_CHANGE_ACTION) && !enabled) {
+            // GPS is off
+            visible = false;
+            iconId = textResId = 0;
+        } else {
+            // GPS is on, but not receiving fixes
+            iconId = R.drawable.stat_sys_gps_acquiring_anim;
+            textResId = R.string.gps_notification_searching_text;
+            visible = true;
+        }
+        
+        try {
+            if (visible) {
+                Intent gpsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
+                gpsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, gpsIntent, 0);
+
+                Notification n = new Notification.Builder(mContext)
+                    .setSmallIcon(iconId)
+                    .setContentTitle(mContext.getText(textResId))
+                    .setOngoing(true)
+                    .setContentIntent(pendingIntent)
+                    .getNotification();
+
+                // Notification.Builder will helpfully fill these out for you no matter what you do
+                n.tickerView = null;
+                n.tickerText = null;
+
+                int[] idOut = new int[1];
+                mNotificationService.enqueueNotificationWithTagPriority(
+                        mContext.getPackageName(),
+                        null, 
+                        GPS_NOTIFICATION_ID, 
+                        StatusBarNotification.PRIORITY_SYSTEM, // !!!1!one!!!
+                        n,
+                        idOut);
+            } else {
+                mNotificationService.cancelNotification(
+                        mContext.getPackageName(),
+                        GPS_NOTIFICATION_ID);
+            }
+        } catch (android.os.RemoteException ex) {
+            // well, it was worth a shot
+        }
+    }
+}
+
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/PanelBackgroundView.java b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/PanelBackgroundView.java
index 5eafdc1..9ac933f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/PanelBackgroundView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/PanelBackgroundView.java
@@ -14,28 +14,25 @@
  * limitations under the License.
  */
 
-package com.android.systemui.statusbar.phone;
+package com.android.systemui.statusbar.tablet;
 
 import android.content.Context;
-import android.content.res.TypedArray;
-import android.util.AttributeSet;
-import android.util.Slog;
-import android.view.View;
-import android.graphics.BitmapFactory;
-import android.graphics.Bitmap;
-import android.graphics.Paint;
 import android.graphics.Canvas;
+import android.util.AttributeSet;
+import android.view.View;
 
 public class PanelBackgroundView extends View {
+    /*
     private Bitmap mTexture;
     private Paint mPaint;
     private int mTextureWidth;
     private int mTextureHeight;
-    
+    */
+
     public PanelBackgroundView(Context context, AttributeSet attrs) {
         super(context, attrs);
         /*
-        mTexture = BitmapFactory.decodeResource(getResources(), 
+        mTexture = BitmapFactory.decodeResource(getResources(),
                 com.android.internal.R.drawable.status_bar_background);
         mTextureWidth = mTexture.getWidth();
         mTextureHeight = mTexture.getHeight();
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 4bac07f..7a13fde 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
@@ -65,6 +65,7 @@
 import com.android.systemui.statusbar.*;
 import com.android.systemui.statusbar.policy.BatteryController;
 import com.android.systemui.statusbar.policy.BluetoothController;
+import com.android.systemui.statusbar.policy.LocationController;
 import com.android.systemui.statusbar.policy.NetworkController;
 import com.android.systemui.recent.RecentApplicationsActivity;
 
@@ -135,6 +136,7 @@
     HeightReceiver mHeightReceiver;
     BatteryController mBatteryController;
     BluetoothController mBluetoothController;
+    LocationController mLocationController;
     NetworkController mNetworkController;
 
     View mBarContents;
@@ -359,6 +361,8 @@
         mTicker = new TabletTicker(this);
 
         // The icons
+        mLocationController = new LocationController(mContext); // will post a notification
+
         mBatteryController = new BatteryController(mContext);
         mBatteryController.addIconView((ImageView)sb.findViewById(R.id.battery));
         mBluetoothController = new BluetoothController(mContext);
diff --git a/packages/SystemUI/src/com/android/systemui/usb/UsbStorageActivity.java b/packages/SystemUI/src/com/android/systemui/usb/UsbStorageActivity.java
index a834266..1368baa 100644
--- a/packages/SystemUI/src/com/android/systemui/usb/UsbStorageActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/usb/UsbStorageActivity.java
@@ -71,6 +71,7 @@
     private static final int DLG_CONFIRM_KILL_STORAGE_USERS = 1;
     private static final int DLG_ERROR_SHARING = 2;
     static final boolean localLOGV = false;
+    private boolean mDestroyed;
 
     // UI thread
     private Handler mUIHandler;
@@ -136,6 +137,12 @@
         mProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress);
     }
 
+    @Override
+    protected void onDestroy() {
+        super.onDestroy();
+        mDestroyed = true;
+    }
+
     private void switchDisplay(final boolean usbStorageInUse) {
         mUIHandler.post(new Runnable() {
             @Override
@@ -232,9 +239,16 @@
         return null;
     }
 
-    private void showDialogInner(int id) {
-        removeDialog(id);
-        showDialog(id);
+    private void scheduleShowDialog(final int id) {
+        mUIHandler.post(new Runnable() {
+            @Override
+            public void run() {
+                if (!mDestroyed) {
+                    removeDialog(id);
+                    showDialog(id);
+                }
+            }
+        });
     }
 
     private void switchUsbMassStorage(final boolean on) {
@@ -276,7 +290,7 @@
         IMountService ims = getMountService();
         if (ims == null) {
             // Display error dialog
-            showDialogInner(DLG_ERROR_SHARING);
+            scheduleShowDialog(DLG_ERROR_SHARING);
         }
         String extStoragePath = Environment.getExternalStorageDirectory().toString();
         boolean showDialog = false;
@@ -294,11 +308,11 @@
             }
         } catch (RemoteException e) {
             // Display error dialog
-            showDialogInner(DLG_ERROR_SHARING);
+            scheduleShowDialog(DLG_ERROR_SHARING);
         }
         if (showDialog) {
             // Display dialog to user
-            showDialogInner(DLG_CONFIRM_KILL_STORAGE_USERS);
+            scheduleShowDialog(DLG_CONFIRM_KILL_STORAGE_USERS);
         } else {
             if (localLOGV) Log.i(TAG, "Enabling UMS");
             switchUsbMassStorage(true);
diff --git a/services/audioflinger/AudioMixer.cpp b/services/audioflinger/AudioMixer.cpp
index 8aaa325..433f1f7 100644
--- a/services/audioflinger/AudioMixer.cpp
+++ b/services/audioflinger/AudioMixer.cpp
@@ -975,7 +975,6 @@
 {
     int32_t* const outTemp = state->outputTemp;
     const size_t size = sizeof(int32_t) * MAX_NUM_CHANNELS * state->frameCount;
-    memset(outTemp, 0, size);
 
     size_t numFrames = state->frameCount;
 
@@ -997,6 +996,7 @@
         }
         e0 &= ~(e1);
         int32_t *out = t1.mainBuffer;
+        memset(outTemp, 0, size);
         while (e1) {
             const int i = 31 - __builtin_clz(e1);
             e1 &= ~(1<<i);
diff --git a/services/java/com/android/server/NativeDaemonConnector.java b/services/java/com/android/server/NativeDaemonConnector.java
index cf87a9d..88d94c2 100644
--- a/services/java/com/android/server/NativeDaemonConnector.java
+++ b/services/java/com/android/server/NativeDaemonConnector.java
@@ -97,11 +97,12 @@
                     LocalSocketAddress.Namespace.RESERVED);
 
             socket.connect(address);
-            mCallbacks.onDaemonConnected();
 
             InputStream inputStream = socket.getInputStream();
             mOutputStream = socket.getOutputStream();
 
+            mCallbacks.onDaemonConnected();
+
             byte[] buffer = new byte[BUFFER_SIZE];
             int start = 0;
 
diff --git a/services/java/com/android/server/NotificationManagerService.java b/services/java/com/android/server/NotificationManagerService.java
index 0490190..47dce41 100755
--- a/services/java/com/android/server/NotificationManagerService.java
+++ b/services/java/com/android/server/NotificationManagerService.java
@@ -156,10 +156,11 @@
         final int id;
         final int uid;
         final int initialPid;
+        final int priority;
         final Notification notification;
         IBinder statusBarKey;
 
-        NotificationRecord(String pkg, String tag, int id, int uid, int initialPid,
+        NotificationRecord(String pkg, String tag, int id, int uid, int initialPid, int priority,
                 Notification notification)
         {
             this.pkg = pkg;
@@ -167,6 +168,7 @@
             this.id = id;
             this.uid = uid;
             this.initialPid = initialPid;
+            this.priority = priority;
             this.notification = notification;
         }
 
@@ -194,7 +196,9 @@
                 + Integer.toHexString(System.identityHashCode(this))
                 + " pkg=" + pkg
                 + " id=" + Integer.toHexString(id)
-                + " tag=" + tag + "}";
+                + " tag=" + tag 
+                + " pri=" + priority 
+                + "}";
         }
     }
 
@@ -649,11 +653,27 @@
                 tag, id, notification, idOut);
     }
 
+    public void enqueueNotificationWithTagPriority(String pkg, String tag, int id, int priority,
+            Notification notification, int[] idOut)
+    {
+        enqueueNotificationInternal(pkg, Binder.getCallingUid(), Binder.getCallingPid(),
+                tag, id, priority, notification, idOut);
+    }
+
     // Not exposed via Binder; for system use only (otherwise malicious apps could spoof the
     // uid/pid of another application)
     public void enqueueNotificationInternal(String pkg, int callingUid, int callingPid,
             String tag, int id, Notification notification, int[] idOut)
     {
+        enqueueNotificationInternal(pkg, callingUid, callingPid, tag, id, 
+                ((notification.flags & Notification.FLAG_ONGOING_EVENT) != 0)
+                    ? StatusBarNotification.PRIORITY_ONGOING
+                    : StatusBarNotification.PRIORITY_NORMAL,
+                notification, idOut);
+    }
+    public void enqueueNotificationInternal(String pkg, int callingUid, int callingPid,
+            String tag, int id, int priority, Notification notification, int[] idOut)
+    {
         checkIncomingCall(pkg);
 
         // Limit the number of notifications that any given package except the android
@@ -695,8 +715,10 @@
         }
 
         synchronized (mNotificationList) {
-            NotificationRecord r = new NotificationRecord(pkg, tag, id,
-                    callingUid, callingPid, notification);
+            NotificationRecord r = new NotificationRecord(pkg, tag, id, 
+                    callingUid, callingPid, 
+                    priority,
+                    notification);
             NotificationRecord old = null;
 
             int index = indexOfNotificationLocked(pkg, tag, id);
@@ -722,6 +744,8 @@
             if (notification.icon != 0) {
                 StatusBarNotification n = new StatusBarNotification(pkg, id, tag,
                         r.uid, r.initialPid, notification);
+                n.priority = r.priority;
+
                 if (old != null && old.statusBarKey != null) {
                     r.statusBarKey = old.statusBarKey;
                     long identity = Binder.clearCallingIdentity();
@@ -743,6 +767,7 @@
                 }
                 sendAccessibilityEvent(notification, pkg);
             } else {
+                Slog.e(TAG, "Ignoring notification with icon==0: " + notification);
                 if (old != null && old.statusBarKey != null) {
                     long identity = Binder.clearCallingIdentity();
                     try {
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 683c2c0..6a6cc2a 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -630,6 +630,9 @@
             }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
         }
 
+        // Mmmmmm... more memory!
+        dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
+
         // The system server has to run all of the time, so it needs to be
         // as efficient as possible with its memory usage.
         VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
diff --git a/services/java/com/android/server/WindowManagerService.java b/services/java/com/android/server/WindowManagerService.java
index c51e4a6..b7a276f 100644
--- a/services/java/com/android/server/WindowManagerService.java
+++ b/services/java/com/android/server/WindowManagerService.java
@@ -694,7 +694,7 @@
             boolean changed = setRotationUncheckedLocked(
                     WindowManagerPolicy.USE_LAST_ROTATION, 0, false);
             if (changed) {
-                sendNewConfiguration();
+                mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
             }
         }
 
@@ -706,6 +706,9 @@
             Surface.openTransaction();
             try {
                 mSurface.setPosition((int)(x - mThumbOffsetX), (int)(y - mThumbOffsetY));
+                if (SHOW_TRANSACTIONS) Slog.i(TAG, "  DRAG "
+                        + mSurface + ": pos=(" +
+                        (int)(x - mThumbOffsetX) + "," + (int)(y - mThumbOffsetY) + ")");
             } finally {
                 Surface.closeTransaction();
                 if (SHOW_TRANSACTIONS) Slog.i(TAG, "<<< CLOSE TRANSACTION notifyMoveLw");
@@ -913,7 +916,7 @@
     Rect mCompatibleScreenFrame = new Rect();
     // The surface used to fill the outer rim of the app running in compatibility mode.
     Surface mBackgroundFillerSurface = null;
-    boolean mBackgroundFillerShown = false;
+    WindowState mBackgroundFillerTarget = null;
 
     public static WindowManagerService main(Context context,
             PowerManagerService pm, boolean haveInputMethods) {
@@ -927,9 +930,8 @@
                 } catch (InterruptedException e) {
                 }
             }
+            return thr.mService;
         }
-
-        return thr.mService;
     }
 
     static class WMThread extends Thread {
@@ -5882,6 +5884,8 @@
                     if (mDragState == null) {
                         Surface surface = new Surface(session, callerPid, "drag surface", 0,
                                 width, height, PixelFormat.TRANSLUCENT, Surface.HIDDEN);
+                        if (SHOW_TRANSACTIONS) Slog.i(TAG, "  DRAG "
+                                + surface + ": CREATE");
                         outSurface.copyFrom(surface);
                         final IBinder winBinder = window.asBinder();
                         token = new Binder();
@@ -8104,9 +8108,7 @@
                  mFrame.left <= mCompatibleScreenFrame.left &&
                  mFrame.top <= mCompatibleScreenFrame.top &&
                  mFrame.right >= mCompatibleScreenFrame.right &&
-                 mFrame.bottom >= mCompatibleScreenFrame.bottom &&
-                 // and starting window do not need background filler
-                 mAttrs.type != mAttrs.TYPE_APPLICATION_STARTING;
+                 mFrame.bottom >= mCompatibleScreenFrame.bottom;
         }
 
         boolean isFullscreen(int screenWidth, int screenHeight) {
@@ -10437,7 +10439,8 @@
             boolean dimming = false;
             boolean covered = false;
             boolean syswin = false;
-            boolean backgroundFillerShown = false;
+            boolean backgroundFillerWasShown = mBackgroundFillerTarget != null;
+            mBackgroundFillerTarget = null;
 
             final int N = mWindows.size();
 
@@ -10739,6 +10742,16 @@
 
                 final boolean obscuredChanged = w.mObscured != obscured;
 
+                if (mBackgroundFillerTarget != null) {
+                    if (w.isAnimating()) {
+                        // Background filler is below all other windows that
+                        // are animating.
+                        mBackgroundFillerTarget = w;
+                    } else if (w.mIsWallpaper) {
+                        mBackgroundFillerTarget = w;
+                    }
+                }
+
                 // Update effect.
                 if (!(w.mObscured=obscured)) {
                     if (w.mSurface != null) {
@@ -10767,33 +10780,10 @@
                         // so we want to leave all of them as unblurred (for
                         // performance reasons).
                         obscured = true;
-                    } else if (opaqueDrawn && w.needsBackgroundFiller(dw, dh)) {
-                        if (SHOW_TRANSACTIONS) Slog.d(TAG, "showing background filler");
+                    } else if (w.needsBackgroundFiller(dw, dh) && (canBeSeen || w.isAnimating())) {
                         // This window is in compatibility mode, and needs background filler.
                         obscured = true;
-                        if (mBackgroundFillerSurface == null) {
-                            try {
-                                mBackgroundFillerSurface = new Surface(mFxSession, 0,
-                                        "BackGroundFiller",
-                                        0, dw, dh,
-                                        PixelFormat.OPAQUE,
-                                        Surface.FX_SURFACE_NORMAL);
-                            } catch (Exception e) {
-                                Slog.e(TAG, "Exception creating filler surface", e);
-                            }
-                        }
-                        try {
-                            mBackgroundFillerSurface.setPosition(0, 0);
-                            mBackgroundFillerSurface.setSize(dw, dh);
-                            // Using the same layer as Dim because they will never be shown at the
-                            // same time.
-                            mBackgroundFillerSurface.setLayer(w.mAnimLayer - 1);
-                            mBackgroundFillerSurface.show();
-                        } catch (RuntimeException e) {
-                            Slog.e(TAG, "Exception showing filler surface");
-                        }
-                        backgroundFillerShown = true;
-                        mBackgroundFillerShown = true;
+                        mBackgroundFillerTarget = w;
                     } else if (canBeSeen && !obscured &&
                             (attrFlags&FLAG_BLUR_BEHIND|FLAG_DIM_BEHIND) != 0) {
                         if (localLOGV) Slog.v(TAG, "Win " + w
@@ -10817,8 +10807,6 @@
                                 //Slog.i(TAG, "BLUR BEHIND: " + w);
                                 blurring = true;
                                 if (mBlurSurface == null) {
-                                    if (SHOW_TRANSACTIONS) Slog.i(TAG, "  BLUR "
-                                            + mBlurSurface + ": CREATE");
                                     try {
                                         mBlurSurface = new Surface(mFxSession, 0,
                                                 "BlurSurface",
@@ -10828,6 +10816,8 @@
                                     } catch (Exception e) {
                                         Slog.e(TAG, "Exception creating Blur surface", e);
                                     }
+                                    if (SHOW_TRANSACTIONS) Slog.i(TAG, "  BLUR "
+                                            + mBlurSurface + ": CREATE");
                                 }
                                 if (mBlurSurface != null) {
                                     if (SHOW_TRANSACTIONS) Slog.i(TAG, "  BLUR "
@@ -10860,9 +10850,39 @@
                 }
             }
 
-            if (backgroundFillerShown == false && mBackgroundFillerShown) {
-                mBackgroundFillerShown = false;
-                if (SHOW_TRANSACTIONS) Slog.d(TAG, "hiding background filler");
+            if (mBackgroundFillerTarget != null) {
+                if (mBackgroundFillerSurface == null) {
+                    try {
+                        mBackgroundFillerSurface = new Surface(mFxSession, 0,
+                                "BackGroundFiller",
+                                0, dw, dh,
+                                PixelFormat.OPAQUE,
+                                Surface.FX_SURFACE_NORMAL);
+                    } catch (Exception e) {
+                        Slog.e(TAG, "Exception creating filler surface", e);
+                    }
+                    if (SHOW_TRANSACTIONS) Slog.i(TAG, "  BG FILLER "
+                            + mBackgroundFillerSurface + ": CREATE");
+                }
+                try {
+                    if (SHOW_TRANSACTIONS) Slog.i(TAG, "  BG FILLER "
+                            + mBackgroundFillerSurface + " SHOW: pos=(0,0) ("
+                            + dw + "x" + dh + ") layer="
+                            + (mBackgroundFillerTarget.mLayer - 1));
+                    mBackgroundFillerSurface.setPosition(0, 0);
+                    mBackgroundFillerSurface.setSize(dw, dh);
+                    // Using the same layer as Dim because they will never be shown at the
+                    // same time.  NOTE: we do NOT use mAnimLayer, because we don't
+                    // want this surface dragged up in front of stuff that is animating.
+                    mBackgroundFillerSurface.setLayer(mBackgroundFillerTarget.mLayer - 1);
+                    mBackgroundFillerSurface.show();
+                } catch (RuntimeException e) {
+                    Slog.e(TAG, "Exception showing filler surface");
+                }
+            } else if (backgroundFillerWasShown) {
+                mBackgroundFillerTarget = null;
+                if (SHOW_TRANSACTIONS) Slog.i(TAG, "  BG FILLER "
+                        + mBackgroundFillerSurface + " HIDE");
                 try {
                     mBackgroundFillerSurface.hide();
                 } catch (RuntimeException e) {
@@ -11059,7 +11079,7 @@
             boolean changed = setRotationUncheckedLocked(
                     WindowManagerPolicy.USE_LAST_ROTATION, 0, false);
             if (changed) {
-                sendNewConfiguration();
+                mH.sendEmptyMessage(H.SEND_NEW_CONFIGURATION);
             }
         }
         
@@ -12045,7 +12065,6 @@
      * This is used for opening/closing transition for apps in compatible mode.
      */
     private static class FadeInOutAnimation extends Animation {
-        int mWidth;
         boolean mFadeIn;
 
         public FadeInOutAnimation(boolean fadeIn) {
@@ -12060,24 +12079,7 @@
             if (!mFadeIn) {
                 x = 1.0f - x; // reverse the interpolation for fade out
             }
-            if (x < 0.5) {
-                // move the window out of the screen.
-                t.getMatrix().setTranslate(mWidth, 0);
-            } else {
-                t.getMatrix().setTranslate(0, 0);// show
-                t.setAlpha((x - 0.5f) * 2);
-            }
-        }
-
-        @Override
-        public void initialize(int width, int height, int parentWidth, int parentHeight) {
-            // width is the screen width {@see AppWindowToken#stepAnimatinoLocked}
-            mWidth = width;
-        }
-
-        @Override
-        public int getZAdjustment() {
-            return Animation.ZORDER_TOP;
+            t.setAlpha(x);
         }
     }
 
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index ea5e5cc..697e879 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -293,18 +293,21 @@
     return result;
 }
 
-void SensorService::cleanupConnection(const wp<SensorEventConnection>& connection)
+void SensorService::cleanupConnection(SensorEventConnection* c)
 {
     Mutex::Autolock _l(mLock);
+    const wp<SensorEventConnection> connection(c);
     size_t size = mActiveSensors.size();
     for (size_t i=0 ; i<size ; ) {
-        SensorRecord* rec = mActiveSensors.valueAt(i);
-        if (rec && rec->removeConnection(connection)) {
-            int handle = mActiveSensors.keyAt(i);
+        int handle = mActiveSensors.keyAt(i);
+        if (c->hasSensor(handle)) {
             SensorInterface* sensor = mSensorMap.valueFor( handle );
             if (sensor) {
-                sensor->activate(connection.unsafe_get(), false);
+                sensor->activate(c, false);
             }
+        }
+        SensorRecord* rec = mActiveSensors.valueAt(i);
+        if (rec && rec->removeConnection(connection)) {
             mActiveSensors.removeItemsAt(i, 1);
             mActiveVirtualSensors.removeItem(handle);
             delete rec;
diff --git a/services/sensorservice/SensorService.h b/services/sensorservice/SensorService.h
index 540c7e2..21f12bd 100644
--- a/services/sensorservice/SensorService.h
+++ b/services/sensorservice/SensorService.h
@@ -129,7 +129,7 @@
 public:
     static char const* getServiceName() { return "sensorservice"; }
 
-    void cleanupConnection(const wp<SensorEventConnection>& connection);
+    void cleanupConnection(SensorEventConnection* connection);
     status_t enable(const sp<SensorEventConnection>& connection, int handle);
     status_t disable(const sp<SensorEventConnection>& connection, int handle);
     status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns);
diff --git a/telephony/java/com/android/internal/telephony/SMSDispatcher.java b/telephony/java/com/android/internal/telephony/SMSDispatcher.java
old mode 100644
new mode 100755
index 99123af..02af79f
--- a/telephony/java/com/android/internal/telephony/SMSDispatcher.java
+++ b/telephony/java/com/android/internal/telephony/SMSDispatcher.java
@@ -66,6 +66,7 @@
 
 public abstract class SMSDispatcher extends Handler {
     private static final String TAG = "SMS";
+    private static final String SEND_NEXT_MSG_EXTRA = "SendNextMsg";
 
     /** Default checking period for SMS sent without user permit */
     private static final int DEFAULT_SMS_CHECK_PERIOD = 3600000;
@@ -162,6 +163,8 @@
     protected boolean mSmsReceiveDisabled;
     protected boolean mSmsSendDisabled;
 
+    protected static int mRemainingMessages = -1;
+
     protected static int getNextConcatenatedRef() {
         sConcatenatedRef += 1;
         return sConcatenatedRef;
@@ -486,7 +489,17 @@
 
             if (sentIntent != null) {
                 try {
-                    sentIntent.send(Activity.RESULT_OK);
+                    if (mRemainingMessages > -1) {
+                        mRemainingMessages--;
+                    }
+
+                    if (mRemainingMessages == 0) {
+                        Intent sendNext = new Intent();
+                        sendNext.putExtra(SEND_NEXT_MSG_EXTRA, true);
+                        sentIntent.send(mContext, Activity.RESULT_OK, sendNext);
+                    } else {
+                        sentIntent.send(Activity.RESULT_OK);
+                    }
                 } catch (CanceledException ex) {}
             }
         } else {
@@ -525,8 +538,15 @@
                     if (ar.result != null) {
                         fillIn.putExtra("errorCode", ((SmsResponse)ar.result).errorCode);
                     }
-                    tracker.mSentIntent.send(mContext, error, fillIn);
+                    if (mRemainingMessages > -1) {
+                        mRemainingMessages--;
+                    }
 
+                    if (mRemainingMessages == 0) {
+                        fillIn.putExtra(SEND_NEXT_MSG_EXTRA, true);
+                    }
+
+                    tracker.mSentIntent.send(mContext, error, fillIn);
                 } catch (CanceledException ex) {}
             }
         }
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java b/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
index 21ae98e..f576b4e 100755
--- a/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
@@ -200,6 +200,8 @@
         int msgCount = parts.size();
         int encoding = android.telephony.SmsMessage.ENCODING_UNKNOWN;
 
+        mRemainingMessages = msgCount;
+
         for (int i = 0; i < msgCount; i++) {
             TextEncodingDetails details = SmsMessage.calculateLength(parts.get(i), false);
             if (encoding != details.codeUnitSize
@@ -289,6 +291,8 @@
         int msgCount = parts.size();
         int encoding = android.telephony.SmsMessage.ENCODING_UNKNOWN;
 
+        mRemainingMessages = msgCount;
+
         for (int i = 0; i < msgCount; i++) {
             TextEncodingDetails details = SmsMessage.calculateLength(parts.get(i), false);
             if (encoding != details.codeUnitSize
diff --git a/tests/HwAccelerationTest/AndroidManifest.xml b/tests/HwAccelerationTest/AndroidManifest.xml
index 3535809..f72de127 100644
--- a/tests/HwAccelerationTest/AndroidManifest.xml
+++ b/tests/HwAccelerationTest/AndroidManifest.xml
@@ -32,6 +32,15 @@
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
+        
+        <activity
+                android:name="MarqueeActivity"
+                android:label="_Marquee">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
 
         <activity
                 android:name="ShapesActivity"
diff --git a/tests/HwAccelerationTest/res/anim/accelerate_interpolator_2.xml b/tests/HwAccelerationTest/res/anim/accelerate_interpolator_2.xml
new file mode 100644
index 0000000..e4a8d48
--- /dev/null
+++ b/tests/HwAccelerationTest/res/anim/accelerate_interpolator_2.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+** Copyright 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.
+*/
+-->
+
+<accelerateInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
+    android:factor="2.0"/>
diff --git a/tests/HwAccelerationTest/res/anim/slide_off_left.xml b/tests/HwAccelerationTest/res/anim/slide_off_left.xml
new file mode 100644
index 0000000..f05de39
--- /dev/null
+++ b/tests/HwAccelerationTest/res/anim/slide_off_left.xml
@@ -0,0 +1,20 @@
+<?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.
+-->
+<translate xmlns:android="http://schemas.android.com/apk/res/android"
+    android:fromXDelta="0%"
+    android:toXDelta="-100%"
+    android:interpolator="@anim/accelerate_interpolator_2"
+    android:duration="600"/>
\ No newline at end of file
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/MarqueeActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/MarqueeActivity.java
new file mode 100644
index 0000000..715cdbb
--- /dev/null
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/MarqueeActivity.java
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+
+package com.android.test.hwui;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.text.TextUtils;
+import android.view.View;
+import android.view.animation.Animation;
+import android.view.animation.AnimationUtils;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+@SuppressWarnings({"UnusedDeclaration"})
+public class MarqueeActivity extends Activity {
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        final LinearLayout linearLayout = new LinearLayout(this);
+        linearLayout.setOrientation(LinearLayout.VERTICAL);
+        
+        final TextView text1 = new TextView(this);
+        text1.setText("This is a marquee inside a TextView");
+        text1.setSingleLine(true);
+        text1.setHorizontalFadingEdgeEnabled(true);
+        text1.setEllipsize(TextUtils.TruncateAt.MARQUEE);
+        linearLayout.addView(text1, new LinearLayout.LayoutParams(
+                100, LinearLayout.LayoutParams.WRAP_CONTENT));
+
+        final TextView text2 = new TextView(this);
+        text2.setText("This is a marquee inside a TextView");
+        text2.setSingleLine(true);
+        text2.setHorizontalFadingEdgeEnabled(true);
+        text2.setEllipsize(TextUtils.TruncateAt.MARQUEE);
+        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
+                100, LinearLayout.LayoutParams.WRAP_CONTENT);
+        linearLayout.addView(text2, params);
+
+        setContentView(linearLayout);
+        
+        getWindow().getDecorView().postDelayed(new Runnable() {
+            @Override
+            public void run() {
+                text2.setVisibility(View.INVISIBLE);
+                Animation animation = AnimationUtils.loadAnimation(text2.getContext(),
+                        R.anim.slide_off_left);
+                animation.setFillEnabled(true);
+                animation.setFillAfter(true);
+                text2.startAnimation(animation);
+            }
+        }, 1000);
+    }
+}
diff --git a/tests/StatusBar/src/com/android/statusbartest/NotificationTestList.java b/tests/StatusBar/src/com/android/statusbartest/NotificationTestList.java
index 90c2a1a..f463a19 100644
--- a/tests/StatusBar/src/com/android/statusbartest/NotificationTestList.java
+++ b/tests/StatusBar/src/com/android/statusbartest/NotificationTestList.java
@@ -35,6 +35,10 @@
 import android.widget.ProgressBar;
 import android.os.PowerManager;
 
+// private NM API
+import android.app.INotificationManager;
+import com.android.internal.statusbar.StatusBarNotification;
+
 public class NotificationTestList extends TestActivity
 {
     private final static String TAG = "NotificationTestList";
@@ -205,6 +209,15 @@
             }
         },
 
+        new Test("Null Icon #1 (when=now)") {
+            public void run() {
+                Notification n = new Notification(0, null, System.currentTimeMillis());
+                n.setLatestEventInfo(NotificationTestList.this, "Persistent #1",
+                            "This is the same notification!!!", makeIntent());
+                mNM.notify(1, n);
+            }
+        },
+
         new Test("Bad resource #1 (when=create)") {
             public void run() {
                 Notification n = new Notification(R.drawable.icon2,
@@ -752,6 +765,30 @@
             }
         },
 
+        new Test("System priority notification") {
+            public void run() {
+                Notification n = new Notification.Builder(NotificationTestList.this)
+                    .setSmallIcon(R.drawable.notification1)
+                    .setContentTitle("System priority")
+                    .setContentText("This should appear before all others")
+                    .getNotification();
+
+                int[] idOut = new int[1];
+                try {
+                    INotificationManager directLine = mNM.getService();
+                    directLine.enqueueNotificationWithTagPriority(
+                            getPackageName(),
+                            null, 
+                            1, 
+                            StatusBarNotification.PRIORITY_SYSTEM,
+                            n,
+                            idOut);
+                } catch (android.os.RemoteException ex) {
+                    // oh well
+                }
+            }
+        },
+
         new Test("Crash") {
             public void run()
             {
diff --git a/tools/layoutlib/bridge/Android.mk b/tools/layoutlib/bridge/Android.mk
index 3d4c76a..ca7db8c 100644
--- a/tools/layoutlib/bridge/Android.mk
+++ b/tools/layoutlib/bridge/Android.mk
@@ -17,6 +17,8 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES := $(call all-java-files-under,src)
+LOCAL_JAVA_RESOURCE_DIRS := resources
+
 
 LOCAL_JAVA_LIBRARIES := \
 	kxml2-2.3.0 \
diff --git a/tools/layoutlib/bridge/resources/bars/action_bar.xml b/tools/layoutlib/bridge/resources/bars/action_bar.xml
new file mode 100644
index 0000000..51983f2
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/action_bar.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<merge xmlns:android="http://schemas.android.com/apk/res/android">
+	<ImageView
+			android:layout_height="wrap_content"
+			android:layout_width="wrap_content"/>
+	<TextView
+			android:layout_width="wrap_content"
+			android:layout_height="wrap_content"/>
+</merge>
diff --git a/tools/layoutlib/bridge/resources/bars/hdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/hdpi/stat_sys_wifi_signal_4_fully.png
new file mode 100644
index 0000000..bd44b52
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/hdpi/stat_sys_wifi_signal_4_fully.png
Binary files differ
diff --git a/tools/layoutlib/bridge/resources/bars/hdpi/status_bar_background.9.png b/tools/layoutlib/bridge/resources/bars/hdpi/status_bar_background.9.png
new file mode 100644
index 0000000..a4be298
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/hdpi/status_bar_background.9.png
Binary files differ
diff --git a/tools/layoutlib/bridge/resources/bars/mdpi/ic_sysbar_back_default.png b/tools/layoutlib/bridge/resources/bars/mdpi/ic_sysbar_back_default.png
new file mode 100644
index 0000000..4bcd2be
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/mdpi/ic_sysbar_back_default.png
Binary files differ
diff --git a/tools/layoutlib/bridge/resources/bars/mdpi/ic_sysbar_home_default.png b/tools/layoutlib/bridge/resources/bars/mdpi/ic_sysbar_home_default.png
new file mode 100644
index 0000000..cfeba3e
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/mdpi/ic_sysbar_home_default.png
Binary files differ
diff --git a/tools/layoutlib/bridge/resources/bars/mdpi/ic_sysbar_recent_default.png b/tools/layoutlib/bridge/resources/bars/mdpi/ic_sysbar_recent_default.png
new file mode 100644
index 0000000..1d97e05
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/mdpi/ic_sysbar_recent_default.png
Binary files differ
diff --git a/tools/layoutlib/bridge/resources/bars/mdpi/stat_sys_wifi_signal_4_fully.png b/tools/layoutlib/bridge/resources/bars/mdpi/stat_sys_wifi_signal_4_fully.png
new file mode 100644
index 0000000..c629387
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/mdpi/stat_sys_wifi_signal_4_fully.png
Binary files differ
diff --git a/tools/layoutlib/bridge/resources/bars/mdpi/status_bar_background.9.png b/tools/layoutlib/bridge/resources/bars/mdpi/status_bar_background.9.png
new file mode 100644
index 0000000..eb7c1a4
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/mdpi/status_bar_background.9.png
Binary files differ
diff --git a/tools/layoutlib/bridge/resources/bars/phone_system_bar.xml b/tools/layoutlib/bridge/resources/bars/phone_system_bar.xml
new file mode 100644
index 0000000..5211b0a
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/phone_system_bar.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="utf-8"?>
+<merge xmlns:android="http://schemas.android.com/apk/res/android">
+	<TextView
+			android:layout_width="wrap_content"
+			android:layout_height="wrap_content"
+			android:layout_weight="1"/>
+	<ImageView
+			android:layout_height="wrap_content"
+			android:layout_width="wrap_content"/>
+	<ImageView
+			android:layout_height="wrap_content"
+			android:layout_width="wrap_content"/>
+</merge>
diff --git a/tools/layoutlib/bridge/resources/bars/tablet_system_bar.xml b/tools/layoutlib/bridge/resources/bars/tablet_system_bar.xml
new file mode 100644
index 0000000..c5acddb
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/tablet_system_bar.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<merge xmlns:android="http://schemas.android.com/apk/res/android">
+	<ImageView
+			android:layout_height="wrap_content"
+			android:layout_width="wrap_content"/>
+	<ImageView
+			android:layout_height="wrap_content"
+			android:layout_width="wrap_content"/>
+	<ImageView
+			android:layout_height="wrap_content"
+			android:layout_width="wrap_content"/>
+	<TextView
+			android:layout_width="wrap_content"
+			android:layout_height="wrap_content"
+			android:layout_weight="1"/>
+	<ImageView
+			android:layout_height="wrap_content"
+			android:layout_width="wrap_content"/>
+	<ImageView
+			android:layout_height="wrap_content"
+			android:layout_width="wrap_content"
+			android:layout_marginLeft="3dip"
+			android:layout_marginRight="15dip"/>
+</merge>
diff --git a/tools/layoutlib/bridge/resources/bars/title_bar.xml b/tools/layoutlib/bridge/resources/bars/title_bar.xml
new file mode 100644
index 0000000..76d78d9
--- /dev/null
+++ b/tools/layoutlib/bridge/resources/bars/title_bar.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<merge xmlns:android="http://schemas.android.com/apk/res/android">
+	<TextView
+			android:layout_width="wrap_content"
+			android:layout_height="wrap_content"/>
+</merge>
diff --git a/tools/layoutlib/bridge/src/android/graphics/BitmapFactory.java b/tools/layoutlib/bridge/src/android/graphics/BitmapFactory.java
deleted file mode 100644
index 993c305..0000000
--- a/tools/layoutlib/bridge/src/android/graphics/BitmapFactory.java
+++ /dev/null
@@ -1,578 +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.
- */
-
-package android.graphics;
-
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.layoutlib.bridge.Bridge;
-import com.android.resources.Density;
-
-import android.content.res.AssetManager;
-import android.content.res.Resources;
-import android.util.DisplayMetrics;
-import android.util.TypedValue;
-
-import java.io.BufferedInputStream;
-import java.io.FileDescriptor;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * Creates Bitmap objects from various sources, including files, streams,
- * and byte-arrays.
- */
-public class BitmapFactory {
-    public static class Options {
-        /**
-         * Create a default Options object, which if left unchanged will give
-         * the same result from the decoder as if null were passed.
-         */
-        public Options() {
-            inDither = true;
-            inScaled = true;
-        }
-
-        /**
-         * If set to true, the decoder will return null (no bitmap), but
-         * the out... fields will still be set, allowing the caller to query
-         * the bitmap without having to allocate the memory for its pixels.
-         */
-        public boolean inJustDecodeBounds;
-
-        /**
-         * If set to a value > 1, requests the decoder to subsample the original
-         * image, returning a smaller image to save memory. The sample size is
-         * the number of pixels in either dimension that correspond to a single
-         * pixel in the decoded bitmap. For example, inSampleSize == 4 returns
-         * an image that is 1/4 the width/height of the original, and 1/16 the
-         * number of pixels. Any value <= 1 is treated the same as 1. Note: the
-         * decoder will try to fulfill this request, but the resulting bitmap
-         * may have different dimensions that precisely what has been requested.
-         * Also, powers of 2 are often faster/easier for the decoder to honor.
-         */
-        public int inSampleSize;
-
-        /**
-         * If this is non-null, the decoder will try to decode into this
-         * internal configuration. If it is null, or the request cannot be met,
-         * the decoder will try to pick the best matching config based on the
-         * system's screen depth, and characteristics of the original image such
-         * as if it has per-pixel alpha (requiring a config that also does).
-         */
-        public Bitmap.Config inPreferredConfig;
-
-        /**
-         * If dither is true, the decoder will attempt to dither the decoded
-         * image.
-         */
-        public boolean inDither;
-
-        /**
-         * The pixel density to use for the bitmap.  This will always result
-         * in the returned bitmap having a density set for it (see
-         * {@link Bitmap#setDensity(int) Bitmap.setDensity(int)).  In addition,
-         * if {@link #inScaled} is set (which it is by default} and this
-         * density does not match {@link #inTargetDensity}, then the bitmap
-         * will be scaled to the target density before being returned.
-         *
-         * <p>If this is 0,
-         * {@link BitmapFactory#decodeResource(Resources, int)},
-         * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
-         * and {@link BitmapFactory#decodeResourceStream}
-         * will fill in the density associated with the resource.  The other
-         * functions will leave it as-is and no density will be applied.
-         *
-         * @see #inTargetDensity
-         * @see #inScreenDensity
-         * @see #inScaled
-         * @see Bitmap#setDensity(int)
-         * @see android.util.DisplayMetrics#densityDpi
-         */
-        public int inDensity;
-
-        /**
-         * The pixel density of the destination this bitmap will be drawn to.
-         * This is used in conjunction with {@link #inDensity} and
-         * {@link #inScaled} to determine if and how to scale the bitmap before
-         * returning it.
-         *
-         * <p>If this is 0,
-         * {@link BitmapFactory#decodeResource(Resources, int)},
-         * {@link BitmapFactory#decodeResource(Resources, int, android.graphics.BitmapFactory.Options)},
-         * and {@link BitmapFactory#decodeResourceStream}
-         * will fill in the density associated the Resources object's
-         * DisplayMetrics.  The other
-         * functions will leave it as-is and no scaling for density will be
-         * performed.
-         *
-         * @see #inDensity
-         * @see #inScreenDensity
-         * @see #inScaled
-         * @see android.util.DisplayMetrics#densityDpi
-         */
-        public int inTargetDensity;
-
-        /**
-         * The pixel density of the actual screen that is being used.  This is
-         * purely for applications running in density compatibility code, where
-         * {@link #inTargetDensity} is actually the density the application
-         * sees rather than the real screen density.
-         *
-         * <p>By setting this, you
-         * allow the loading code to avoid scaling a bitmap that is currently
-         * in the screen density up/down to the compatibility density.  Instead,
-         * if {@link #inDensity} is the same as {@link #inScreenDensity}, the
-         * bitmap will be left as-is.  Anything using the resulting bitmap
-         * must also used {@link Bitmap#getScaledWidth(int)
-         * Bitmap.getScaledWidth} and {@link Bitmap#getScaledHeight
-         * Bitmap.getScaledHeight} to account for any different between the
-         * bitmap's density and the target's density.
-         *
-         * <p>This is never set automatically for the caller by
-         * {@link BitmapFactory} itself.  It must be explicitly set, since the
-         * caller must deal with the resulting bitmap in a density-aware way.
-         *
-         * @see #inDensity
-         * @see #inTargetDensity
-         * @see #inScaled
-         * @see android.util.DisplayMetrics#densityDpi
-         */
-        public int inScreenDensity;
-
-        /**
-         * When this flag is set, if {@link #inDensity} and
-         * {@link #inTargetDensity} are not 0, the
-         * bitmap will be scaled to match {@link #inTargetDensity} when loaded,
-         * rather than relying on the graphics system scaling it each time it
-         * is drawn to a Canvas.
-         *
-         * <p>This flag is turned on by default and should be turned off if you need
-         * a non-scaled version of the bitmap.  Nine-patch bitmaps ignore this
-         * flag and are always scaled.
-         */
-        public boolean inScaled;
-
-        /**
-         * If this is set to true, then the resulting bitmap will allocate its
-         * pixels such that they can be purged if the system needs to reclaim
-         * memory. In that instance, when the pixels need to be accessed again
-         * (e.g. the bitmap is drawn, getPixels() is called), they will be
-         * automatically re-decoded.
-         *
-         * For the re-decode to happen, the bitmap must have access to the
-         * encoded data, either by sharing a reference to the input
-         * or by making a copy of it. This distinction is controlled by
-         * inInputShareable. If this is true, then the bitmap may keep a shallow
-         * reference to the input. If this is false, then the bitmap will
-         * explicitly make a copy of the input data, and keep that. Even if
-         * sharing is allowed, the implementation may still decide to make a
-         * deep copy of the input data.
-         */
-        public boolean inPurgeable;
-
-        /**
-         * This field works in conjuction with inPurgeable. If inPurgeable is
-         * false, then this field is ignored. If inPurgeable is true, then this
-         * field determines whether the bitmap can share a reference to the
-         * input data (inputstream, array, etc.) or if it must make a deep copy.
-         */
-        public boolean inInputShareable;
-
-        /**
-         * Normally bitmap allocations count against the dalvik heap, which
-         * means they help trigger GCs when a lot have been allocated. However,
-         * in rare cases, the caller may want to allocate the bitmap outside of
-         * that heap. To request that, set inNativeAlloc to true. In these
-         * rare instances, it is solely up to the caller to ensure that OOM is
-         * managed explicitly by calling bitmap.recycle() as soon as such a
-         * bitmap is no longer needed.
-         *
-         * @hide pending API council approval
-         */
-        public boolean inNativeAlloc;
-
-        /**
-         * The resulting width of the bitmap, set independent of the state of
-         * inJustDecodeBounds. However, if there is an error trying to decode,
-         * outWidth will be set to -1.
-         */
-        public int outWidth;
-
-        /**
-         * The resulting height of the bitmap, set independent of the state of
-         * inJustDecodeBounds. However, if there is an error trying to decode,
-         * outHeight will be set to -1.
-         */
-        public int outHeight;
-
-        /**
-         * If known, this string is set to the mimetype of the decoded image.
-         * If not know, or there is an error, it is set to null.
-         */
-        public String outMimeType;
-
-        /**
-         * Temp storage to use for decoding.  Suggest 16K or so.
-         */
-        public byte[] inTempStorage;
-
-        private native void requestCancel();
-
-        /**
-         * Flag to indicate that cancel has been called on this object.  This
-         * is useful if there's an intermediary that wants to first decode the
-         * bounds and then decode the image.  In that case the intermediary
-         * can check, inbetween the bounds decode and the image decode, to see
-         * if the operation is canceled.
-         */
-        public boolean mCancel;
-
-        /**
-         *  This can be called from another thread while this options object is
-         *  inside a decode... call. Calling this will notify the decoder that
-         *  it should cancel its operation. This is not guaranteed to cancel
-         *  the decode, but if it does, the decoder... operation will return
-         *  null, or if inJustDecodeBounds is true, will set outWidth/outHeight
-         *  to -1
-         */
-        public void requestCancelDecode() {
-            mCancel = true;
-            requestCancel();
-        }
-    }
-
-    /**
-     * Decode a file path into a bitmap. If the specified file name is null,
-     * or cannot be decoded into a bitmap, the function returns null.
-     *
-     * @param pathName complete path name for the file to be decoded.
-     * @param opts null-ok; Options that control downsampling and whether the
-     *             image should be completely decoded, or just is size returned.
-     * @return The decoded bitmap, or null if the image data could not be
-     *         decoded, or, if opts is non-null, if opts requested only the
-     *         size be returned (in opts.outWidth and opts.outHeight)
-     */
-    public static Bitmap decodeFile(String pathName, Options opts) {
-        Bitmap bm = null;
-        InputStream stream = null;
-        try {
-            stream = new FileInputStream(pathName);
-            bm = decodeStream(stream, null, opts);
-        } catch (Exception e) {
-            /*  do nothing.
-                If the exception happened on open, bm will be null.
-            */
-        } finally {
-            if (stream != null) {
-                try {
-                    stream.close();
-                } catch (IOException e) {
-                    // do nothing here
-                }
-            }
-        }
-        return bm;
-    }
-
-    /**
-     * Decode a file path into a bitmap. If the specified file name is null,
-     * or cannot be decoded into a bitmap, the function returns null.
-     *
-     * @param pathName complete path name for the file to be decoded.
-     * @return the resulting decoded bitmap, or null if it could not be decoded.
-     */
-    public static Bitmap decodeFile(String pathName) {
-        return decodeFile(pathName, null);
-    }
-
-    /**
-     * Decode a new Bitmap from an InputStream. This InputStream was obtained from
-     * resources, which we pass to be able to scale the bitmap accordingly.
-     */
-    public static Bitmap decodeResourceStream(Resources res, TypedValue value,
-            InputStream is, Rect pad, Options opts) {
-
-        if (opts == null) {
-            opts = new Options();
-        }
-
-        if (opts.inDensity == 0 && value != null) {
-            final int density = value.density;
-            if (density == TypedValue.DENSITY_DEFAULT) {
-                opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
-            } else if (density != TypedValue.DENSITY_NONE) {
-                opts.inDensity = density;
-            }
-        }
-
-        if (opts.inTargetDensity == 0 && res != null) {
-            opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
-        }
-
-        return decodeStream(is, pad, opts);
-    }
-
-    /**
-     * Synonym for opening the given resource and calling
-     * {@link #decodeResourceStream}.
-     *
-     * @param res   The resources object containing the image data
-     * @param id The resource id of the image data
-     * @param opts null-ok; Options that control downsampling and whether the
-     *             image should be completely decoded, or just is size returned.
-     * @return The decoded bitmap, or null if the image data could not be
-     *         decoded, or, if opts is non-null, if opts requested only the
-     *         size be returned (in opts.outWidth and opts.outHeight)
-     */
-    public static Bitmap decodeResource(Resources res, int id, Options opts) {
-        Bitmap bm = null;
-        InputStream is = null;
-
-        try {
-            final TypedValue value = new TypedValue();
-            is = res.openRawResource(id, value);
-
-            bm = decodeResourceStream(res, value, is, null, opts);
-        } catch (Exception e) {
-            /*  do nothing.
-                If the exception happened on open, bm will be null.
-                If it happened on close, bm is still valid.
-            */
-            Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ,
-                    String.format("Error decoding bitmap of id 0x%x", id), e, null /*data*/);
-        } finally {
-            try {
-                if (is != null) is.close();
-            } catch (IOException e) {
-                // Ignore
-            }
-        }
-
-        return bm;
-    }
-
-    /**
-     * Synonym for {@link #decodeResource(Resources, int, android.graphics.BitmapFactory.Options)}
-     * will null Options.
-     *
-     * @param res The resources object containing the image data
-     * @param id The resource id of the image data
-     * @return The decoded bitmap, or null if the image could not be decode.
-     */
-    public static Bitmap decodeResource(Resources res, int id) {
-        return decodeResource(res, id, null);
-    }
-
-    /**
-     * Decode an immutable bitmap from the specified byte array.
-     *
-     * @param data byte array of compressed image data
-     * @param offset offset into imageData for where the decoder should begin
-     *               parsing.
-     * @param length the number of bytes, beginning at offset, to parse
-     * @param opts null-ok; Options that control downsampling and whether the
-     *             image should be completely decoded, or just is size returned.
-     * @return The decoded bitmap, or null if the image data could not be
-     *         decoded, or, if opts is non-null, if opts requested only the
-     *         size be returned (in opts.outWidth and opts.outHeight)
-     */
-    public static Bitmap decodeByteArray(byte[] data, int offset, int length, Options opts) {
-        if ((offset | length) < 0 || data.length < offset + length) {
-            throw new ArrayIndexOutOfBoundsException();
-        }
-
-        // FIXME: implement as needed, but it's unlikely that this is needed in the context of the bridge.
-        return null;
-        //return nativeDecodeByteArray(data, offset, length, opts);
-    }
-
-    /**
-     * Decode an immutable bitmap from the specified byte array.
-     *
-     * @param data byte array of compressed image data
-     * @param offset offset into imageData for where the decoder should begin
-     *               parsing.
-     * @param length the number of bytes, beginning at offset, to parse
-     * @return The decoded bitmap, or null if the image could not be decode.
-     */
-    public static Bitmap decodeByteArray(byte[] data, int offset, int length) {
-        return decodeByteArray(data, offset, length, null);
-    }
-
-    /**
-     * Decode an input stream into a bitmap. If the input stream is null, or
-     * cannot be used to decode a bitmap, the function returns null.
-     * The stream's position will be where ever it was after the encoded data
-     * was read.
-     *
-     * @param is The input stream that holds the raw data to be decoded into a
-     *           bitmap.
-     * @param outPadding If not null, return the padding rect for the bitmap if
-     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
-     *                   no bitmap is returned (null) then padding is
-     *                   unchanged.
-     * @param opts null-ok; Options that control downsampling and whether the
-     *             image should be completely decoded, or just is size returned.
-     * @return The decoded bitmap, or null if the image data could not be
-     *         decoded, or, if opts is non-null, if opts requested only the
-     *         size be returned (in opts.outWidth and opts.outHeight)
-     */
-    public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) {
-        // we don't throw in this case, thus allowing the caller to only check
-        // the cache, and not force the image to be decoded.
-        if (is == null) {
-            return null;
-        }
-
-        // we need mark/reset to work properly
-
-        if (!is.markSupported()) {
-            is = new BufferedInputStream(is, 16 * 1024);
-        }
-
-        // so we can call reset() if a given codec gives up after reading up to
-        // this many bytes. FIXME: need to find out from the codecs what this
-        // value should be.
-        is.mark(1024);
-
-        Bitmap  bm;
-
-        if (is instanceof AssetManager.AssetInputStream) {
-            Bridge.getLog().error(LayoutLog.TAG_UNSUPPORTED,
-                    "Bitmap.decodeStream: " +
-                    "InputStream is unsupported (AssetManager.AssetInputStream)", null /*data*/);
-            return null;
-        } else {
-            // pass some temp storage down to the native code. 1024 is made up,
-            // but should be large enough to avoid too many small calls back
-            // into is.read(...) This number is not related to the value passed
-            // to mark(...) above.
-            try {
-                Density density = Density.MEDIUM;
-                if (opts != null) {
-                    density = Density.getEnum(opts.inDensity);
-                }
-                bm = Bitmap_Delegate.createBitmap(is, true, density);
-            } catch (IOException e) {
-                return null;
-            }
-        }
-
-        return finishDecode(bm, outPadding, opts);
-    }
-
-    private static Bitmap finishDecode(Bitmap bm, Rect outPadding, Options opts) {
-        if (bm == null || opts == null) {
-            return bm;
-        }
-
-        final int density = opts.inDensity;
-        if (density == 0) {
-            return bm;
-        }
-
-        bm.setDensity(density);
-        final int targetDensity = opts.inTargetDensity;
-        if (targetDensity == 0 || density == targetDensity
-                || density == opts.inScreenDensity) {
-            return bm;
-        }
-
-        byte[] np = bm.getNinePatchChunk();
-        final boolean isNinePatch = false; //np != null && NinePatch.isNinePatchChunk(np);
-        if (opts.inScaled || isNinePatch) {
-            float scale = targetDensity / (float)density;
-            // TODO: This is very inefficient and should be done in native by Skia
-            final Bitmap oldBitmap = bm;
-            bm = Bitmap.createScaledBitmap(oldBitmap, (int) (bm.getWidth() * scale + 0.5f),
-                    (int) (bm.getHeight() * scale + 0.5f), true);
-            oldBitmap.recycle();
-
-            if (isNinePatch) {
-                //np = nativeScaleNinePatch(np, scale, outPadding);
-                bm.setNinePatchChunk(np);
-            }
-            bm.setDensity(targetDensity);
-        }
-
-        return bm;
-    }
-
-    /**
-     * Decode an input stream into a bitmap. If the input stream is null, or
-     * cannot be used to decode a bitmap, the function returns null.
-     * The stream's position will be where ever it was after the encoded data
-     * was read.
-     *
-     * @param is The input stream that holds the raw data to be decoded into a
-     *           bitmap.
-     * @return The decoded bitmap, or null if the image data could not be
-     *         decoded, or, if opts is non-null, if opts requested only the
-     *         size be returned (in opts.outWidth and opts.outHeight)
-     */
-    public static Bitmap decodeStream(InputStream is) {
-        return decodeStream(is, null, null);
-    }
-
-    /**
-     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
-     * return null. The position within the descriptor will not be changed when
-     * this returns, so the descriptor can be used again as-is.
-     *
-     * @param fd The file descriptor containing the bitmap data to decode
-     * @param outPadding If not null, return the padding rect for the bitmap if
-     *                   it exists, otherwise set padding to [-1,-1,-1,-1]. If
-     *                   no bitmap is returned (null) then padding is
-     *                   unchanged.
-     * @param opts null-ok; Options that control downsampling and whether the
-     *             image should be completely decoded, or just is size returned.
-     * @return the decoded bitmap, or null
-     */
-    public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {
-        return null;
-
-        /* FIXME: implement as needed
-        try {
-            if (MemoryFile.isMemoryFile(fd)) {
-                int mappedlength = MemoryFile.getMappedSize(fd);
-                MemoryFile file = new MemoryFile(fd, mappedlength, "r");
-                InputStream is = file.getInputStream();
-                Bitmap bm = decodeStream(is, outPadding, opts);
-                return finishDecode(bm, outPadding, opts);
-            }
-        } catch (IOException ex) {
-            // invalid filedescriptor, no need to call nativeDecodeFileDescriptor()
-            return null;
-        }
-        //Bitmap bm = nativeDecodeFileDescriptor(fd, outPadding, opts);
-        //return finishDecode(bm, outPadding, opts);
-        */
-    }
-
-    /**
-     * Decode a bitmap from the file descriptor. If the bitmap cannot be decoded
-     * return null. The position within the descriptor will not be changed when
-     * this returns, so the descriptor can be used again as is.
-     *
-     * @param fd The file descriptor containing the bitmap data to decode
-     * @return the decoded bitmap, or null
-     */
-    public static Bitmap decodeFileDescriptor(FileDescriptor fd) {
-        return decodeFileDescriptor(fd, null, null);
-    }
-}
-
diff --git a/tools/layoutlib/bridge/src/android/graphics/BitmapFactory_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/BitmapFactory_Delegate.java
new file mode 100644
index 0000000..c4fffc86
--- /dev/null
+++ b/tools/layoutlib/bridge/src/android/graphics/BitmapFactory_Delegate.java
@@ -0,0 +1,158 @@
+/*
+ * 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.graphics;
+
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.android.BridgeResources.NinePatchInputStream;
+import com.android.layoutlib.bridge.impl.DelegateManager;
+import com.android.ninepatch.NinePatchChunk;
+import com.android.resources.Density;
+
+import android.graphics.BitmapFactory.Options;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Delegate implementing the native methods of android.graphics.BitmapFactory
+ *
+ * Through the layoutlib_create tool, the original native methods of BitmapFactory have been
+ * replaced by calls to methods of the same name in this delegate class.
+ *
+ * Because it's a stateless class to start with, there's no need to keep a {@link DelegateManager}
+ * around to map int to instance of the delegate.
+ *
+ */
+/*package*/ class BitmapFactory_Delegate {
+
+    // ------ Java delegates ------
+
+    /*package*/ static Bitmap finishDecode(Bitmap bm, Rect outPadding, Options opts) {
+        if (bm == null || opts == null) {
+            return bm;
+        }
+
+        final int density = opts.inDensity;
+        if (density == 0) {
+            return bm;
+        }
+
+        bm.setDensity(density);
+        final int targetDensity = opts.inTargetDensity;
+        if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) {
+            return bm;
+        }
+
+        byte[] np = bm.getNinePatchChunk();
+        final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
+        // DELEGATE CHANGE: never scale 9-patch
+        if (opts.inScaled && isNinePatch == false) {
+            float scale = targetDensity / (float)density;
+            // TODO: This is very inefficient and should be done in native by Skia
+            final Bitmap oldBitmap = bm;
+            bm = Bitmap.createScaledBitmap(oldBitmap, (int) (bm.getWidth() * scale + 0.5f),
+                    (int) (bm.getHeight() * scale + 0.5f), true);
+            oldBitmap.recycle();
+
+            if (isNinePatch) {
+                np = nativeScaleNinePatch(np, scale, outPadding);
+                bm.setNinePatchChunk(np);
+            }
+            bm.setDensity(targetDensity);
+        }
+
+        return bm;
+    }
+
+
+    // ------ Native Delegates ------
+
+    /*package*/ static void nativeSetDefaultConfig(int nativeConfig) {
+        // pass
+    }
+
+    /*package*/ static Bitmap nativeDecodeStream(InputStream is, byte[] storage,
+            Rect padding, Options opts) {
+        Bitmap bm = null;
+
+        Density density = Density.MEDIUM;
+        if (opts != null) {
+            density = Density.getEnum(opts.inDensity);
+        }
+
+        try {
+            if (is instanceof NinePatchInputStream) {
+                NinePatchInputStream npis = (NinePatchInputStream) is;
+                npis.disableFakeMarkSupport();
+
+                // load the bitmap as a nine patch
+                com.android.ninepatch.NinePatch ninePatch = com.android.ninepatch.NinePatch.load(
+                        npis, true /*is9Patch*/, false /*convert*/);
+
+                // get the bitmap and chunk objects.
+                bm = Bitmap_Delegate.createBitmap(ninePatch.getImage(), true /*isMutable*/,
+                        density);
+                NinePatchChunk chunk = ninePatch.getChunk();
+
+                // put the chunk in the bitmap
+                bm.setNinePatchChunk(NinePatch_Delegate.serialize(chunk));
+
+                // read the padding
+                int[] paddingarray = chunk.getPadding();
+                padding.left = paddingarray[0];
+                padding.top = paddingarray[1];
+                padding.right = paddingarray[2];
+                padding.bottom = paddingarray[3];
+            } else {
+                // load the bitmap directly.
+                bm = Bitmap_Delegate.createBitmap(is, true, density);
+            }
+        } catch (IOException e) {
+            Bridge.getLog().error(null,"Failed to load image" , e, null);
+        }
+
+        return bm;
+    }
+
+    /*package*/ static Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,
+            Rect padding, Options opts) {
+        opts.inBitmap = null;
+        return null;
+    }
+
+    /*package*/ static Bitmap nativeDecodeAsset(int asset, Rect padding, Options opts) {
+        opts.inBitmap = null;
+        return null;
+    }
+
+    /*package*/ static Bitmap nativeDecodeByteArray(byte[] data, int offset,
+            int length, Options opts) {
+        opts.inBitmap = null;
+        return null;
+    }
+
+    /*package*/ static byte[] nativeScaleNinePatch(byte[] chunk, float scale, Rect pad) {
+        // don't scale for now. This should not be called anyway since we re-implement
+        // BitmapFactory.finishDecode();
+        return chunk;
+    }
+
+    /*package*/ static boolean nativeIsSeekable(FileDescriptor fd) {
+        return true;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java
index efe6955..3e80614 100644
--- a/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/Bitmap_Delegate.java
@@ -21,6 +21,7 @@
 import com.android.layoutlib.bridge.impl.DelegateManager;
 import com.android.resources.Density;
 
+import android.graphics.Bitmap;
 import android.graphics.Bitmap.Config;
 import android.os.Parcel;
 
diff --git a/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java
index 7a6da95..61ed71e 100644
--- a/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java
@@ -91,6 +91,50 @@
         return array;
     }
 
+    /**
+     * Returns a {@link NinePatchChunk} object for the given serialized representation.
+     *
+     * If the chunk is present in the cache then the object from the cache is returned, otherwise
+     * the array is deserialized into a {@link NinePatchChunk} object.
+     *
+     * @param array the serialized representation of the chunk.
+     * @return the NinePatchChunk or null if deserialization failed.
+     */
+    public static NinePatchChunk getChunk(byte[] array) {
+        SoftReference<NinePatchChunk> chunkRef = sChunkCache.get(array);
+        NinePatchChunk chunk = chunkRef.get();
+        if (chunk == null) {
+            ByteArrayInputStream bais = new ByteArrayInputStream(array);
+            ObjectInputStream ois = null;
+            try {
+                ois = new ObjectInputStream(bais);
+                chunk = (NinePatchChunk) ois.readObject();
+
+                // put back the chunk in the cache
+                if (chunk != null) {
+                    sChunkCache.put(array, new SoftReference<NinePatchChunk>(chunk));
+                }
+            } catch (IOException e) {
+                Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                        "Failed to deserialize NinePatchChunk content.", e, null /*data*/);
+                return null;
+            } catch (ClassNotFoundException e) {
+                Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                        "Failed to deserialize NinePatchChunk class.", e, null /*data*/);
+                return null;
+            } finally {
+                if (ois != null) {
+                    try {
+                        ois.close();
+                    } catch (IOException e) {
+                    }
+                }
+            }
+        }
+
+        return chunk;
+    }
+
     // ---- native methods ----
 
     /*package*/ static boolean isNinePatchChunk(byte[] chunk) {
@@ -173,47 +217,5 @@
 
     // ---- Private Helper methods ----
 
-    /**
-     * Returns a {@link NinePatchChunk} object for the given serialized representation.
-     *
-     * If the chunk is present in the cache then the object from the cache is returned, otherwise
-     * the array is deserialized into a {@link NinePatchChunk} object.
-     *
-     * @param array the serialized representation of the chunk.
-     * @return the NinePatchChunk or null if deserialization failed.
-     */
-    private static NinePatchChunk getChunk(byte[] array) {
-        SoftReference<NinePatchChunk> chunkRef = sChunkCache.get(array);
-        NinePatchChunk chunk = chunkRef.get();
-        if (chunk == null) {
-            ByteArrayInputStream bais = new ByteArrayInputStream(array);
-            ObjectInputStream ois = null;
-            try {
-                ois = new ObjectInputStream(bais);
-                chunk = (NinePatchChunk) ois.readObject();
 
-                // put back the chunk in the cache
-                if (chunk != null) {
-                    sChunkCache.put(array, new SoftReference<NinePatchChunk>(chunk));
-                }
-            } catch (IOException e) {
-                Bridge.getLog().error(LayoutLog.TAG_BROKEN,
-                        "Failed to deserialize NinePatchChunk content.", e, null /*data*/);
-                return null;
-            } catch (ClassNotFoundException e) {
-                Bridge.getLog().error(LayoutLog.TAG_BROKEN,
-                        "Failed to deserialize NinePatchChunk class.", e, null /*data*/);
-                return null;
-            } finally {
-                if (ois != null) {
-                    try {
-                        ois.close();
-                    } catch (IOException e) {
-                    }
-                }
-            }
-        }
-
-        return chunk;
-    }
 }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
index 93c81d1..90dcc27 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
@@ -20,12 +20,14 @@
 import static com.android.ide.common.rendering.api.Result.Status.SUCCESS;
 
 import com.android.ide.common.rendering.api.Capability;
+import com.android.ide.common.rendering.api.DrawableParams;
 import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.ide.common.rendering.api.Params;
 import com.android.ide.common.rendering.api.RenderSession;
 import com.android.ide.common.rendering.api.Result;
+import com.android.ide.common.rendering.api.SessionParams;
 import com.android.layoutlib.bridge.android.BridgeAssetManager;
 import com.android.layoutlib.bridge.impl.FontLoader;
+import com.android.layoutlib.bridge.impl.RenderDrawable;
 import com.android.layoutlib.bridge.impl.RenderSessionImpl;
 import com.android.ninepatch.NinePatchChunk;
 import com.android.resources.ResourceType;
@@ -188,7 +190,7 @@
         // with newer, unsupported capabilities.
         mCapabilities = EnumSet.of(
                 Capability.UNBOUND_RENDERING,
-                Capability.TRANSPARENCY,
+                Capability.CUSTOM_BACKGROUND_COLOR,
                 Capability.RENDER,
                 Capability.EMBEDDED_LAYOUT,
                 Capability.VIEW_MANIPULATION,
@@ -293,15 +295,15 @@
 
     /**
      * Starts a layout session by inflating and rendering it. The method returns a
-     * {@link ILayoutScene} on which further actions can be taken.
+     * {@link RenderSession} on which further actions can be taken.
      *
-     * @param params the {@link SceneParams} object with all the information necessary to create
+     * @param params the {@link SessionParams} object with all the information necessary to create
      *           the scene.
-     * @return a new {@link ILayoutScene} object that contains the result of the layout.
+     * @return a new {@link RenderSession} object that contains the result of the layout.
      * @since 5
      */
     @Override
-    public RenderSession createSession(Params params) {
+    public RenderSession createSession(SessionParams params) {
         try {
             Result lastResult = SUCCESS.createResult();
             RenderSessionImpl scene = new RenderSessionImpl(params);
@@ -331,10 +333,33 @@
         }
     }
 
-    /*
-     * (non-Javadoc)
-     * @see com.android.layoutlib.api.ILayoutLibBridge#clearCaches(java.lang.Object)
-     */
+    @Override
+    public Result renderDrawable(DrawableParams params) {
+        try {
+            Result lastResult = SUCCESS.createResult();
+            RenderDrawable action = new RenderDrawable(params);
+            try {
+                prepareThread();
+                lastResult = action.init(params.getTimeout());
+                if (lastResult.isSuccess()) {
+                    lastResult = action.render();
+                }
+            } finally {
+                action.release();
+                cleanupThread();
+            }
+
+            return lastResult;
+        } catch (Throwable t) {
+            // get the real cause of the exception.
+            Throwable t2 = t;
+            while (t2.getCause() != null) {
+                t2 = t.getCause();
+            }
+            return ERROR_UNKNOWN.createResult(t2.getMessage(), t);
+        }
+    }
+
     @Override
     public void clearCaches(Object projectKey) {
         if (projectKey != null) {
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeRenderSession.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeRenderSession.java
index 0c6fa20..765fd99 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeRenderSession.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeRenderSession.java
@@ -18,7 +18,7 @@
 
 import com.android.ide.common.rendering.api.IAnimationListener;
 import com.android.ide.common.rendering.api.ILayoutPullParser;
-import com.android.ide.common.rendering.api.Params;
+import com.android.ide.common.rendering.api.RenderParams;
 import com.android.ide.common.rendering.api.RenderSession;
 import com.android.ide.common.rendering.api.Result;
 import com.android.ide.common.rendering.api.ViewInfo;
@@ -128,7 +128,7 @@
             boolean isFrameworkAnimation, IAnimationListener listener) {
         try {
             Bridge.prepareThread();
-            mLastResult = mSession.acquire(Params.DEFAULT_TIMEOUT);
+            mLastResult = mSession.acquire(RenderParams.DEFAULT_TIMEOUT);
             if (mLastResult.isSuccess()) {
                 mLastResult = mSession.animate(targetObject, animationName, isFrameworkAnimation,
                         listener);
@@ -150,7 +150,7 @@
 
         try {
             Bridge.prepareThread();
-            mLastResult = mSession.acquire(Params.DEFAULT_TIMEOUT);
+            mLastResult = mSession.acquire(RenderParams.DEFAULT_TIMEOUT);
             if (mLastResult.isSuccess()) {
                 mLastResult = mSession.insertChild((ViewGroup) parentView, childXml, index,
                         listener);
@@ -176,7 +176,7 @@
 
         try {
             Bridge.prepareThread();
-            mLastResult = mSession.acquire(Params.DEFAULT_TIMEOUT);
+            mLastResult = mSession.acquire(RenderParams.DEFAULT_TIMEOUT);
             if (mLastResult.isSuccess()) {
                 mLastResult = mSession.moveChild((ViewGroup) parentView, (View) childView, index,
                         layoutParams, listener);
@@ -197,7 +197,7 @@
 
         try {
             Bridge.prepareThread();
-            mLastResult = mSession.acquire(Params.DEFAULT_TIMEOUT);
+            mLastResult = mSession.acquire(RenderParams.DEFAULT_TIMEOUT);
             if (mLastResult.isSuccess()) {
                 mLastResult = mSession.removeChild((View) childView, listener);
             }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
index bb4c56c..33dd214 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
@@ -176,6 +176,10 @@
         return mProjectKey;
     }
 
+    public DisplayMetrics getMetrics() {
+        return mMetrics;
+    }
+
     public IProjectCallback getProjectCallback() {
         return mProjectCallback;
     }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeResources.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeResources.java
index 5ea0a8d..5e5aeb1 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeResources.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeResources.java
@@ -22,6 +22,7 @@
 import com.android.layoutlib.bridge.Bridge;
 import com.android.layoutlib.bridge.BridgeConstants;
 import com.android.layoutlib.bridge.impl.ResourceHelper;
+import com.android.ninepatch.NinePatch;
 import com.android.resources.ResourceType;
 import com.android.util.Pair;
 
@@ -58,6 +59,35 @@
     private boolean[] mPlatformResourceFlag = new boolean[1];
 
     /**
+     * Simpler wrapper around FileInputStream. This is used when the input stream represent
+     * not a normal bitmap but a nine patch.
+     * This is useful when the InputStream is created in a method but used in another that needs
+     * to know whether this is 9-patch or not, such as BitmapFactory.
+     */
+    public class NinePatchInputStream extends FileInputStream {
+        private boolean mFakeMarkSupport = true;
+        public NinePatchInputStream(File file) throws FileNotFoundException {
+            super(file);
+        }
+
+        @Override
+        public boolean markSupported() {
+            if (mFakeMarkSupport) {
+                // this is needed so that BitmapFactory doesn't wrap this in a BufferedInputStream.
+                return true;
+            }
+
+            return super.markSupported();
+        }
+
+        public void disableFakeMarkSupport() {
+            // disable fake mark support so that in case codec actually try to use them
+            // we don't lie to them.
+            mFakeMarkSupport = false;
+        }
+    }
+
+    /**
      * This initializes the static field {@link Resources#mSystem} which is used
      * by methods who get global resources using {@link Resources#getSystem()}.
      * <p/>
@@ -129,7 +159,7 @@
         ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
-            return ResourceHelper.getDrawable(value, mContext, value.isFramework());
+            return ResourceHelper.getDrawable(value, mContext);
         }
 
         // id was not found or not resolved. Throw a NotFoundException.
@@ -165,44 +195,9 @@
         ResourceValue resValue = getResourceValue(id, mPlatformResourceFlag);
 
         if (resValue != null) {
-            String value = resValue.getValue();
-            if (value != null) {
-                // first check if the value is a file (xml most likely)
-                File f = new File(value);
-                if (f.isFile()) {
-                    try {
-                        // let the framework inflate the ColorStateList from the XML file, by
-                        // providing an XmlPullParser
-                        KXmlParser parser = new KXmlParser();
-                        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
-                        parser.setInput(new FileReader(f));
-
-                        return ColorStateList.createFromXml(this,
-                                new BridgeXmlBlockParser(parser, mContext, resValue.isFramework()));
-                    } catch (XmlPullParserException e) {
-                        Bridge.getLog().error(LayoutLog.TAG_BROKEN,
-                                "Failed to configure parser for " + value, e, null /*data*/);
-                        // we'll return null below.
-                    } catch (Exception e) {
-                        // this is an error and not warning since the file existence is
-                        // checked before attempting to parse it.
-                        Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ,
-                                "Failed to parse file " + value, e, null /*data*/);
-
-                        return null;
-                    }
-                } else {
-                    // try to load the color state list from an int
-                    try {
-                        int color = ResourceHelper.getColor(value);
-                        return ColorStateList.valueOf(color);
-                    } catch (NumberFormatException e) {
-                        Bridge.getLog().error(LayoutLog.TAG_RESOURCES_FORMAT,
-                                "Failed to convert " + value + " into a ColorStateList", e,
-                                null /*data*/);
-                        return null;
-                    }
-                }
+            ColorStateList stateList = ResourceHelper.getColorStateList(resValue, mContext);
+            if (stateList != null) {
+                return stateList;
             }
         }
 
@@ -562,13 +557,19 @@
         ResourceValue value = getResourceValue(id, mPlatformResourceFlag);
 
         if (value != null) {
-            String v = value.getValue();
+            String path = value.getValue();
 
-            if (v != null) {
+            if (path != null) {
                 // check this is a file
-                File f = new File(value.getValue());
+                File f = new File(path);
                 if (f.isFile()) {
                     try {
+                        // if it's a nine-patch return a custom input stream so that
+                        // other methods (mainly bitmap factory) can detect it's a 9-patch
+                        // and actually load it as a 9-patch instead of a normal bitmap
+                        if (path.toLowerCase().endsWith(NinePatch.EXTENSION_9PATCH)) {
+                            return new NinePatchInputStream(f);
+                        }
                         return new FileInputStream(f);
                     } catch (FileNotFoundException e) {
                         NotFoundException newE = new NotFoundException();
@@ -590,9 +591,17 @@
     public InputStream openRawResource(int id, TypedValue value) throws NotFoundException {
         getValue(id, value, true);
 
-        File f = new File(value.string.toString());
+        String path = value.string.toString();
+
+        File f = new File(path);
         if (f.isFile()) {
             try {
+                // if it's a nine-patch return a custom input stream so that
+                // other methods (mainly bitmap factory) can detect it's a 9-patch
+                // and actually load it as a 9-patch instead of a normal bitmap
+                if (path.toLowerCase().endsWith(NinePatch.EXTENSION_9PATCH)) {
+                    return new NinePatchInputStream(f);
+                }
                 return new FileInputStream(f);
             } catch (FileNotFoundException e) {
                 NotFoundException exception = new NotFoundException();
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeTypedArray.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeTypedArray.java
index cf2c0ff..15c4f44 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeTypedArray.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeTypedArray.java
@@ -270,13 +270,10 @@
             return defValue;
         }
 
-        String s = mResourceData[index].getValue();
-        try {
-            return ResourceHelper.getColor(s);
-        } catch (NumberFormatException e) {
-            Bridge.getLog().error(LayoutLog.TAG_RESOURCES_FORMAT, e.getMessage(), e, null /*data*/);
-
-            // we'll return the default value below.
+        ColorStateList colorStateList = ResourceHelper.getColorStateList(
+                mResourceData[index], mContext);
+        if (colorStateList != null) {
+            return colorStateList.getDefaultColor();
         }
 
         return defValue;
@@ -690,7 +687,7 @@
             return null;
         }
 
-        return ResourceHelper.getDrawable(value, mContext, mResourceData[index].isFramework());
+        return ResourceHelper.getDrawable(value, mContext);
     }
 
 
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/CustomBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/CustomBar.java
new file mode 100644
index 0000000..70c507c
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/CustomBar.java
@@ -0,0 +1,260 @@
+/*
+ * 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.layoutlib.bridge.bars;
+
+import com.android.ide.common.rendering.api.RenderResources;
+import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.ide.common.rendering.api.StyleResourceValue;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.android.BridgeContext;
+import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
+import com.android.layoutlib.bridge.impl.ResourceHelper;
+import com.android.resources.Density;
+import com.android.resources.ResourceType;
+
+import org.kxml2.io.KXmlParser;
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.content.Context;
+import android.content.res.ColorStateList;
+import android.graphics.Bitmap;
+import android.graphics.Bitmap_Delegate;
+import android.graphics.drawable.BitmapDrawable;
+import android.graphics.drawable.Drawable;
+import android.util.TypedValue;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Base "bar" class for the window decor around the the edited layout.
+ * This is basically an horizontal layout that loads a given layout on creation (it is read
+ * through {@link Class#getResourceAsStream(String)}).
+ *
+ * The given layout should be a merge layout so that all the children belong to this class directly.
+ *
+ * It also provides a few utility methods to configure the content of the layout.
+ */
+abstract class CustomBar extends LinearLayout {
+
+    protected abstract TextView getStyleableTextView();
+
+    protected CustomBar(Context context, Density density, String layoutPath)
+            throws XmlPullParserException {
+        super(context);
+        setOrientation(LinearLayout.HORIZONTAL);
+        setGravity(Gravity.CENTER_VERTICAL);
+        setBackgroundColor(0xFF000000);
+
+        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(
+                Context.LAYOUT_INFLATER_SERVICE);
+
+        KXmlParser parser = new KXmlParser();
+        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
+        parser.setInput(
+                getClass().getResourceAsStream(layoutPath),
+                "UTF8");
+
+        BridgeXmlBlockParser bridgeParser = new BridgeXmlBlockParser(
+                parser, (BridgeContext) context, false);
+
+        inflater.inflate(bridgeParser, this, true);
+    }
+
+    private InputStream getIcon(String iconName, Density[] densityInOut, String[] pathOut,
+            boolean tryOtherDensities) {
+        // current density
+        Density density = densityInOut[0];
+
+        // bitmap url relative to this class
+        pathOut[0] = "/bars/" + density.getResourceValue() + "/" + iconName;
+
+        InputStream stream = getClass().getResourceAsStream(pathOut[0]);
+        if (stream == null && tryOtherDensities) {
+            for (Density d : Density.values()) {
+                if (d != density) {
+                    densityInOut[0] = d;
+                    stream = getIcon(iconName, densityInOut, pathOut, false /*tryOtherDensities*/);
+                    if (stream != null) {
+                        return stream;
+                    }
+                }
+            }
+        }
+
+        return stream;
+    }
+
+    protected void loadIcon(int index, String iconName, Density density) {
+        View child = getChildAt(index);
+        if (child instanceof ImageView) {
+            ImageView imageView = (ImageView) child;
+
+            String[] pathOut = new String[1];
+            Density[] densityInOut = new Density[] { density };
+            InputStream stream = getIcon(iconName, densityInOut, pathOut,
+                    true /*tryOtherDensities*/);
+            density = densityInOut[0];
+
+            if (stream != null) {
+                // look for a cached bitmap
+                Bitmap bitmap = Bridge.getCachedBitmap(pathOut[0], true /*isFramework*/);
+                if (bitmap == null) {
+                    try {
+                        bitmap = Bitmap_Delegate.createBitmap(stream, false /*isMutable*/, density);
+                        Bridge.setCachedBitmap(pathOut[0], bitmap, true /*isFramework*/);
+                    } catch (IOException e) {
+                        return;
+                    }
+                }
+
+                if (bitmap != null) {
+                    BitmapDrawable drawable = new BitmapDrawable(getContext().getResources(),
+                            bitmap);
+                    imageView.setBackgroundDrawable(drawable);
+                }
+            }
+        }
+    }
+
+    protected void loadIcon(int index, String iconReference) {
+        ResourceValue value = getResourceValue(iconReference);
+        if (value != null) {
+            loadIcon(index, value);
+        }
+    }
+
+    protected Drawable loadIcon(int index, ResourceType type, String name) {
+        BridgeContext bridgeContext = (BridgeContext) mContext;
+        RenderResources res = bridgeContext.getRenderResources();
+
+        // find the resource
+        ResourceValue value = res.getFrameworkResource(type, name);
+
+        // resolve it if needed
+        value = res.resolveResValue(value);
+        return loadIcon(index, value);
+    }
+
+    private Drawable loadIcon(int index, ResourceValue value) {
+        View child = getChildAt(index);
+        if (child instanceof ImageView) {
+            ImageView imageView = (ImageView) child;
+
+            Drawable drawable = ResourceHelper.getDrawable(
+                    value, (BridgeContext) mContext);
+            if (drawable != null) {
+                imageView.setBackgroundDrawable(drawable);
+            }
+
+            return drawable;
+        }
+
+        return null;
+    }
+
+    protected TextView setText(int index, String stringReference) {
+        View child = getChildAt(index);
+        if (child instanceof TextView) {
+            TextView textView = (TextView) child;
+            ResourceValue value = getResourceValue(stringReference);
+            if (value != null) {
+                textView.setText(value.getValue());
+            } else {
+                textView.setText(stringReference);
+            }
+            return textView;
+        }
+
+        return null;
+    }
+
+    protected void setStyle(String themeEntryName) {
+
+        BridgeContext bridgeContext = (BridgeContext) mContext;
+        RenderResources res = bridgeContext.getRenderResources();
+
+        ResourceValue value = res.findItemInTheme(themeEntryName);
+        value = res.resolveResValue(value);
+
+        if (value instanceof StyleResourceValue == false) {
+            return;
+        }
+
+        StyleResourceValue style = (StyleResourceValue) value;
+
+        // get the background
+        ResourceValue backgroundValue = res.findItemInStyle(style, "background");
+        backgroundValue = res.resolveResValue(backgroundValue);
+        if (backgroundValue != null) {
+            Drawable d = ResourceHelper.getDrawable(backgroundValue, bridgeContext);
+            if (d != null) {
+                setBackgroundDrawable(d);
+            }
+        }
+
+        TextView textView = getStyleableTextView();
+        if (textView != null) {
+            // get the text style
+            ResourceValue textStyleValue = res.findItemInStyle(style, "titleTextStyle");
+            textStyleValue = res.resolveResValue(textStyleValue);
+            if (textStyleValue instanceof StyleResourceValue) {
+                StyleResourceValue textStyle = (StyleResourceValue) textStyleValue;
+
+                ResourceValue textSize = res.findItemInStyle(textStyle, "textSize");
+                textSize = res.resolveResValue(textSize);
+
+                if (textSize != null) {
+                    TypedValue out = new TypedValue();
+                    if (ResourceHelper.stringToFloat(textSize.getValue(), out)) {
+                        textView.setTextSize(
+                                out.getDimension(bridgeContext.getResources().mMetrics));
+                    }
+                }
+
+
+                ResourceValue textColor = res.findItemInStyle(textStyle, "textColor");
+                textColor = res.resolveResValue(textColor);
+                if (textColor != null) {
+                    ColorStateList stateList = ResourceHelper.getColorStateList(
+                            textColor, bridgeContext);
+                    if (stateList != null) {
+                        textView.setTextColor(stateList);
+                    }
+                }
+            }
+        }
+    }
+
+    private ResourceValue getResourceValue(String reference) {
+        BridgeContext bridgeContext = (BridgeContext) mContext;
+        RenderResources res = bridgeContext.getRenderResources();
+
+        // find the resource
+        ResourceValue value = res.findResValue(reference, false /*isFramework*/);
+
+        // resolve it if needed
+        return res.resolveResValue(value);
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/FakeActionBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/FakeActionBar.java
new file mode 100644
index 0000000..3af4e3a
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/FakeActionBar.java
@@ -0,0 +1,47 @@
+/*
+ * 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.layoutlib.bridge.bars;
+
+import com.android.resources.Density;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.content.Context;
+import android.widget.TextView;
+
+public class FakeActionBar extends CustomBar {
+
+    private TextView mTextView;
+
+    public FakeActionBar(Context context, Density density, String label, String icon)
+            throws XmlPullParserException {
+        super(context, density, "/bars/action_bar.xml");
+
+        // Cannot access the inside items through id because no R.id values have been
+        // created for them.
+        // We do know the order though.
+        loadIcon(0, icon);
+        mTextView = setText(1, label);
+
+        setStyle("actionBarStyle");
+    }
+
+    @Override
+    protected TextView getStyleableTextView() {
+        return mTextView;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/PhoneSystemBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/PhoneSystemBar.java
new file mode 100644
index 0000000..e3022b4
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/PhoneSystemBar.java
@@ -0,0 +1,52 @@
+/*
+ * 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.layoutlib.bridge.bars;
+
+import com.android.resources.Density;
+import com.android.resources.ResourceType;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.content.Context;
+import android.graphics.drawable.Drawable;
+import android.graphics.drawable.LevelListDrawable;
+import android.view.Gravity;
+import android.widget.TextView;
+
+public class PhoneSystemBar extends CustomBar {
+
+    public PhoneSystemBar(Context context, Density density) throws XmlPullParserException {
+        super(context, density, "/bars/tablet_system_bar.xml");
+
+        setGravity(mGravity | Gravity.RIGHT);
+
+        // Cannot access the inside items through id because no R.id values have been
+        // created for them.
+        // We do know the order though.
+        // 0 is the spacer
+        loadIcon(1, "stat_sys_wifi_signal_4_fully.png", density);
+        Drawable drawable = loadIcon(2, ResourceType.DRAWABLE, "stat_sys_battery_charge");
+        if (drawable instanceof LevelListDrawable) {
+            ((LevelListDrawable) drawable).setLevel(100);
+        }
+    }
+
+    @Override
+    protected TextView getStyleableTextView() {
+        return null;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TabletSystemBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TabletSystemBar.java
new file mode 100644
index 0000000..db1efdb
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TabletSystemBar.java
@@ -0,0 +1,52 @@
+/*
+ * 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.layoutlib.bridge.bars;
+
+import com.android.resources.Density;
+import com.android.resources.ResourceType;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.content.Context;
+import android.graphics.drawable.Drawable;
+import android.graphics.drawable.LevelListDrawable;
+import android.widget.TextView;
+
+public class TabletSystemBar extends CustomBar {
+
+    public TabletSystemBar(Context context, Density density) throws XmlPullParserException {
+        super(context, density, "/bars/tablet_system_bar.xml");
+
+        // Cannot access the inside items through id because no R.id values have been
+        // created for them.
+        // We do know the order though.
+        loadIcon(0, "ic_sysbar_back_default.png", density);
+        loadIcon(1, "ic_sysbar_home_default.png", density);
+        loadIcon(2, "ic_sysbar_recent_default.png", density);
+        // 3 is the spacer
+        loadIcon(4, "stat_sys_wifi_signal_4_fully.png", density);
+        Drawable drawable = loadIcon(5, ResourceType.DRAWABLE, "stat_sys_battery_charge");
+        if (drawable instanceof LevelListDrawable) {
+            ((LevelListDrawable) drawable).setLevel(100);
+        }
+    }
+
+    @Override
+    protected TextView getStyleableTextView() {
+        return null;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TitleBar.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TitleBar.java
new file mode 100644
index 0000000..d7401d9
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/bars/TitleBar.java
@@ -0,0 +1,46 @@
+/*
+ * 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.layoutlib.bridge.bars;
+
+import com.android.resources.Density;
+
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.content.Context;
+import android.widget.TextView;
+
+public class TitleBar extends CustomBar {
+
+    private TextView mTextView;
+
+    public TitleBar(Context context, Density density, String label)
+            throws XmlPullParserException {
+        super(context, density, "/bars/title_bar.xml");
+
+        // Cannot access the inside items through id because no R.id values have been
+        // created for them.
+        // We do know the order though.
+        mTextView = setText(0, label);
+
+        setStyle("windowTitleBackgroundStyle");
+    }
+
+    @Override
+    protected TextView getStyleableTextView() {
+        return mTextView;
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderAction.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderAction.java
new file mode 100644
index 0000000..8e80c21
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderAction.java
@@ -0,0 +1,285 @@
+/*
+ * 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.
+ */
+
+package com.android.layoutlib.bridge.impl;
+
+import static com.android.ide.common.rendering.api.Result.Status.ERROR_LOCK_INTERRUPTED;
+import static com.android.ide.common.rendering.api.Result.Status.ERROR_TIMEOUT;
+import static com.android.ide.common.rendering.api.Result.Status.SUCCESS;
+
+import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.ide.common.rendering.api.RenderParams;
+import com.android.ide.common.rendering.api.RenderResources;
+import com.android.ide.common.rendering.api.Result;
+import com.android.ide.common.rendering.api.RenderResources.FrameworkResourceIdProvider;
+import com.android.layoutlib.bridge.Bridge;
+import com.android.layoutlib.bridge.android.BridgeContext;
+import com.android.resources.ResourceType;
+
+import android.util.DisplayMetrics;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * Base class for rendering action.
+ *
+ * It provides life-cycle methods to init and stop the rendering.
+ * The most important methods are:
+ * {@link #init(long)} and {@link #acquire(long)} to start a rendering and {@link #release()}
+ * after the rendering.
+ *
+ *
+ * @param <T> the {@link RenderParams} implementation
+ *
+ */
+public abstract class RenderAction<T extends RenderParams> extends FrameworkResourceIdProvider {
+
+    /**
+     * The current context being rendered. This is set through {@link #acquire(long)} and
+     * {@link #init(long)}, and unset in {@link #release()}.
+     */
+    private static BridgeContext sCurrentContext = null;
+
+    private final T mParams;
+
+    private BridgeContext mContext;
+
+    /**
+     * Creates a renderAction.
+     * <p>
+     * This <b>must</b> be followed by a call to {@link RenderAction#init()}, which act as a
+     * call to {@link RenderAction#acquire(long)}
+     *
+     * @param params the RenderParams. This must be a copy that the action can keep
+     *
+     */
+    protected RenderAction(T params) {
+        mParams = params;
+    }
+
+    /**
+     * Initializes and acquires the scene, creating various Android objects such as context,
+     * inflater, and parser.
+     *
+     * @param timeout the time to wait if another rendering is happening.
+     *
+     * @return whether the scene was prepared
+     *
+     * @see #acquire(long)
+     * @see #release()
+     */
+    public Result init(long timeout) {
+        // acquire the lock. if the result is null, lock was just acquired, otherwise, return
+        // the result.
+        Result result = acquireLock(timeout);
+        if (result != null) {
+            return result;
+        }
+
+        // setup the display Metrics.
+        DisplayMetrics metrics = new DisplayMetrics();
+        metrics.densityDpi = mParams.getDensity().getDpiValue();
+        metrics.density = metrics.densityDpi / (float) DisplayMetrics.DENSITY_DEFAULT;
+        metrics.scaledDensity = metrics.density;
+        metrics.widthPixels = mParams.getScreenWidth();
+        metrics.heightPixels = mParams.getScreenHeight();
+        metrics.xdpi = mParams.getXdpi();
+        metrics.ydpi = mParams.getYdpi();
+
+        RenderResources resources = mParams.getResources();
+
+        // build the context
+        mContext = new BridgeContext(mParams.getProjectKey(), metrics, resources,
+                mParams.getProjectCallback(), mParams.getTargetSdkVersion());
+
+        setUp();
+
+        return SUCCESS.createResult();
+    }
+
+    /**
+     * Prepares the scene for action.
+     * <p>
+     * This call is blocking if another rendering/inflating is currently happening, and will return
+     * whether the preparation worked.
+     *
+     * The preparation can fail if another rendering took too long and the timeout was elapsed.
+     *
+     * More than one call to this from the same thread will have no effect and will return
+     * {@link Result#SUCCESS}.
+     *
+     * After scene actions have taken place, only one call to {@link #release()} must be
+     * done.
+     *
+     * @param timeout the time to wait if another rendering is happening.
+     *
+     * @return whether the scene was prepared
+     *
+     * @see #release()
+     *
+     * @throws IllegalStateException if {@link #init(long)} was never called.
+     */
+    public Result acquire(long timeout) {
+        if (mContext == null) {
+            throw new IllegalStateException("After scene creation, #init() must be called");
+        }
+
+        // acquire the lock. if the result is null, lock was just acquired, otherwise, return
+        // the result.
+        Result result = acquireLock(timeout);
+        if (result != null) {
+            return result;
+        }
+
+        setUp();
+
+        return SUCCESS.createResult();
+    }
+
+    /**
+     * Acquire the lock so that the scene can be acted upon.
+     * <p>
+     * This returns null if the lock was just acquired, otherwise it returns
+     * {@link Result#SUCCESS} if the lock already belonged to that thread, or another
+     * instance (see {@link Result#getStatus()}) if an error occurred.
+     *
+     * @param timeout the time to wait if another rendering is happening.
+     * @return null if the lock was just acquire or another result depending on the state.
+     *
+     * @throws IllegalStateException if the current context is different than the one owned by
+     *      the scene.
+     */
+    private Result acquireLock(long timeout) {
+        ReentrantLock lock = Bridge.getLock();
+        if (lock.isHeldByCurrentThread() == false) {
+            try {
+                boolean acquired = lock.tryLock(timeout, TimeUnit.MILLISECONDS);
+
+                if (acquired == false) {
+                    return ERROR_TIMEOUT.createResult();
+                }
+            } catch (InterruptedException e) {
+                return ERROR_LOCK_INTERRUPTED.createResult();
+            }
+        } else {
+            // This thread holds the lock already. Checks that this wasn't for a different context.
+            // If this is called by init, mContext will be null and so should sCurrentContext
+            // anyway
+            if (mContext != sCurrentContext) {
+                throw new IllegalStateException("Acquiring different scenes from same thread without releases");
+            }
+            return SUCCESS.createResult();
+        }
+
+        return null;
+    }
+
+    /**
+     * Cleans up the scene after an action.
+     */
+    public void release() {
+        ReentrantLock lock = Bridge.getLock();
+
+        // with the use of finally blocks, it is possible to find ourself calling this
+        // without a successful call to prepareScene. This test makes sure that unlock() will
+        // not throw IllegalMonitorStateException.
+        if (lock.isHeldByCurrentThread()) {
+            tearDown();
+            lock.unlock();
+        }
+    }
+
+    /**
+     * Sets up the session for rendering.
+     * <p/>
+     * The counterpart is {@link #tearDown()}.
+     */
+    private void setUp() {
+        // make sure the Resources object references the context (and other objects) for this
+        // scene
+        mContext.initResources();
+        sCurrentContext = mContext;
+
+        LayoutLog currentLog = mParams.getLog();
+        Bridge.setLog(currentLog);
+        mContext.getRenderResources().setFrameworkResourceIdProvider(this);
+        mContext.getRenderResources().setLogger(currentLog);
+    }
+
+    /**
+     * Tear down the session after rendering.
+     * <p/>
+     * The counterpart is {@link #setUp()}.
+     */
+    private void tearDown() {
+        // Make sure to remove static references, otherwise we could not unload the lib
+        mContext.disposeResources();
+        sCurrentContext = null;
+
+        Bridge.setLog(null);
+        mContext.getRenderResources().setFrameworkResourceIdProvider(null);
+        mContext.getRenderResources().setLogger(null);
+    }
+
+    public static BridgeContext getCurrentContext() {
+        return sCurrentContext;
+    }
+
+    protected T getParams() {
+        return mParams;
+    }
+
+    protected BridgeContext getContext() {
+        return mContext;
+    }
+
+    /**
+     * Returns the log associated with the session.
+     * @return the log or null if there are none.
+     */
+    public LayoutLog getLog() {
+        if (mParams != null) {
+            return mParams.getLog();
+        }
+
+        return null;
+    }
+
+    /**
+     * Checks that the lock is owned by the current thread and that the current context is the one
+     * from this scene.
+     *
+     * @throws IllegalStateException if the current context is different than the one owned by
+     *      the scene, or if {@link #acquire(long)} was not called.
+     */
+    protected void checkLock() {
+        ReentrantLock lock = Bridge.getLock();
+        if (lock.isHeldByCurrentThread() == false) {
+            throw new IllegalStateException("scene must be acquired first. see #acquire(long)");
+        }
+        if (sCurrentContext != mContext) {
+            throw new IllegalStateException("Thread acquired a scene but is rendering a different one");
+        }
+    }
+
+    // --- FrameworkResourceIdProvider methods
+
+    @Override
+    public Integer getId(ResourceType resType, String resName) {
+        return Bridge.getResourceId(resType, resName);
+    }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderDrawable.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderDrawable.java
new file mode 100644
index 0000000..953d8cf
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderDrawable.java
@@ -0,0 +1,141 @@
+/*
+ * 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.layoutlib.bridge.impl;
+
+import static com.android.ide.common.rendering.api.Result.Status.ERROR_UNKNOWN;
+
+import com.android.ide.common.rendering.api.DrawableParams;
+import com.android.ide.common.rendering.api.ResourceValue;
+import com.android.ide.common.rendering.api.Result;
+import com.android.ide.common.rendering.api.Result.Status;
+import com.android.layoutlib.bridge.android.BridgeContext;
+import com.android.layoutlib.bridge.android.BridgeWindow;
+import com.android.layoutlib.bridge.android.BridgeWindowSession;
+import com.android.resources.ResourceType;
+
+import android.graphics.Bitmap;
+import android.graphics.Bitmap_Delegate;
+import android.graphics.Canvas;
+import android.graphics.drawable.Drawable;
+import android.os.Handler;
+import android.view.View;
+import android.view.View.AttachInfo;
+import android.view.View.MeasureSpec;
+import android.widget.FrameLayout;
+
+import java.awt.AlphaComposite;
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+
+/**
+ * Action to render a given Drawable provided through {@link DrawableParams#getDrawable()}.
+ *
+ * The class only provides a simple {@link #render()} method, but the full life-cycle of the
+ * action must be respected.
+ *
+ * @see RenderAction
+ *
+ */
+public class RenderDrawable extends RenderAction<DrawableParams> {
+
+    public RenderDrawable(DrawableParams params) {
+        super(new DrawableParams(params));
+    }
+
+    public Result render() {
+        checkLock();
+        try {
+            // get the drawable resource value
+            DrawableParams params = getParams();
+            ResourceValue drawableResource = params.getDrawable();
+
+            // resolve it
+            BridgeContext context = getContext();
+            drawableResource = context.getRenderResources().resolveResValue(drawableResource);
+
+            if (drawableResource == null ||
+                    drawableResource.getResourceType() != ResourceType.DRAWABLE) {
+                return Status.ERROR_NOT_A_DRAWABLE.createResult();
+            }
+
+            // create a simple FrameLayout
+            FrameLayout content = new FrameLayout(context);
+
+            // get the actual Drawable object to draw
+            Drawable d = ResourceHelper.getDrawable(drawableResource, context);
+            content.setBackgroundDrawable(d);
+
+            // set the AttachInfo on the root view.
+            AttachInfo info = new AttachInfo(new BridgeWindowSession(), new BridgeWindow(),
+                    new Handler(), null);
+            info.mHasWindowFocus = true;
+            info.mWindowVisibility = View.VISIBLE;
+            info.mInTouchMode = false; // this is so that we can display selections.
+            info.mHardwareAccelerated = false;
+            content.dispatchAttachedToWindow(info, 0);
+
+
+            // measure
+            int w = params.getScreenWidth();
+            int h = params.getScreenHeight();
+            int w_spec = MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY);
+            int h_spec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
+            content.measure(w_spec, h_spec);
+
+            // now do the layout.
+            content.layout(0, 0, w, h);
+
+            // preDraw setup
+            content.mAttachInfo.mTreeObserver.dispatchOnPreDraw();
+
+            // draw into a new image
+            BufferedImage image = getImage(w, h);
+
+            // create an Android bitmap around the BufferedImage
+            Bitmap bitmap = Bitmap_Delegate.createBitmap(image,
+                    true /*isMutable*/, params.getDensity());
+
+            // create a Canvas around the Android bitmap
+            Canvas canvas = new Canvas(bitmap);
+            canvas.setDensity(params.getDensity().getDpiValue());
+
+            // and draw
+            content.draw(canvas);
+
+            return Status.SUCCESS.createResult(image);
+        } catch (IOException e) {
+            return ERROR_UNKNOWN.createResult(e.getMessage(), e);
+        }
+    }
+
+    protected BufferedImage getImage(int w, int h) {
+        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
+        Graphics2D gc = image.createGraphics();
+        gc.setComposite(AlphaComposite.Src);
+
+        gc.setColor(new Color(0x00000000, true));
+        gc.fillRect(0, 0, w, h);
+
+        // done
+        gc.dispose();
+
+        return image;
+    }
+
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java
index c8ad1d6..3e5127e 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java
@@ -18,9 +18,7 @@
 
 import static com.android.ide.common.rendering.api.Result.Status.ERROR_ANIM_NOT_FOUND;
 import static com.android.ide.common.rendering.api.Result.Status.ERROR_INFLATION;
-import static com.android.ide.common.rendering.api.Result.Status.ERROR_LOCK_INTERRUPTED;
 import static com.android.ide.common.rendering.api.Result.Status.ERROR_NOT_INFLATED;
-import static com.android.ide.common.rendering.api.Result.Status.ERROR_TIMEOUT;
 import static com.android.ide.common.rendering.api.Result.Status.ERROR_UNKNOWN;
 import static com.android.ide.common.rendering.api.Result.Status.ERROR_VIEWGROUP_NO_CHILDREN;
 import static com.android.ide.common.rendering.api.Result.Status.SUCCESS;
@@ -28,17 +26,15 @@
 import com.android.ide.common.rendering.api.IAnimationListener;
 import com.android.ide.common.rendering.api.ILayoutPullParser;
 import com.android.ide.common.rendering.api.IProjectCallback;
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.ide.common.rendering.api.Params;
+import com.android.ide.common.rendering.api.RenderParams;
 import com.android.ide.common.rendering.api.RenderResources;
 import com.android.ide.common.rendering.api.RenderSession;
 import com.android.ide.common.rendering.api.ResourceValue;
 import com.android.ide.common.rendering.api.Result;
-import com.android.ide.common.rendering.api.StyleResourceValue;
+import com.android.ide.common.rendering.api.SessionParams;
 import com.android.ide.common.rendering.api.ViewInfo;
-import com.android.ide.common.rendering.api.Params.RenderingMode;
-import com.android.ide.common.rendering.api.RenderResources.FrameworkResourceIdProvider;
 import com.android.ide.common.rendering.api.Result.Status;
+import com.android.ide.common.rendering.api.SessionParams.RenderingMode;
 import com.android.internal.util.XmlUtils;
 import com.android.layoutlib.bridge.Bridge;
 import com.android.layoutlib.bridge.android.BridgeContext;
@@ -47,11 +43,16 @@
 import com.android.layoutlib.bridge.android.BridgeWindow;
 import com.android.layoutlib.bridge.android.BridgeWindowSession;
 import com.android.layoutlib.bridge.android.BridgeXmlBlockParser;
-import com.android.resources.Density;
+import com.android.layoutlib.bridge.bars.FakeActionBar;
+import com.android.layoutlib.bridge.bars.PhoneSystemBar;
+import com.android.layoutlib.bridge.bars.TabletSystemBar;
+import com.android.layoutlib.bridge.bars.TitleBar;
 import com.android.resources.ResourceType;
 import com.android.resources.ScreenSize;
 import com.android.util.Pair;
 
+import org.xmlpull.v1.XmlPullParserException;
+
 import android.animation.Animator;
 import android.animation.AnimatorInflater;
 import android.animation.LayoutTransition;
@@ -83,8 +84,6 @@
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.ReentrantLock;
 
 /**
  * Class implementing the render session.
@@ -94,36 +93,28 @@
  * be done on the layout.
  *
  */
-public class RenderSessionImpl extends FrameworkResourceIdProvider {
+public class RenderSessionImpl extends RenderAction<SessionParams> {
 
     private static final int DEFAULT_TITLE_BAR_HEIGHT = 25;
     private static final int DEFAULT_STATUS_BAR_HEIGHT = 25;
 
-    /**
-     * The current context being rendered. This is set through {@link #acquire(long)} and
-     * {@link #init(long)}, and unset in {@link #release()}.
-     */
-    private static BridgeContext sCurrentContext = null;
-
-    private final Params mParams;
-
     // scene state
     private RenderSession mScene;
-    private BridgeContext mContext;
     private BridgeXmlBlockParser mBlockParser;
     private BridgeInflater mInflater;
     private ResourceValue mWindowBackground;
-    private FrameLayout mViewRoot;
+    private ViewGroup mViewRoot;
+    private FrameLayout mContentRoot;
     private Canvas mCanvas;
     private int mMeasuredScreenWidth = -1;
     private int mMeasuredScreenHeight = -1;
-    private boolean mIsAlphaChannelImage = true;
+    private boolean mIsAlphaChannelImage;
+    private boolean mWindowIsFloating;
 
     private int mStatusBarSize;
-    private int mTopBarSize;
     private int mSystemBarSize;
-    private int mTopOffset;
-    private int mTotalBarSize;
+    private int mTitleBarSize;
+    private int mActionBarSize;
 
 
     // information being returned through the API
@@ -146,9 +137,8 @@
      *
      * @see LayoutBridge#createScene(com.android.layoutlib.api.SceneParams)
      */
-    public RenderSessionImpl(Params params) {
-        // copy the params.
-        mParams = new Params(params);
+    public RenderSessionImpl(SessionParams params) {
+        super(new SessionParams(params));
     }
 
     /**
@@ -162,185 +152,43 @@
      * @see #acquire(long)
      * @see #release()
      */
+    @Override
     public Result init(long timeout) {
-        // acquire the lock. if the result is null, lock was just acquired, otherwise, return
-        // the result.
-        Result result = acquireLock(timeout);
-        if (result != null) {
+        Result result = super.init(timeout);
+        if (result.isSuccess() == false) {
             return result;
         }
 
-        // setup the display Metrics.
-        DisplayMetrics metrics = new DisplayMetrics();
-        metrics.densityDpi = mParams.getDensity();
-        metrics.density = mParams.getDensity() / (float) DisplayMetrics.DENSITY_DEFAULT;
-        metrics.scaledDensity = metrics.density;
-        metrics.widthPixels = mParams.getScreenWidth();
-        metrics.heightPixels = mParams.getScreenHeight();
-        metrics.xdpi = mParams.getXdpi();
-        metrics.ydpi = mParams.getYdpi();
+        SessionParams params = getParams();
+        BridgeContext context = getContext();
 
-        RenderResources resources = mParams.getResources();
-
-        // build the context
-        mContext = new BridgeContext(mParams.getProjectKey(), metrics, resources,
-                mParams.getProjectCallback(), mParams.getTargetSdkVersion());
+        RenderResources resources = getParams().getResources();
+        DisplayMetrics metrics = getContext().getMetrics();
 
         // use default of true in case it's not found to use alpha by default
         mIsAlphaChannelImage  = getBooleanThemeValue(resources,
                 "windowIsFloating", true /*defaultValue*/);
 
-
-        setUp();
+        mWindowIsFloating = getBooleanThemeValue(resources, "windowIsFloating",
+                true /*defaultValue*/);
 
         findBackground(resources);
         findStatusBar(resources, metrics);
-        findTopBar(resources, metrics);
+        findActionBar(resources, metrics);
         findSystemBar(resources, metrics);
 
-        mTopOffset = mStatusBarSize + mTopBarSize;
-        mTotalBarSize = mTopOffset + mSystemBarSize;
-
         // build the inflater and parser.
-        mInflater = new BridgeInflater(mContext, mParams.getProjectCallback());
-        mContext.setBridgeInflater(mInflater);
-        mInflater.setFactory2(mContext);
+        mInflater = new BridgeInflater(context, params.getProjectCallback());
+        context.setBridgeInflater(mInflater);
+        mInflater.setFactory2(context);
 
-        mBlockParser = new BridgeXmlBlockParser(mParams.getLayoutDescription(),
-                mContext, false /* platformResourceFlag */);
+        mBlockParser = new BridgeXmlBlockParser(params.getLayoutDescription(),
+                context, false /* platformResourceFlag */);
 
         return SUCCESS.createResult();
     }
 
     /**
-     * Prepares the scene for action.
-     * <p>
-     * This call is blocking if another rendering/inflating is currently happening, and will return
-     * whether the preparation worked.
-     *
-     * The preparation can fail if another rendering took too long and the timeout was elapsed.
-     *
-     * More than one call to this from the same thread will have no effect and will return
-     * {@link Result#SUCCESS}.
-     *
-     * After scene actions have taken place, only one call to {@link #release()} must be
-     * done.
-     *
-     * @param timeout the time to wait if another rendering is happening.
-     *
-     * @return whether the scene was prepared
-     *
-     * @see #release()
-     *
-     * @throws IllegalStateException if {@link #init(long)} was never called.
-     */
-    public Result acquire(long timeout) {
-        if (mContext == null) {
-            throw new IllegalStateException("After scene creation, #init() must be called");
-        }
-
-        // acquire the lock. if the result is null, lock was just acquired, otherwise, return
-        // the result.
-        Result result = acquireLock(timeout);
-        if (result != null) {
-            return result;
-        }
-
-        setUp();
-
-        return SUCCESS.createResult();
-    }
-
-    /**
-     * Acquire the lock so that the scene can be acted upon.
-     * <p>
-     * This returns null if the lock was just acquired, otherwise it returns
-     * {@link Result#SUCCESS} if the lock already belonged to that thread, or another
-     * instance (see {@link Result#getStatus()}) if an error occurred.
-     *
-     * @param timeout the time to wait if another rendering is happening.
-     * @return null if the lock was just acquire or another result depending on the state.
-     *
-     * @throws IllegalStateException if the current context is different than the one owned by
-     *      the scene.
-     */
-    private Result acquireLock(long timeout) {
-        ReentrantLock lock = Bridge.getLock();
-        if (lock.isHeldByCurrentThread() == false) {
-            try {
-                boolean acquired = lock.tryLock(timeout, TimeUnit.MILLISECONDS);
-
-                if (acquired == false) {
-                    return ERROR_TIMEOUT.createResult();
-                }
-            } catch (InterruptedException e) {
-                return ERROR_LOCK_INTERRUPTED.createResult();
-            }
-        } else {
-            // This thread holds the lock already. Checks that this wasn't for a different context.
-            // If this is called by init, mContext will be null and so should sCurrentContext
-            // anyway
-            if (mContext != sCurrentContext) {
-                throw new IllegalStateException("Acquiring different scenes from same thread without releases");
-            }
-            return SUCCESS.createResult();
-        }
-
-        return null;
-    }
-
-    /**
-     * Cleans up the scene after an action.
-     */
-    public void release() {
-        ReentrantLock lock = Bridge.getLock();
-
-        // with the use of finally blocks, it is possible to find ourself calling this
-        // without a successful call to prepareScene. This test makes sure that unlock() will
-        // not throw IllegalMonitorStateException.
-        if (lock.isHeldByCurrentThread()) {
-            tearDown();
-            lock.unlock();
-        }
-    }
-
-    /**
-     * Sets up the session for rendering.
-     * <p/>
-     * The counterpart is {@link #tearDown()}.
-     */
-    private void setUp() {
-        // make sure the Resources object references the context (and other objects) for this
-        // scene
-        mContext.initResources();
-        sCurrentContext = mContext;
-
-        LayoutLog currentLog = mParams.getLog();
-        Bridge.setLog(currentLog);
-        mContext.getRenderResources().setFrameworkResourceIdProvider(this);
-        mContext.getRenderResources().setLogger(currentLog);
-    }
-
-    /**
-     * Tear down the session after rendering.
-     * <p/>
-     * The counterpart is {@link #setUp()}.
-     */
-    private void tearDown() {
-        // Make sure to remove static references, otherwise we could not unload the lib
-        mContext.disposeResources();
-        sCurrentContext = null;
-
-        Bridge.setLog(null);
-        mContext.getRenderResources().setFrameworkResourceIdProvider(null);
-        mContext.getRenderResources().setLogger(null);
-    }
-
-    public static BridgeContext getCurrentContext() {
-        return sCurrentContext;
-    }
-
-    /**
      * Inflates the layout.
      * <p>
      * {@link #acquire(long)} must have been called before this.
@@ -353,13 +201,103 @@
 
         try {
 
-            mViewRoot = new FrameLayout(mContext);
+            SessionParams params = getParams();
+            BridgeContext context = getContext();
+
+            if (mWindowIsFloating || params.isForceNoDecor()) {
+                mViewRoot = mContentRoot = new FrameLayout(context);
+            } else {
+                /*
+                 * we're creating the following layout
+                 *
+                   +-------------------------------------------------+
+                   | System bar (only in phone UI)                   |
+                   +-------------------------------------------------+
+                   | Title/Action bar (optional)                     |
+                   +-------------------------------------------------+
+                   | Content, vertical extending                     |
+                   |                                                 |
+                   +-------------------------------------------------+
+                   | System bar (only in tablet UI)                  |
+                   +-------------------------------------------------+
+
+                 */
+
+                LinearLayout topLayout = new LinearLayout(context);
+                mViewRoot = topLayout;
+                topLayout.setOrientation(LinearLayout.VERTICAL);
+
+                if (mStatusBarSize > 0) {
+                    // system bar
+                    try {
+                        PhoneSystemBar systemBar = new PhoneSystemBar(context,
+                                params.getDensity());
+                        systemBar.setLayoutParams(
+                                new LinearLayout.LayoutParams(
+                                        LayoutParams.MATCH_PARENT, mStatusBarSize));
+                        topLayout.addView(systemBar);
+                    } catch (XmlPullParserException e) {
+
+                    }
+                }
+
+                // if the theme says no title/action bar, then the size will be 0
+                if (mActionBarSize > 0) {
+                    try {
+                        FakeActionBar actionBar = new FakeActionBar(context,
+                                params.getDensity(),
+                                params.getAppLabel(), params.getAppIcon());
+                        actionBar.setLayoutParams(
+                                new LinearLayout.LayoutParams(
+                                        LayoutParams.MATCH_PARENT, mActionBarSize));
+                        topLayout.addView(actionBar);
+                    } catch (XmlPullParserException e) {
+
+                    }
+                } else if (mTitleBarSize > 0) {
+                    try {
+                        TitleBar titleBar = new TitleBar(context,
+                                params.getDensity(), params.getAppLabel());
+                        titleBar.setLayoutParams(
+                                new LinearLayout.LayoutParams(
+                                        LayoutParams.MATCH_PARENT, mTitleBarSize));
+                        topLayout.addView(titleBar);
+                    } catch (XmlPullParserException e) {
+
+                    }
+                }
+
+
+                // content frame
+                mContentRoot = new FrameLayout(context);
+                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
+                        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
+                layoutParams.weight = 1;
+                mContentRoot.setLayoutParams(layoutParams);
+                topLayout.addView(mContentRoot);
+
+                if (mSystemBarSize > 0) {
+                    // system bar
+                    try {
+                        TabletSystemBar systemBar = new TabletSystemBar(context,
+                                params.getDensity());
+                        systemBar.setLayoutParams(
+                                new LinearLayout.LayoutParams(
+                                        LayoutParams.MATCH_PARENT, mSystemBarSize));
+                        topLayout.addView(systemBar);
+                    } catch (XmlPullParserException e) {
+
+                    }
+                }
+
+            }
+
 
             // Sets the project callback (custom view loader) to the fragment delegate so that
             // it can instantiate the custom Fragment.
-            Fragment_Delegate.setProjectCallback(mParams.getProjectCallback());
+            Fragment_Delegate.setProjectCallback(params.getProjectCallback());
 
-            View view = mInflater.inflate(mBlockParser, mViewRoot);
+            View view = mInflater.inflate(mBlockParser, mContentRoot);
 
             Fragment_Delegate.setProjectCallback(null);
 
@@ -373,13 +311,12 @@
             mViewRoot.dispatchAttachedToWindow(info, 0);
 
             // post-inflate process. For now this supports TabHost/TabWidget
-            postInflateProcess(view, mParams.getProjectCallback());
+            postInflateProcess(view, params.getProjectCallback());
 
             // get the background drawable
             if (mWindowBackground != null) {
-                Drawable d = ResourceHelper.getDrawable(mWindowBackground,
-                        mContext, true /* isFramework */);
-                mViewRoot.setBackgroundDrawable(d);
+                Drawable d = ResourceHelper.getDrawable(mWindowBackground, context);
+                mContentRoot.setBackgroundDrawable(d);
             }
 
             return SUCCESS.createResult();
@@ -408,12 +345,14 @@
      * @throws IllegalStateException if the current context is different than the one owned by
      *      the scene, or if {@link #acquire(long)} was not called.
      *
-     * @see SceneParams#getRenderingMode()
-     * @see LayoutScene#render(long)
+     * @see RenderParams#getRenderingMode()
+     * @see RenderSession#render(long)
      */
     public Result render(boolean freshRender) {
         checkLock();
 
+        SessionParams params = getParams();
+
         try {
             if (mViewRoot == null) {
                 return ERROR_NOT_INFLATED.createResult();
@@ -421,14 +360,14 @@
             // measure the views
             int w_spec, h_spec;
 
-            RenderingMode renderingMode = mParams.getRenderingMode();
+            RenderingMode renderingMode = params.getRenderingMode();
 
             // only do the screen measure when needed.
             boolean newRenderSize = false;
             if (mMeasuredScreenWidth == -1) {
                 newRenderSize = true;
-                mMeasuredScreenWidth = mParams.getScreenWidth();
-                mMeasuredScreenHeight = mParams.getScreenHeight() - mTotalBarSize;
+                mMeasuredScreenWidth = params.getScreenWidth();
+                mMeasuredScreenHeight = params.getScreenHeight();
 
                 if (renderingMode != RenderingMode.NORMAL) {
                     // measure the full size needed by the layout.
@@ -473,64 +412,44 @@
             // create the BufferedImage into which the layout will be rendered.
             boolean newImage = false;
             if (newRenderSize || mCanvas == null) {
-                if (mParams.getImageFactory() != null) {
-                    mImage = mParams.getImageFactory().getImage(
+                if (params.getImageFactory() != null) {
+                    mImage = params.getImageFactory().getImage(
                             mMeasuredScreenWidth,
-                            mMeasuredScreenHeight + mTotalBarSize);
+                            mMeasuredScreenHeight);
                 } else {
                     mImage = new BufferedImage(
                             mMeasuredScreenWidth,
-                            mMeasuredScreenHeight + mTotalBarSize,
+                            mMeasuredScreenHeight,
                             BufferedImage.TYPE_INT_ARGB);
                     newImage = true;
                 }
 
-                if (mParams.isBgColorOverridden()) {
+                if (params.isBgColorOverridden()) {
                     // since we override the content, it's the same as if it was a new image.
                     newImage = true;
                     Graphics2D gc = mImage.createGraphics();
-                    gc.setColor(new Color(mParams.getOverrideBgColor(), true));
+                    gc.setColor(new Color(params.getOverrideBgColor(), true));
                     gc.setComposite(AlphaComposite.Src);
-                    gc.fillRect(0, 0, mMeasuredScreenWidth,
-                            mMeasuredScreenHeight + mTotalBarSize);
+                    gc.fillRect(0, 0, mMeasuredScreenWidth, mMeasuredScreenHeight);
                     gc.dispose();
                 }
 
                 // create an Android bitmap around the BufferedImage
                 Bitmap bitmap = Bitmap_Delegate.createBitmap(mImage,
-                        true /*isMutable*/,
-                        Density.getEnum(mParams.getDensity()));
+                        true /*isMutable*/, params.getDensity());
 
                 // create a Canvas around the Android bitmap
                 mCanvas = new Canvas(bitmap);
-                mCanvas.setDensity(mParams.getDensity());
-                mCanvas.translate(0, mTopOffset);
+                mCanvas.setDensity(params.getDensity().getDpiValue());
             }
 
             if (freshRender && newImage == false) {
                 Graphics2D gc = mImage.createGraphics();
                 gc.setComposite(AlphaComposite.Src);
 
-                if (mStatusBarSize > 0) {
-                    gc.setColor(new Color(0xFF3C3C3C, true));
-                    gc.fillRect(0, 0, mMeasuredScreenWidth, mStatusBarSize);
-                }
-
-                if (mTopBarSize > 0) {
-                    gc.setColor(new Color(0xFF7F7F7F, true));
-                    gc.fillRect(0, mStatusBarSize, mMeasuredScreenWidth, mTopOffset);
-                }
-
-                // erase the rest
                 gc.setColor(new Color(0x00000000, true));
-                gc.fillRect(0, mTopOffset,
-                        mMeasuredScreenWidth, mMeasuredScreenHeight + mTopOffset);
-
-                if (mSystemBarSize > 0) {
-                    gc.setColor(new Color(0xFF3C3C3C, true));
-                    gc.fillRect(0, mMeasuredScreenHeight + mTopOffset,
-                            mMeasuredScreenWidth, mMeasuredScreenHeight + mTotalBarSize);
-                }
+                gc.fillRect(0, 0,
+                        mMeasuredScreenWidth, mMeasuredScreenHeight);
 
                 // done
                 gc.dispose();
@@ -538,7 +457,7 @@
 
             mViewRoot.draw(mCanvas);
 
-            mViewInfoList = visitAllChildren((ViewGroup)mViewRoot, mContext, mTopOffset);
+            mViewInfoList = startVisitingViews(mViewRoot, 0);
 
             // success!
             return SUCCESS.createResult();
@@ -561,33 +480,35 @@
      * @throws IllegalStateException if the current context is different than the one owned by
      *      the scene, or if {@link #acquire(long)} was not called.
      *
-     * @see LayoutScene#animate(Object, String, boolean, IAnimationListener)
+     * @see RenderSession#animate(Object, String, boolean, IAnimationListener)
      */
     public Result animate(Object targetObject, String animationName,
             boolean isFrameworkAnimation, IAnimationListener listener) {
         checkLock();
 
+        BridgeContext context = getContext();
+
         // find the animation file.
         ResourceValue animationResource = null;
         int animationId = 0;
         if (isFrameworkAnimation) {
-            animationResource = mContext.getRenderResources().getFrameworkResource(
+            animationResource = context.getRenderResources().getFrameworkResource(
                     ResourceType.ANIMATOR, animationName);
             if (animationResource != null) {
                 animationId = Bridge.getResourceId(ResourceType.ANIMATOR, animationName);
             }
         } else {
-            animationResource = mContext.getRenderResources().getProjectResource(
+            animationResource = context.getRenderResources().getProjectResource(
                     ResourceType.ANIMATOR, animationName);
             if (animationResource != null) {
-                animationId = mContext.getProjectCallback().getResourceId(
+                animationId = context.getProjectCallback().getResourceId(
                         ResourceType.ANIMATOR, animationName);
             }
         }
 
         if (animationResource != null) {
             try {
-                Animator anim = AnimatorInflater.loadAnimator(mContext, animationId);
+                Animator anim = AnimatorInflater.loadAnimator(context, animationId);
                 if (anim != null) {
                     anim.setTarget(targetObject);
 
@@ -617,14 +538,16 @@
      * @throws IllegalStateException if the current context is different than the one owned by
      *      the scene, or if {@link #acquire(long)} was not called.
      *
-     * @see LayoutScene#insertChild(Object, ILayoutPullParser, int, IAnimationListener)
+     * @see RenderSession#insertChild(Object, ILayoutPullParser, int, IAnimationListener)
      */
     public Result insertChild(final ViewGroup parentView, ILayoutPullParser childXml,
             final int index, IAnimationListener listener) {
         checkLock();
 
+        BridgeContext context = getContext();
+
         // create a block parser for the XML
-        BridgeXmlBlockParser blockParser = new BridgeXmlBlockParser(childXml, mContext,
+        BridgeXmlBlockParser blockParser = new BridgeXmlBlockParser(childXml, context,
                 false /* platformResourceFlag */);
 
         // inflate the child without adding it to the root since we want to control where it'll
@@ -696,7 +619,7 @@
      * @throws IllegalStateException if the current context is different than the one owned by
      *      the scene, or if {@link #acquire(long)} was not called.
      *
-     * @see LayoutScene#moveChild(Object, Object, int, Map, IAnimationListener)
+     * @see RenderSession#moveChild(Object, Object, int, Map, IAnimationListener)
      */
     public Result moveChild(final ViewGroup newParentView, final View childView, final int index,
             Map<String, String> layoutParamsMap, final IAnimationListener listener) {
@@ -892,7 +815,7 @@
      * @throws IllegalStateException if the current context is different than the one owned by
      *      the scene, or if {@link #acquire(long)} was not called.
      *
-     * @see LayoutScene#removeChild(Object, IAnimationListener)
+     * @see RenderSession#removeChild(Object, IAnimationListener)
      */
     public Result removeChild(final View childView, IAnimationListener listener) {
         checkLock();
@@ -947,37 +870,9 @@
         }
     }
 
-    /**
-     * Returns the log associated with the session.
-     * @return the log or null if there are none.
-     */
-    public LayoutLog getLog() {
-        if (mParams != null) {
-            return mParams.getLog();
-        }
-
-        return null;
-    }
-
-    /**
-     * Checks that the lock is owned by the current thread and that the current context is the one
-     * from this scene.
-     *
-     * @throws IllegalStateException if the current context is different than the one owned by
-     *      the scene, or if {@link #acquire(long)} was not called.
-     */
-    private void checkLock() {
-        ReentrantLock lock = Bridge.getLock();
-        if (lock.isHeldByCurrentThread() == false) {
-            throw new IllegalStateException("scene must be acquired first. see #acquire(long)");
-        }
-        if (sCurrentContext != mContext) {
-            throw new IllegalStateException("Thread acquired a scene but is rendering a different one");
-        }
-    }
 
     private void findBackground(RenderResources resources) {
-        if (mParams.isBgColorOverridden() == false) {
+        if (getParams().isBgColorOverridden() == false) {
             mWindowBackground = resources.findItemInTheme("windowBackground");
             if (mWindowBackground != null) {
                 mWindowBackground = resources.resolveResValue(mWindowBackground);
@@ -986,35 +881,7 @@
     }
 
     private boolean isTabletUi() {
-        return mParams.getConfigScreenSize() == ScreenSize.XLARGE;
-    }
-
-    private boolean isHCApp() {
-        RenderResources resources = mContext.getRenderResources();
-
-        // the app must say it targets 11+ and the theme name must extend Theme.Holo or
-        // Theme.Holo.Light (which does not extend Theme.Holo, but Theme.Light)
-        if (mParams.getTargetSdkVersion() < 11) {
-            return false;
-        }
-
-        StyleResourceValue currentTheme = resources.getCurrentTheme();
-        StyleResourceValue holoTheme = resources.getTheme("Theme.Holo", true /*frameworkTheme*/);
-
-        if (currentTheme == holoTheme ||
-                resources.themeIsParentOf(holoTheme, currentTheme)) {
-            return true;
-        }
-
-        StyleResourceValue holoLightTheme = resources.getTheme("Theme.Holo.Light",
-                true /*frameworkTheme*/);
-
-        if (currentTheme == holoLightTheme ||
-                resources.themeIsParentOf(holoLightTheme, currentTheme)) {
-            return true;
-        }
-
-        return false;
+        return getParams().getConfigScreenSize() == ScreenSize.XLARGE;
     }
 
     private void findStatusBar(RenderResources resources, DisplayMetrics metrics) {
@@ -1022,7 +889,7 @@
             boolean windowFullscreen = getBooleanThemeValue(resources,
                     "windowFullscreen", false /*defaultValue*/);
 
-            if (windowFullscreen == false) {
+            if (windowFullscreen == false && mWindowIsFloating == false) {
                 // default value
                 mStatusBarSize = DEFAULT_STATUS_BAR_HEIGHT;
 
@@ -1041,20 +908,11 @@
         }
     }
 
-    private void findTopBar(RenderResources resources, DisplayMetrics metrics) {
-        boolean windowIsFloating = getBooleanThemeValue(resources,
-                "windowIsFloating", true /*defaultValue*/);
-
-        if (windowIsFloating == false) {
-            if (isHCApp()) {
-                findActionBar(resources, metrics);
-            } else {
-                findTitleBar(resources, metrics);
-            }
-        }
-    }
-
     private void findActionBar(RenderResources resources, DisplayMetrics metrics) {
+        if (mWindowIsFloating) {
+            return;
+        }
+
         boolean windowActionBar = getBooleanThemeValue(resources,
                 "windowActionBar", true /*defaultValue*/);
 
@@ -1062,7 +920,7 @@
         if (windowActionBar) {
 
             // default size of the window title bar
-            mTopBarSize = DEFAULT_TITLE_BAR_HEIGHT;
+            mActionBarSize = DEFAULT_TITLE_BAR_HEIGHT;
 
             // get value from the theme.
             ResourceValue value = resources.findItemInTheme("actionBarSize");
@@ -1075,44 +933,43 @@
                 TypedValue typedValue = ResourceHelper.getValue(value.getValue());
                 if (typedValue != null) {
                     // compute the pixel value based on the display metrics
-                    mTopBarSize = (int)typedValue.getDimension(metrics);
+                    mActionBarSize = (int)typedValue.getDimension(metrics);
                 }
             }
-        }
-    }
+        } else {
+            // action bar overrides title bar so only look for this one if action bar is hidden
+            boolean windowNoTitle = getBooleanThemeValue(resources,
+                    "windowNoTitle", false /*defaultValue*/);
 
-    private void findTitleBar(RenderResources resources, DisplayMetrics metrics) {
-        boolean windowNoTitle = getBooleanThemeValue(resources,
-                "windowNoTitle", false /*defaultValue*/);
+            if (windowNoTitle == false) {
 
-        if (windowNoTitle == false) {
+                // default size of the window title bar
+                mTitleBarSize = DEFAULT_TITLE_BAR_HEIGHT;
 
-            // default size of the window title bar
-            mTopBarSize = DEFAULT_TITLE_BAR_HEIGHT;
+                // get value from the theme.
+                ResourceValue value = resources.findItemInTheme("windowTitleSize");
 
-            // get value from the theme.
-            ResourceValue value = resources.findItemInTheme("windowTitleSize");
+                // resolve it
+                value = resources.resolveResValue(value);
 
-            // resolve it
-            value = resources.resolveResValue(value);
-
-            if (value != null) {
-                // get the numerical value, if available
-                TypedValue typedValue = ResourceHelper.getValue(value.getValue());
-                if (typedValue != null) {
-                    // compute the pixel value based on the display metrics
-                    mTopBarSize = (int)typedValue.getDimension(metrics);
+                if (value != null) {
+                    // get the numerical value, if available
+                    TypedValue typedValue = ResourceHelper.getValue(value.getValue());
+                    if (typedValue != null) {
+                        // compute the pixel value based on the display metrics
+                        mTitleBarSize = (int)typedValue.getDimension(metrics);
+                    }
                 }
             }
+
         }
     }
 
     private void findSystemBar(RenderResources resources, DisplayMetrics metrics) {
-        if (isTabletUi() && getBooleanThemeValue(
-                resources, "windowIsFloating", true /*defaultValue*/) == false) {
+        if (isTabletUi() && mWindowIsFloating == false) {
 
             // default value
-            mSystemBarSize = 56; // ??
+            mSystemBarSize = 48; // ??
 
             // get the real value
             ResourceValue value = resources.getFrameworkResource(ResourceType.DIMEN,
@@ -1221,7 +1078,7 @@
                     tabHost.getResources().getDrawable(android.R.drawable.ic_menu_info_details))
                     .setContent(new TabHost.TabContentFactory() {
                         public View createTabContent(String tag) {
-                            return new LinearLayout(mContext);
+                            return new LinearLayout(getContext());
                         }
                     });
             tabHost.addTab(spec);
@@ -1244,40 +1101,71 @@
         }
     }
 
+    private List<ViewInfo> startVisitingViews(View view, int offset) {
+        if (view == null) {
+            return null;
+        }
+
+        // adjust the offset to this view.
+        offset += view.getTop();
+
+        if (view == mContentRoot) {
+            return visitAllChildren(mContentRoot, offset);
+        }
+
+        // otherwise, look for mContentRoot in the children
+        if (view instanceof ViewGroup) {
+            ViewGroup group = ((ViewGroup) view);
+
+            for (int i = 0; i < group.getChildCount(); i++) {
+                List<ViewInfo> list = startVisitingViews(group.getChildAt(i), offset);
+                if (list != null) {
+                    return list;
+                }
+            }
+        }
+
+        return null;
+    }
 
     /**
      * Visits a View and its children and generate a {@link ViewInfo} containing the
      * bounds of all the views.
      * @param view the root View
-     * @param context the context.
+     * @param offset an offset for the view bounds.
      */
-    private ViewInfo visit(View view, BridgeContext context, int offset) {
+    private ViewInfo visit(View view, int offset) {
         if (view == null) {
             return null;
         }
 
         ViewInfo result = new ViewInfo(view.getClass().getName(),
-                context.getViewKey(view),
+                getContext().getViewKey(view),
                 view.getLeft(), view.getTop() + offset, view.getRight(), view.getBottom() + offset,
                 view, view.getLayoutParams());
 
         if (view instanceof ViewGroup) {
             ViewGroup group = ((ViewGroup) view);
-            result.setChildren(visitAllChildren(group, context, 0 /*offset*/));
+            result.setChildren(visitAllChildren(group, 0 /*offset*/));
         }
 
         return result;
     }
 
-    private List<ViewInfo> visitAllChildren(ViewGroup viewGroup, BridgeContext context,
-            int offset) {
+    /**
+     * Visits all the children of a given ViewGroup generate a list of {@link ViewInfo}
+     * containing the bounds of all the views.
+     * @param view the root View
+     * @param offset an offset for the view bounds.
+     */
+    private List<ViewInfo> visitAllChildren(ViewGroup viewGroup, int offset) {
         if (viewGroup == null) {
             return null;
         }
 
         List<ViewInfo> children = new ArrayList<ViewInfo>();
         for (int i = 0; i < viewGroup.getChildCount(); i++) {
-            children.add(visit(viewGroup.getChildAt(i), context, offset));
+            children.add(visit(viewGroup.getChildAt(i), offset));
         }
         return children;
     }
@@ -1300,7 +1188,7 @@
     }
 
     public Map<String, String> getDefaultProperties(Object viewObject) {
-        return mContext.getDefaultPropMap(viewObject);
+        return getContext().getDefaultPropMap(viewObject);
     }
 
     public void setScene(RenderSession session) {
@@ -1310,11 +1198,4 @@
     public RenderSession getSession() {
         return mScene;
     }
-
-    // --- FrameworkResourceIdProvider methods
-
-    @Override
-    public Integer getId(ResourceType resType, String resName) {
-        return Bridge.getResourceId(resType, resName);
-    }
 }
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java
index 25bb81c..19392a7 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java
@@ -18,6 +18,7 @@
 
 import com.android.ide.common.rendering.api.DensityBasedResourceValue;
 import com.android.ide.common.rendering.api.LayoutLog;
+import com.android.ide.common.rendering.api.RenderResources;
 import com.android.ide.common.rendering.api.ResourceValue;
 import com.android.layoutlib.bridge.Bridge;
 import com.android.layoutlib.bridge.android.BridgeContext;
@@ -28,7 +29,9 @@
 
 import org.kxml2.io.KXmlParser;
 import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
 
+import android.content.res.ColorStateList;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap_Delegate;
 import android.graphics.NinePatch_Delegate;
@@ -40,8 +43,10 @@
 import android.util.TypedValue;
 
 import java.io.File;
+import java.io.FileInputStream;
 import java.io.FileReader;
 import java.io.IOException;
+import java.io.InputStream;
 import java.net.MalformedURLException;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -108,75 +113,84 @@
         throw new NumberFormatException();
     }
 
+    public static ColorStateList getColorStateList(ResourceValue resValue, BridgeContext context) {
+        String value = resValue.getValue();
+        if (value != null) {
+            // first check if the value is a file (xml most likely)
+            File f = new File(value);
+            if (f.isFile()) {
+                try {
+                    // let the framework inflate the ColorStateList from the XML file, by
+                    // providing an XmlPullParser
+                    KXmlParser parser = new KXmlParser();
+                    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
+                    parser.setInput(new FileReader(f));
+
+                    return ColorStateList.createFromXml(context.getResources(),
+                            new BridgeXmlBlockParser(parser, context, resValue.isFramework()));
+                } catch (XmlPullParserException e) {
+                    Bridge.getLog().error(LayoutLog.TAG_BROKEN,
+                            "Failed to configure parser for " + value, e, null /*data*/);
+                    // we'll return null below.
+                } catch (Exception e) {
+                    // this is an error and not warning since the file existence is
+                    // checked before attempting to parse it.
+                    Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ,
+                            "Failed to parse file " + value, e, null /*data*/);
+
+                    return null;
+                }
+            } else {
+                // try to load the color state list from an int
+                try {
+                    int color = ResourceHelper.getColor(value);
+                    return ColorStateList.valueOf(color);
+                } catch (NumberFormatException e) {
+                    Bridge.getLog().error(LayoutLog.TAG_RESOURCES_FORMAT,
+                            "Failed to convert " + value + " into a ColorStateList", e,
+                            null /*data*/);
+                    return null;
+                }
+            }
+        }
+
+        return null;
+    }
+
     /**
      * Returns a drawable from the given value.
      * @param value The value that contains a path to a 9 patch, a bitmap or a xml based drawable,
      * or an hexadecimal color
-     * @param context
-     * @param isFramework indicates whether the resource is a framework resources.
-     * Framework resources are cached, and loaded only once.
+     * @param context the current context
      */
-    public static Drawable getDrawable(ResourceValue value, BridgeContext context,
-            boolean isFramework) {
+    public static Drawable getDrawable(ResourceValue value, BridgeContext context) {
         Drawable d = null;
 
         String stringValue = value.getValue();
+        if (RenderResources.REFERENCE_NULL.equals(stringValue)) {
+            return null;
+        }
 
         String lowerCaseValue = stringValue.toLowerCase();
 
+        Density density = Density.MEDIUM;
+        if (value instanceof DensityBasedResourceValue) {
+            density =
+                ((DensityBasedResourceValue)value).getResourceDensity();
+        }
+
+
         if (lowerCaseValue.endsWith(NinePatch.EXTENSION_9PATCH)) {
             File file = new File(stringValue);
             if (file.isFile()) {
-                // see if we still have both the chunk and the bitmap in the caches
-                NinePatchChunk chunk = Bridge.getCached9Patch(stringValue,
-                        isFramework ? null : context.getProjectKey());
-                Bitmap bitmap = Bridge.getCachedBitmap(stringValue,
-                        isFramework ? null : context.getProjectKey());
-
-                // if either chunk or bitmap is null, then we reload the 9-patch file.
-                if (chunk == null || bitmap == null) {
-                    try {
-                        NinePatch ninePatch = NinePatch.load(file.toURI().toURL(),
-                                false /* convert */);
-                        if (ninePatch != null) {
-                            if (chunk == null) {
-                                chunk = ninePatch.getChunk();
-
-                                Bridge.setCached9Patch(stringValue, chunk,
-                                        isFramework ? null : context.getProjectKey());
-                            }
-
-                            if (bitmap == null) {
-                                Density density = Density.MEDIUM;
-                                if (value instanceof DensityBasedResourceValue) {
-                                    density =
-                                        ((DensityBasedResourceValue)value).getResourceDensity();
-                                }
-
-                                bitmap = Bitmap_Delegate.createBitmap(ninePatch.getImage(),
-                                        false /*isMutable*/,
-                                        density);
-
-                                Bridge.setCachedBitmap(stringValue, bitmap,
-                                        isFramework ? null : context.getProjectKey());
-                            }
-                        }
-                    } catch (MalformedURLException e) {
-                        // URL is wrong, we'll return null below
-                    } catch (IOException e) {
-                        // failed to read the file, we'll return null below.
-                        Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ,
-                                "Failed lot load " + file.getAbsolutePath(), e, null /*data*/);
-                    }
-                }
-
-                if (chunk != null && bitmap != null) {
-                    int[] padding = chunk.getPadding();
-                    Rect paddingRect = new Rect(padding[0], padding[1], padding[2], padding[3]);
-
-                    return new NinePatchDrawable(context.getResources(), bitmap,
-                            NinePatch_Delegate.serialize(chunk),
-                            paddingRect, null);
+                try {
+                    return getNinePatchDrawable(
+                            new FileInputStream(file), density, value.isFramework(),
+                            stringValue, context);
+                } catch (IOException e) {
+                    // failed to read the file, we'll return null below.
+                    Bridge.getLog().error(LayoutLog.TAG_RESOURCES_READ,
+                            "Failed lot load " + file.getAbsolutePath(), e, null /*data*/);
                 }
             }
 
@@ -192,7 +206,7 @@
                     parser.setInput(new FileReader(f));
 
                     d = Drawable.createFromXml(context.getResources(),
-                            new BridgeXmlBlockParser(parser, context, isFramework));
+                            new BridgeXmlBlockParser(parser, context, value.isFramework()));
                     return d;
                 } catch (Exception e) {
                     // this is an error and not warning since the file existence is checked before
@@ -212,18 +226,13 @@
             if (bmpFile.isFile()) {
                 try {
                     Bitmap bitmap = Bridge.getCachedBitmap(stringValue,
-                            isFramework ? null : context.getProjectKey());
+                            value.isFramework() ? null : context.getProjectKey());
 
                     if (bitmap == null) {
-                        Density density = Density.MEDIUM;
-                        if (value instanceof DensityBasedResourceValue) {
-                            density = ((DensityBasedResourceValue)value).getResourceDensity();
-                        }
-
                         bitmap = Bitmap_Delegate.createBitmap(bmpFile, false /*isMutable*/,
                                 density);
                         Bridge.setCachedBitmap(stringValue, bitmap,
-                                isFramework ? null : context.getProjectKey());
+                                value.isFramework() ? null : context.getProjectKey());
                     }
 
                     return new BitmapDrawable(context.getResources(), bitmap);
@@ -249,6 +258,52 @@
         return null;
     }
 
+    private static Drawable getNinePatchDrawable(InputStream inputStream, Density density,
+            boolean isFramework, String cacheKey, BridgeContext context) throws IOException {
+        // see if we still have both the chunk and the bitmap in the caches
+        NinePatchChunk chunk = Bridge.getCached9Patch(cacheKey,
+                isFramework ? null : context.getProjectKey());
+        Bitmap bitmap = Bridge.getCachedBitmap(cacheKey,
+                isFramework ? null : context.getProjectKey());
+
+        // if either chunk or bitmap is null, then we reload the 9-patch file.
+        if (chunk == null || bitmap == null) {
+            try {
+                NinePatch ninePatch = NinePatch.load(inputStream, true /*is9Patch*/,
+                        false /* convert */);
+                if (ninePatch != null) {
+                    if (chunk == null) {
+                        chunk = ninePatch.getChunk();
+
+                        Bridge.setCached9Patch(cacheKey, chunk,
+                                isFramework ? null : context.getProjectKey());
+                    }
+
+                    if (bitmap == null) {
+                        bitmap = Bitmap_Delegate.createBitmap(ninePatch.getImage(),
+                                false /*isMutable*/,
+                                density);
+
+                        Bridge.setCachedBitmap(cacheKey, bitmap,
+                                isFramework ? null : context.getProjectKey());
+                    }
+                }
+            } catch (MalformedURLException e) {
+                // URL is wrong, we'll return null below
+            }
+        }
+
+        if (chunk != null && bitmap != null) {
+            int[] padding = chunk.getPadding();
+            Rect paddingRect = new Rect(padding[0], padding[1], padding[2], padding[3]);
+
+            return new NinePatchDrawable(context.getResources(), bitmap,
+                    NinePatch_Delegate.serialize(chunk),
+                    paddingRect, null);
+        }
+
+        return null;
+    }
 
     // ------- TypedValue stuff
     // This is taken from //device/libs/utils/ResourceTypes.cpp
@@ -411,3 +466,4 @@
         return false;
     }
 }
+
diff --git a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
index 291f076d..eff6bbc 100644
--- a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
@@ -97,6 +97,7 @@
         "android.app.Fragment#instantiate", //(Landroid/content/Context;Ljava/lang/String;Landroid/os/Bundle;)Landroid/app/Fragment;",
         "android.content.res.Resources$Theme#obtainStyledAttributes",
         "android.content.res.Resources$Theme#resolveAttribute",
+        "android.graphics.BitmapFactory#finishDecode",
         "android.os.Handler#sendMessageAtTime",
         "android.os.Build#getString",
         "android.view.LayoutInflater#rInflate",
@@ -112,6 +113,7 @@
         "android.animation.PropertyValuesHolder",
         "android.graphics.AvoidXfermode",
         "android.graphics.Bitmap",
+        "android.graphics.BitmapFactory",
         "android.graphics.BitmapShader",
         "android.graphics.BlurMaskFilter",
         "android.graphics.Canvas",
@@ -164,7 +166,6 @@
      */
     private final static String[] RENAMED_CLASSES =
         new String[] {
-            "android.graphics.BitmapFactory",       "android.graphics._Original_BitmapFactory",
             "android.os.ServiceManager",            "android.os._Original_ServiceManager",
             "android.view.SurfaceView",             "android.view._Original_SurfaceView",
             "android.view.accessibility.AccessibilityManager", "android.view.accessibility._Original_AccessibilityManager",