Merge "split Surface in two classes: SurfaceControl and Surface"
diff --git a/core/java/android/net/CaptivePortalTracker.java b/core/java/android/net/CaptivePortalTracker.java
index 354a8c4..21995c0 100644
--- a/core/java/android/net/CaptivePortalTracker.java
+++ b/core/java/android/net/CaptivePortalTracker.java
@@ -25,14 +25,15 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.res.Resources;
+import android.database.ContentObserver;
 import android.net.ConnectivityManager;
 import android.net.IConnectivityManager;
+import android.os.Handler;
 import android.os.UserHandle;
 import android.os.Message;
 import android.os.RemoteException;
 import android.provider.Settings;
 import android.telephony.TelephonyManager;
-import android.util.Log;
 
 import com.android.internal.util.State;
 import com.android.internal.util.StateMachine;
@@ -81,15 +82,21 @@
     private State mActiveNetworkState = new ActiveNetworkState();
     private State mDelayedCaptiveCheckState = new DelayedCaptiveCheckState();
 
+    private static final String SETUP_WIZARD_PACKAGE = "com.google.android.setupwizard";
+    private boolean mDeviceProvisioned = false;
+    private ProvisioningObserver mProvisioningObserver;
+
     private CaptivePortalTracker(Context context, IConnectivityManager cs) {
         super(TAG);
 
         mContext = context;
         mConnService = cs;
         mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
+        mProvisioningObserver = new ProvisioningObserver();
 
         IntentFilter filter = new IntentFilter();
         filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
+        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE);
         mContext.registerReceiver(mReceiver, filter);
 
         mServer = Settings.Global.getString(mContext.getContentResolver(),
@@ -106,11 +113,31 @@
         setInitialState(mNoActiveNetworkState);
     }
 
+    private class ProvisioningObserver extends ContentObserver {
+        ProvisioningObserver() {
+            super(new Handler());
+            mContext.getContentResolver().registerContentObserver(Settings.Global.getUriFor(
+                    Settings.Global.DEVICE_PROVISIONED), false, this);
+            onChange(false); // load initial value
+        }
+
+        @Override
+        public void onChange(boolean selfChange) {
+            mDeviceProvisioned = Settings.Global.getInt(mContext.getContentResolver(),
+                    Settings.Global.DEVICE_PROVISIONED, 0) != 0;
+        }
+    }
+
     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
             String action = intent.getAction();
-            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
+            // Normally, we respond to CONNECTIVITY_ACTION, allowing time for the change in
+            // connectivity to stabilize, but if the device is not yet provisioned, respond
+            // immediately to speed up transit through the setup wizard.
+            if ((mDeviceProvisioned && action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
+                    || (!mDeviceProvisioned
+                            && action.equals(ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE))) {
                 NetworkInfo info = intent.getParcelableExtra(
                         ConnectivityManager.EXTRA_NETWORK_INFO);
                 sendMessage(obtainMessage(CMD_CONNECTIVITY_CHANGE, info));
@@ -222,8 +249,12 @@
         @Override
         public void enter() {
             if (DBG) log(getName() + "\n");
-            sendMessageDelayed(obtainMessage(CMD_DELAYED_CAPTIVE_CHECK,
-                        ++mDelayedCheckToken, 0), DELAYED_CHECK_INTERVAL_MS);
+            Message message = obtainMessage(CMD_DELAYED_CAPTIVE_CHECK, ++mDelayedCheckToken, 0);
+            if (mDeviceProvisioned) {
+                sendMessageDelayed(message, DELAYED_CHECK_INTERVAL_MS);
+            } else {
+                sendMessage(message);
+            }
         }
 
         @Override
@@ -233,13 +264,26 @@
                 case CMD_DELAYED_CAPTIVE_CHECK:
                     if (message.arg1 == mDelayedCheckToken) {
                         InetAddress server = lookupHost(mServer);
-                        if (server != null) {
-                            if (isCaptivePortal(server)) {
-                                if (DBG) log("Captive network " + mNetworkInfo);
+                        boolean captive = server != null && isCaptivePortal(server);
+                        if (captive) {
+                            if (DBG) log("Captive network " + mNetworkInfo);
+                        } else {
+                            if (DBG) log("Not captive network " + mNetworkInfo);
+                        }
+                        if (mDeviceProvisioned) {
+                            if (captive) {
+                                // Setup Wizard will assist the user in connecting to a captive
+                                // portal, so make the notification visible unless during setup
                                 setNotificationVisible(true);
                             }
+                        } else {
+                            Intent intent = new Intent(
+                                    ConnectivityManager.ACTION_CAPTIVE_PORTAL_TEST_COMPLETED);
+                            intent.putExtra(ConnectivityManager.EXTRA_IS_CAPTIVE_PORTAL, captive);
+                            intent.setPackage(SETUP_WIZARD_PACKAGE);
+                            mContext.sendBroadcast(intent);
                         }
-                        if (DBG) log("Not captive network " + mNetworkInfo);
+
                         transitionTo(mActiveNetworkState);
                     }
                     break;
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index a8a68d0..000c56c 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -228,6 +228,21 @@
     public static final String EXTRA_ERRORED_TETHER = "erroredArray";
 
     /**
+     * Broadcast Action: The captive portal tracker has finished its test.
+     * Sent only while running Setup Wizard, in lieu of showing a user
+     * notification.
+     * @hide
+     */
+    public static final String ACTION_CAPTIVE_PORTAL_TEST_COMPLETED =
+            "android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED";
+    /**
+     * The lookup key for a boolean that indicates whether a captive portal was detected.
+     * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
+     * @hide
+     */
+    public static final String EXTRA_IS_CAPTIVE_PORTAL = "captivePortal";
+
+    /**
      * The absence of APN..
      * @hide
      */
diff --git a/core/java/android/net/NetworkStats.java b/core/java/android/net/NetworkStats.java
index c757605..9cb904d 100644
--- a/core/java/android/net/NetworkStats.java
+++ b/core/java/android/net/NetworkStats.java
@@ -135,6 +135,18 @@
             builder.append(" operations=").append(operations);
             return builder.toString();
         }
+
+        @Override
+        public boolean equals(Object o) {
+            if (o instanceof Entry) {
+                final Entry e = (Entry) o;
+                return uid == e.uid && set == e.set && tag == e.tag && rxBytes == e.rxBytes
+                        && rxPackets == e.rxPackets && txBytes == e.txBytes
+                        && txPackets == e.txPackets && operations == e.operations
+                        && iface.equals(e.iface);
+            }
+            return false;
+        }
     }
 
     public NetworkStats(long elapsedRealtime, int initialSize) {
diff --git a/core/java/android/view/GLES20Canvas.java b/core/java/android/view/GLES20Canvas.java
index 1810205..40f2261 100644
--- a/core/java/android/view/GLES20Canvas.java
+++ b/core/java/android/view/GLES20Canvas.java
@@ -901,9 +901,9 @@
         final int count = (meshWidth + 1) * (meshHeight + 1);
         checkRange(verts.length, vertOffset, count * 2);
 
-        // TODO: Colors are ignored for now
-        colors = null;
-        colorOffset = 0;
+        if (colors != null) {
+            checkRange(colors.length, colorOffset, count);
+        }
 
         int modifiers = paint != null ? setupModifiers(bitmap, paint) : MODIFIER_NONE;
         try {
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index a9ad97f..885327c 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -97,9 +97,6 @@
     void startAppFreezingScreen(IBinder token, int configChanges);
     void stopAppFreezingScreen(IBinder token, boolean force);
     void removeAppToken(IBinder token);
-    void moveAppToken(int index, IBinder token);
-    void moveAppTokensToTop(in List<IBinder> tokens);
-    void moveAppTokensToBottom(in List<IBinder> tokens);
 
     // Re-evaluate the current orientation from the caller's state.
     // If there is a change, the new Configuration is returned and the
diff --git a/core/java/com/android/internal/net/NetworkStatsFactory.java b/core/java/com/android/internal/net/NetworkStatsFactory.java
index c517a68..8282d23 100644
--- a/core/java/com/android/internal/net/NetworkStatsFactory.java
+++ b/core/java/com/android/internal/net/NetworkStatsFactory.java
@@ -31,6 +31,7 @@
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
+import java.net.ProtocolException;
 
 import libcore.io.IoUtils;
 
@@ -41,7 +42,8 @@
 public class NetworkStatsFactory {
     private static final String TAG = "NetworkStatsFactory";
 
-    // TODO: consider moving parsing to native code
+    private static final boolean USE_NATIVE_PARSING = true;
+    private static final boolean SANITY_CHECK_NATIVE = false;
 
     /** Path to {@code /proc/net/xt_qtaguid/iface_stat_all}. */
     private final File mStatsXtIfaceAll;
@@ -69,7 +71,7 @@
      *
      * @throws IllegalStateException when problem parsing stats.
      */
-    public NetworkStats readNetworkStatsSummaryDev() throws IllegalStateException {
+    public NetworkStats readNetworkStatsSummaryDev() throws IOException {
         final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();
 
         final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 6);
@@ -105,11 +107,9 @@
                 reader.finishLine();
             }
         } catch (NullPointerException e) {
-            throw new IllegalStateException("problem parsing stats: " + e);
+            throw new ProtocolException("problem parsing stats", e);
         } catch (NumberFormatException e) {
-            throw new IllegalStateException("problem parsing stats: " + e);
-        } catch (IOException e) {
-            throw new IllegalStateException("problem parsing stats: " + e);
+            throw new ProtocolException("problem parsing stats", e);
         } finally {
             IoUtils.closeQuietly(reader);
             StrictMode.setThreadPolicy(savedPolicy);
@@ -124,7 +124,7 @@
      *
      * @throws IllegalStateException when problem parsing stats.
      */
-    public NetworkStats readNetworkStatsSummaryXt() throws IllegalStateException {
+    public NetworkStats readNetworkStatsSummaryXt() throws IOException {
         final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();
 
         // return null when kernel doesn't support
@@ -154,11 +154,9 @@
                 reader.finishLine();
             }
         } catch (NullPointerException e) {
-            throw new IllegalStateException("problem parsing stats: " + e);
+            throw new ProtocolException("problem parsing stats", e);
         } catch (NumberFormatException e) {
-            throw new IllegalStateException("problem parsing stats: " + e);
-        } catch (IOException e) {
-            throw new IllegalStateException("problem parsing stats: " + e);
+            throw new ProtocolException("problem parsing stats", e);
         } finally {
             IoUtils.closeQuietly(reader);
             StrictMode.setThreadPolicy(savedPolicy);
@@ -166,17 +164,33 @@
         return stats;
     }
 
-    public NetworkStats readNetworkStatsDetail() {
+    public NetworkStats readNetworkStatsDetail() throws IOException {
         return readNetworkStatsDetail(UID_ALL);
     }
 
+    public NetworkStats readNetworkStatsDetail(int limitUid) throws IOException {
+        if (USE_NATIVE_PARSING) {
+            final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 0);
+            if (nativeReadNetworkStatsDetail(stats, mStatsXtUid.getAbsolutePath(), limitUid) != 0) {
+                throw new IOException("Failed to parse network stats");
+            }
+            if (SANITY_CHECK_NATIVE) {
+                final NetworkStats javaStats = javaReadNetworkStatsDetail(mStatsXtUid, limitUid);
+                assertEquals(javaStats, stats);
+            }
+            return stats;
+        } else {
+            return javaReadNetworkStatsDetail(mStatsXtUid, limitUid);
+        }
+    }
+
     /**
-     * Parse and return {@link NetworkStats} with UID-level details. Values
-     * monotonically increase since device boot.
-     *
-     * @throws IllegalStateException when problem parsing stats.
+     * Parse and return {@link NetworkStats} with UID-level details. Values are
+     * expected to monotonically increase since device boot.
      */
-    public NetworkStats readNetworkStatsDetail(int limitUid) throws IllegalStateException {
+    @VisibleForTesting
+    public static NetworkStats javaReadNetworkStatsDetail(File detailPath, int limitUid)
+            throws IOException {
         final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();
 
         final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 24);
@@ -188,13 +202,13 @@
         ProcFileReader reader = null;
         try {
             // open and consume header line
-            reader = new ProcFileReader(new FileInputStream(mStatsXtUid));
+            reader = new ProcFileReader(new FileInputStream(detailPath));
             reader.finishLine();
 
             while (reader.hasMoreData()) {
                 idx = reader.nextInt();
                 if (idx != lastIdx + 1) {
-                    throw new IllegalStateException(
+                    throw new ProtocolException(
                             "inconsistent idx=" + idx + " after lastIdx=" + lastIdx);
                 }
                 lastIdx = idx;
@@ -215,11 +229,9 @@
                 reader.finishLine();
             }
         } catch (NullPointerException e) {
-            throw new IllegalStateException("problem parsing idx " + idx, e);
+            throw new ProtocolException("problem parsing idx " + idx, e);
         } catch (NumberFormatException e) {
-            throw new IllegalStateException("problem parsing idx " + idx, e);
-        } catch (IOException e) {
-            throw new IllegalStateException("problem parsing idx " + idx, e);
+            throw new ProtocolException("problem parsing idx " + idx, e);
         } finally {
             IoUtils.closeQuietly(reader);
             StrictMode.setThreadPolicy(savedPolicy);
@@ -227,4 +239,30 @@
 
         return stats;
     }
+
+    public void assertEquals(NetworkStats expected, NetworkStats actual) {
+        if (expected.size() != actual.size()) {
+            throw new AssertionError(
+                    "Expected size " + expected.size() + ", actual size " + actual.size());
+        }
+
+        NetworkStats.Entry expectedRow = null;
+        NetworkStats.Entry actualRow = null;
+        for (int i = 0; i < expected.size(); i++) {
+            expectedRow = expected.getValues(i, expectedRow);
+            actualRow = actual.getValues(i, actualRow);
+            if (!expectedRow.equals(actualRow)) {
+                throw new AssertionError(
+                        "Expected row " + i + ": " + expectedRow + ", actual row " + actualRow);
+            }
+        }
+    }
+
+    /**
+     * Parse statistics from file into given {@link NetworkStats} object. Values
+     * are expected to monotonically increase since device boot.
+     */
+    @VisibleForTesting
+    public static native int nativeReadNetworkStatsDetail(
+            NetworkStats stats, String path, int limitUid);
 }
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 4d35a6b..04b9884 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -5956,7 +5956,7 @@
                 if (SystemProperties.getBoolean(PROP_QTAGUID_ENABLED, false)) {
                     try {
                         mNetworkSummaryCache = mNetworkStatsFactory.readNetworkStatsSummaryDev();
-                    } catch (IllegalStateException e) {
+                    } catch (IOException e) {
                         Log.wtf(TAG, "problem reading network stats", e);
                     }
                 }
@@ -5980,7 +5980,7 @@
                     try {
                         mNetworkDetailCache = mNetworkStatsFactory
                                 .readNetworkStatsDetail().groupedByUid();
-                    } catch (IllegalStateException e) {
+                    } catch (IOException e) {
                         Log.wtf(TAG, "problem reading network stats", e);
                     }
                 }
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index f47865e..c6b7631 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -146,7 +146,8 @@
 	android_app_backup_FullBackup.cpp \
 	android_content_res_ObbScanner.cpp \
 	android_content_res_Configuration.cpp \
-    android_animation_PropertyValuesHolder.cpp
+	android_animation_PropertyValuesHolder.cpp \
+	com_android_internal_net_NetworkStatsFactory.cpp
 
 LOCAL_C_INCLUDES += \
 	$(JNI_H_INCLUDE) \
@@ -156,7 +157,7 @@
 	$(call include-path-for, bluedroid) \
 	$(call include-path-for, libhardware)/hardware \
 	$(call include-path-for, libhardware_legacy)/hardware_legacy \
- $(TOP)/frameworks/av/include \
+	$(TOP)/frameworks/av/include \
 	external/skia/include/core \
 	external/skia/include/effects \
 	external/skia/include/images \
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 74fd391..86d3cb6 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -172,6 +172,7 @@
 extern int register_android_content_res_Configuration(JNIEnv* env);
 extern int register_android_animation_PropertyValuesHolder(JNIEnv *env);
 extern int register_com_android_internal_content_NativeLibraryHelper(JNIEnv *env);
+extern int register_com_android_internal_net_NetworkStatsFactory(JNIEnv *env);
 
 static AndroidRuntime* gCurRuntime = NULL;
 
@@ -1204,6 +1205,7 @@
 
     REG_JNI(register_android_animation_PropertyValuesHolder),
     REG_JNI(register_com_android_internal_content_NativeLibraryHelper),
+    REG_JNI(register_com_android_internal_net_NetworkStatsFactory),
 };
 
 /*
diff --git a/core/jni/android/graphics/Canvas.cpp b/core/jni/android/graphics/Canvas.cpp
index 46784ce..886eb6e 100644
--- a/core/jni/android/graphics/Canvas.cpp
+++ b/core/jni/android/graphics/Canvas.cpp
@@ -733,7 +733,7 @@
     }
 
 
-    static void drawText___CIIFFIPaint(JNIEnv* env, jobject, SkCanvas* canvas,
+    static void drawText___CIIFFPaint(JNIEnv* env, jobject, SkCanvas* canvas,
                                       jcharArray text, int index, int count,
                                       jfloat x, jfloat y, SkPaint* paint) {
         jchar* textArray = env->GetCharArrayElements(text, NULL);
@@ -741,7 +741,7 @@
         env->ReleaseCharArrayElements(text, textArray, JNI_ABORT);
     }
 
-    static void drawText__StringIIFFIPaint(JNIEnv* env, jobject,
+    static void drawText__StringIIFFPaint(JNIEnv* env, jobject,
                                           SkCanvas* canvas, jstring text,
                                           int start, int end,
                                           jfloat x, jfloat y, SkPaint* paint) {
@@ -827,10 +827,10 @@
         delete[] posPtr;
     }
 
-    static void drawTextRun___CIIIIFFIPaint(
+    static void drawTextRun___CIIIIFFPaint(
         JNIEnv* env, jobject, SkCanvas* canvas, jcharArray text, int index,
         int count, int contextIndex, int contextCount,
-        jfloat x, jfloat y, int dirFlags, SkPaint* paint) {
+        jfloat x, jfloat y, SkPaint* paint) {
 
         jchar* chars = env->GetCharArrayElements(text, NULL);
         drawTextWithGlyphs(canvas, chars + contextIndex, index - contextIndex,
@@ -838,10 +838,10 @@
         env->ReleaseCharArrayElements(text, chars, JNI_ABORT);
     }
 
-    static void drawTextRun__StringIIIIFFIPaint(
+    static void drawTextRun__StringIIIIFFPaint(
         JNIEnv* env, jobject obj, SkCanvas* canvas, jstring text, jint start,
         jint end, jint contextStart, jint contextEnd,
-        jfloat x, jfloat y, jint dirFlags, SkPaint* paint) {
+        jfloat x, jfloat y, SkPaint* paint) {
 
         jint count = end - start;
         jint contextCount = contextEnd - contextStart;
@@ -1026,13 +1026,13 @@
     {"nativeDrawVertices", "(III[FI[FI[II[SIII)V",
         (void*)SkCanvasGlue::drawVertices},
     {"native_drawText","(I[CIIFFI)V",
-        (void*) SkCanvasGlue::drawText___CIIFFIPaint},
+        (void*) SkCanvasGlue::drawText___CIIFFPaint},
     {"native_drawText","(ILjava/lang/String;IIFFI)V",
-        (void*) SkCanvasGlue::drawText__StringIIFFIPaint},
+        (void*) SkCanvasGlue::drawText__StringIIFFPaint},
     {"native_drawTextRun","(I[CIIIIFFI)V",
-        (void*) SkCanvasGlue::drawTextRun___CIIIIFFIPaint},
+        (void*) SkCanvasGlue::drawTextRun___CIIIIFFPaint},
     {"native_drawTextRun","(ILjava/lang/String;IIIIFFI)V",
-        (void*) SkCanvasGlue::drawTextRun__StringIIIIFFIPaint},
+        (void*) SkCanvasGlue::drawTextRun__StringIIIIFFPaint},
     {"native_drawPosText","(I[CII[FI)V",
         (void*) SkCanvasGlue::drawPosText___CII_FPaint},
     {"native_drawPosText","(ILjava/lang/String;[FI)V",
diff --git a/core/jni/android_net_TrafficStats.cpp b/core/jni/android_net_TrafficStats.cpp
index 9e60904..0df8638 100644
--- a/core/jni/android_net_TrafficStats.cpp
+++ b/core/jni/android_net_TrafficStats.cpp
@@ -87,8 +87,8 @@
 
     while (fgets(buffer, sizeof(buffer), fp) != NULL) {
         int matched = sscanf(buffer, "%31s %llu %llu %llu %llu "
-                "%*llu %llu %*llu %*llu %*llu %*llu "
-                "%*llu %llu %*llu %*llu %*llu %*llu", cur_iface, &rxBytes,
+                "%*u %llu %*u %*u %*u %*u "
+                "%*u %llu %*u %*u %*u %*u", cur_iface, &rxBytes,
                 &rxPackets, &txBytes, &txPackets, &tcpRxPackets, &tcpTxPackets);
         if (matched >= 5) {
             if (matched == 7) {
diff --git a/core/jni/com_android_internal_net_NetworkStatsFactory.cpp b/core/jni/com_android_internal_net_NetworkStatsFactory.cpp
new file mode 100644
index 0000000..0906593
--- /dev/null
+++ b/core/jni/com_android_internal_net_NetworkStatsFactory.cpp
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "NetworkStats"
+
+#include <errno.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#include <android_runtime/AndroidRuntime.h>
+#include <cutils/logger.h>
+#include <jni.h>
+
+#include <ScopedUtfChars.h>
+#include <ScopedLocalRef.h>
+#include <ScopedPrimitiveArray.h>
+
+#include <utils/Log.h>
+#include <utils/misc.h>
+#include <utils/Vector.h>
+
+namespace android {
+
+static jclass gStringClass;
+
+static struct {
+    jfieldID size;
+    jfieldID iface;
+    jfieldID uid;
+    jfieldID set;
+    jfieldID tag;
+    jfieldID rxBytes;
+    jfieldID rxPackets;
+    jfieldID txBytes;
+    jfieldID txPackets;
+    jfieldID operations;
+} gNetworkStatsClassInfo;
+
+struct stats_line {
+    int32_t idx;
+    char iface[32];
+    int32_t uid;
+    int32_t set;
+    int32_t tag;
+    int64_t rxBytes;
+    int64_t rxPackets;
+    int64_t txBytes;
+    int64_t txPackets;
+};
+
+static int readNetworkStatsDetail(JNIEnv* env, jclass clazz, jobject stats,
+        jstring path, jint limitUid) {
+    ScopedUtfChars path8(env, path);
+    if (path8.c_str() == NULL) {
+        return -1;
+    }
+
+    FILE *fp = fopen(path8.c_str(), "r");
+    if (fp == NULL) {
+        return -1;
+    }
+
+    Vector<stats_line> lines;
+
+    int lastIdx = 1;
+    char buffer[384];
+    while (fgets(buffer, sizeof(buffer), fp) != NULL) {
+        stats_line s;
+        int64_t rawTag;
+        if (sscanf(buffer, "%d %31s 0x%llx %u %u %llu %llu %llu %llu", &s.idx,
+                &s.iface, &rawTag, &s.uid, &s.set, &s.rxBytes, &s.rxPackets,
+                &s.txBytes, &s.txPackets) == 9) {
+            if (s.idx != lastIdx + 1) {
+                ALOGE("inconsistent idx=%d after lastIdx=%d", s.idx, lastIdx);
+                return -1;
+            }
+            lastIdx = s.idx;
+
+            s.tag = rawTag >> 32;
+            lines.push_back(s);
+        }
+    }
+
+    if (fclose(fp) != 0) {
+        return -1;
+    }
+
+    int size = lines.size();
+
+    ScopedLocalRef<jobjectArray> iface(env, env->NewObjectArray(size, gStringClass, NULL));
+    if (iface.get() == NULL) return -1;
+    ScopedIntArrayRW uid(env, env->NewIntArray(size));
+    if (uid.get() == NULL) return -1;
+    ScopedIntArrayRW set(env, env->NewIntArray(size));
+    if (set.get() == NULL) return -1;
+    ScopedIntArrayRW tag(env, env->NewIntArray(size));
+    if (tag.get() == NULL) return -1;
+    ScopedLongArrayRW rxBytes(env, env->NewLongArray(size));
+    if (rxBytes.get() == NULL) return -1;
+    ScopedLongArrayRW rxPackets(env, env->NewLongArray(size));
+    if (rxPackets.get() == NULL) return -1;
+    ScopedLongArrayRW txBytes(env, env->NewLongArray(size));
+    if (txBytes.get() == NULL) return -1;
+    ScopedLongArrayRW txPackets(env, env->NewLongArray(size));
+    if (txPackets.get() == NULL) return -1;
+    ScopedLongArrayRW operations(env, env->NewLongArray(size));
+    if (operations.get() == NULL) return -1;
+
+    for (int i = 0; i < size; i++) {
+        ScopedLocalRef<jstring> ifaceString(env, env->NewStringUTF(lines[i].iface));
+        env->SetObjectArrayElement(iface.get(), i, ifaceString.get());
+
+        uid[i] = lines[i].uid;
+        set[i] = lines[i].set;
+        tag[i] = lines[i].tag;
+        rxBytes[i] = lines[i].rxBytes;
+        rxPackets[i] = lines[i].rxPackets;
+        txBytes[i] = lines[i].txBytes;
+        txPackets[i] = lines[i].txPackets;
+    }
+
+    env->SetIntField(stats, gNetworkStatsClassInfo.size, size);
+    env->SetObjectField(stats, gNetworkStatsClassInfo.iface, iface.get());
+    env->SetObjectField(stats, gNetworkStatsClassInfo.uid, uid.getJavaArray());
+    env->SetObjectField(stats, gNetworkStatsClassInfo.set, set.getJavaArray());
+    env->SetObjectField(stats, gNetworkStatsClassInfo.tag, tag.getJavaArray());
+    env->SetObjectField(stats, gNetworkStatsClassInfo.rxBytes, rxBytes.getJavaArray());
+    env->SetObjectField(stats, gNetworkStatsClassInfo.rxPackets, rxPackets.getJavaArray());
+    env->SetObjectField(stats, gNetworkStatsClassInfo.txBytes, txBytes.getJavaArray());
+    env->SetObjectField(stats, gNetworkStatsClassInfo.txPackets, txPackets.getJavaArray());
+    env->SetObjectField(stats, gNetworkStatsClassInfo.operations, operations.getJavaArray());
+
+    return 0;
+}
+
+static jclass findClass(JNIEnv* env, const char* name) {
+    ScopedLocalRef<jclass> localClass(env, env->FindClass(name));
+    jclass result = reinterpret_cast<jclass>(env->NewGlobalRef(localClass.get()));
+    if (result == NULL) {
+        ALOGE("failed to find class '%s'", name);
+        abort();
+    }
+    return result;
+}
+
+static JNINativeMethod gMethods[] = {
+        { "nativeReadNetworkStatsDetail",
+                "(Landroid/net/NetworkStats;Ljava/lang/String;I)I",
+                (void*) readNetworkStatsDetail }
+};
+
+int register_com_android_internal_net_NetworkStatsFactory(JNIEnv* env) {
+    int err = AndroidRuntime::registerNativeMethods(env,
+            "com/android/internal/net/NetworkStatsFactory", gMethods,
+            NELEM(gMethods));
+
+    gStringClass = findClass(env, "java/lang/String");
+
+    jclass clazz = env->FindClass("android/net/NetworkStats");
+    gNetworkStatsClassInfo.size = env->GetFieldID(clazz, "size", "I");
+    gNetworkStatsClassInfo.iface = env->GetFieldID(clazz, "iface", "[Ljava/lang/String;");
+    gNetworkStatsClassInfo.uid = env->GetFieldID(clazz, "uid", "[I");
+    gNetworkStatsClassInfo.set = env->GetFieldID(clazz, "set", "[I");
+    gNetworkStatsClassInfo.tag = env->GetFieldID(clazz, "tag", "[I");
+    gNetworkStatsClassInfo.rxBytes = env->GetFieldID(clazz, "rxBytes", "[J");
+    gNetworkStatsClassInfo.rxPackets = env->GetFieldID(clazz, "rxPackets", "[J");
+    gNetworkStatsClassInfo.txBytes = env->GetFieldID(clazz, "txBytes", "[J");
+    gNetworkStatsClassInfo.txPackets = env->GetFieldID(clazz, "txPackets", "[J");
+    gNetworkStatsClassInfo.operations = env->GetFieldID(clazz, "operations", "[J");
+
+    return err;
+}
+
+}
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 5d0614c..d77b504 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -129,6 +129,7 @@
     <protected-broadcast android:name="android.net.conn.CONNECTIVITY_CHANGE" />
     <protected-broadcast android:name="android.net.conn.CONNECTIVITY_CHANGE_IMMEDIATE" />
     <protected-broadcast android:name="android.net.conn.DATA_ACTIVITY_CHANGE" />
+    <protected-broadcast android:name="android.net.conn.CAPTIVE_PORTAL_TEST_COMPLETED" />
 
     <protected-broadcast android:name="android.nfc.action.LLCP_LINK_STATE_CHANGED" />
     <protected-broadcast android:name="com.android.nfc_extras.action.RF_FIELD_ON_DETECTED" />
@@ -641,7 +642,7 @@
         android:protectionLevel="normal"
         android:description="@string/permdesc_accessWifiState"
         android:label="@string/permlab_accessWifiState" />
-        
+
     <!-- Allows applications to change Wi-Fi connectivity state -->
     <permission android:name="android.permission.CHANGE_WIFI_STATE"
         android:permissionGroup="android.permission-group.NETWORK"
@@ -681,14 +682,14 @@
         android:protectionLevel="dangerous"
         android:description="@string/permdesc_bluetooth"
         android:label="@string/permlab_bluetooth" />
-        
+
     <!-- Allows applications to discover and pair bluetooth devices -->
     <permission android:name="android.permission.BLUETOOTH_ADMIN"
         android:permissionGroup="android.permission-group.BLUETOOTH_NETWORK"
         android:protectionLevel="dangerous"
         android:description="@string/permdesc_bluetoothAdmin"
         android:label="@string/permlab_bluetoothAdmin" />
-   
+
     <!-- Allows bluetooth stack to access files
          @hide This should only be used by Bluetooth apk.
     -->
@@ -719,7 +720,7 @@
     <permission android:name="android.permission.LOOP_RADIO"
 	android:permissionGroup="android.permission-group.NETWORK"
 	android:protectionLevel="signature|system" />
-    
+
     <!-- ================================== -->
     <!-- Permissions for accessing accounts -->
     <!-- ================================== -->
@@ -1129,7 +1130,7 @@
         android:protectionLevel="signature|system"
         android:label="@string/permlab_manageUsers"
         android:description="@string/permdesc_manageUsers" />
-    
+
     <!-- Allows an application to get full detailed information about
          recently running tasks, with full fidelity to the real state.
          @hide -->
@@ -1671,7 +1672,7 @@
         android:label="@string/permlab_freezeScreen"
         android:description="@string/permdesc_freezeScreen"
         android:protectionLevel="signature" />
-    
+
     <!-- Allows an application to inject user events (keys, touch, trackball)
          into the event stream and deliver them to ANY window.  Without this
          permission, you can only deliver events to windows in your own process.
diff --git a/core/tests/benchmarks/src/com/android/internal/net/NetworkStatsFactoryBenchmark.java b/core/tests/benchmarks/src/com/android/internal/net/NetworkStatsFactoryBenchmark.java
new file mode 100644
index 0000000..2174be5
--- /dev/null
+++ b/core/tests/benchmarks/src/com/android/internal/net/NetworkStatsFactoryBenchmark.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2012 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.internal.net;
+
+import android.net.NetworkStats;
+import android.os.SystemClock;
+
+import com.google.caliper.SimpleBenchmark;
+
+import java.io.File;
+
+public class NetworkStatsFactoryBenchmark extends SimpleBenchmark {
+    private File mStats;
+
+    // TODO: consider staging stats file with different number of rows
+
+    @Override
+    protected void setUp() {
+        mStats = new File("/proc/net/xt_qtaguid/stats");
+    }
+
+    @Override
+    protected void tearDown() {
+        mStats = null;
+    }
+
+    public void timeReadNetworkStatsDetailJava(int reps) throws Exception {
+        for (int i = 0; i < reps; i++) {
+            NetworkStatsFactory.javaReadNetworkStatsDetail(mStats, NetworkStats.UID_ALL);
+        }
+    }
+
+    public void timeReadNetworkStatsDetailNative(int reps) {
+        for (int i = 0; i < reps; i++) {
+            final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 0);
+            NetworkStatsFactory.nativeReadNetworkStatsDetail(
+                    stats, mStats.getAbsolutePath(), NetworkStats.UID_ALL);
+        }
+    }
+}
diff --git a/docs/html/google/google_toc.cs b/docs/html/google/google_toc.cs
index 8b09fe6..81982a1 100644
--- a/docs/html/google/google_toc.cs
+++ b/docs/html/google/google_toc.cs
@@ -80,6 +80,9 @@
               <span class="en">Reference</span></a></li>
               </ul>
       </li>
+      <li><a href="<?cs var:toroot?>google/play/billing/billing_subscriptions.html">
+              <span class="en">Subscriptions</span></a>
+      </li>
       <li><a href="<?cs var:toroot?>google/play/billing/billing_best_practices.html">
               <span class="en">Security and Design</span></a>
       </li>
diff --git a/docs/html/google/play/billing/api.jd b/docs/html/google/play/billing/api.jd
index 9091f51..3d46715 100644
--- a/docs/html/google/play/billing/api.jd
+++ b/docs/html/google/play/billing/api.jd
@@ -11,12 +11,13 @@
     <li><a href="#producttypes">Product Types</a>
        <ol>
        <li><a href="#managed">Managed In-app Products</a><li>
+       <li><a href="#subs">Subscriptions</a><li>
        </ol>
     </li>
     <li><a href="#purchase">Purchasing Items</a></li>
-    <li><a href="#consume">Consuming Items</a>
+    <li><a href="#consume">Consuming In-app Products</a>
        <ol>
-       <li><a href="#consumetypes">Non-consumable and Consumable Items</a><li>
+       <li><a href="#consumetypes">Non-consumable and Consumable In-app Products</a><li>
        <li><a href="#managingconsumables">Managing Consumable Purchases</a><li>
        </ol>
     </li>
@@ -40,11 +41,22 @@
 
 <h2 id="producttypes">Product Types</h2>
 <p>You define your products using the Google Play Developer Console, including product type, SKU, price, description, and so on. For more information, see <a
-href="{@docRoot}google/play/billing/billing_admin.html">Administering In-app Billing</a>. The Version 3 API only supports the managed in-app product type.</p>
+href="{@docRoot}google/play/billing/billing_admin.html">Administering In-app Billing</a>. The Version 3 API supports managed in-app products and subscriptions.</p>
 <h3 id="managed">Managed In-app Products</h3>
 <p>Managed in-app products are items that have their ownership information tracked and managed by Google Play. When a user purchases a managed in-app item, Google Play stores the purchase information for each item on a per-user basis. This enables you to later query Google Play at any time to restore the state of the items a specific user has purchased. This information is persistent on the Google Play servers even if the user uninstalls the application or if they change devices.</p>
 <p>If you are using the Version 3 API, you can also consume managed items within your application. You would typically implement consumption for items that can be purchased multiple times (such as in-game currency, fuel, or magic spells). Once purchased, a managed item cannot be purchased again until you consume the item, by sending a consumption request to Google Play. To learn more about in-app product consumption, see <a href="#consume">Consuming Items</a></p>
 
+<h3 id="subs">Subscriptions</h3>
+<p>A subscription is a product type offered in In-app Billing that lets you sell 
+content, services, or features to users from inside your app with recurring 
+monthly or annual billing. You can sell subscriptions to almost any type of 
+digital content, from any type of app or game. To understand how  
+subscriptions work, see <a href="{@docRoot}google/play/billing/billing_subscriptions.html">In-app Billing Subscriptions</a>.</p>
+<p>With the Version 3 API, you can use the same purchase flow for buying 
+subscriptions and retrieving subscription purchase information as with in-app 
+products. For a code example, see <a href="{@docRoot}google/play/billing/billing_integrate.html#Subs">Implementing Subscriptions</a>.</p>
+<p class="caution"><strong>Important</strong>: Unlike in-app products, 
+subscriptions cannot be consumed.</p>
 
 <h2 id="purchase">Purchasing Items</h2>
 
@@ -72,29 +84,38 @@
 </p>
 <p>To learn more about the Version 3 API calls and server responses, see <a href="{@docRoot}google/play/billing/billing_reference.html">In-app Billing Reference</a>.</p>
 
-<h2 id="consume">Consuming Items</h2>
-<p>You can use the consumption mechanism to track the user's ownership of in-app products.</p>
-<p>In Version 3, all in-app products are managed. This means that the user's ownership of all in-app item purchases is maintained by Google Play, and your application can query the user's purchase information when needed. When the user successfully purchases an item, that purchase is recorded in Google Play. Once an item is purchased, it is considered to be "owned". Items in the "owned" state cannot be purchased from Google Play. You must send a consumption request for the "owned" item before Google Play makes it available for purchase again. Consuming the item reverts it to the "unowned" state, and discards the previous purchase data.</p>
+<h2 id="consume">Consuming In-app Products</h2>
+<p>You can use the consumption mechanism to track the user's ownership of in-app 
+products.</p>
+<p>In Version 3, all in-app products are managed. This means that the user's 
+ownership of all in-app item purchases is maintained by Google Play, and your 
+application can query the user's purchase information when needed. When the user 
+successfully purchases an in-app product, that purchase is recorded in Google 
+Play. Once an in-app product is purchased, it is considered to be "owned". 
+In-app products in the "owned" state cannot be purchased from Google Play. You 
+must send a consumption request for the "owned" in-app product before Google 
+Play makes it available for purchase again. Consuming the in-app product reverts 
+it to the "unowned" state, and discards the previous purchase data.</p>
 <div class="figure" style="width:420px">
 <img src="{@docRoot}images/in-app-billing/v3/iab_v3_consumption_flow.png" id="figure2" height="300"/>
 <p class="img-caption">
   <strong>Figure 2.</strong> The basic sequence for a consumption request.
 </p>
 </div>
-<p>To retrieve the list of product's owned by the user, your application sends a {@code getPurchases} call to Google Play. Your application can make a consumption request by sending a {@code consumePurchase} call. In the request argument, you must specify the item's unique {@code purchaseToken} String that you obtained from Google Play when it was purchased. Google Play returns a status code indicating if the consumption was recorded successfully.</p>
+<p>To retrieve the list of product's owned by the user, your application sends a {@code getPurchases} call to Google Play. Your application can make a consumption request by sending a {@code consumePurchase} call. In the request argument, you must specify the in-app product's unique {@code purchaseToken} String that you obtained from Google Play when it was purchased. Google Play returns a status code indicating if the consumption was recorded successfully.</p>
 
-<h3 id="consumetypes">Non-consumable and Consumable Items</h3>
+<h3 id="consumetypes">Non-consumable and Consumable In-app Products</h3>
 <p>It's up to you to decide if you want to handle your in-app products as non-consumable or consumable items.</p>
 <dl>
 <dt>Non-consumable Items</dt>
-<dd>Typically, you would not implement consumption for items that can only be purchased once in your application and provide a permanent benefit. Once purchased, these items will be permanently associated to the user's Google account. An example of a non-consumable item is a premium upgrade or a level pack.</dd>
+<dd>Typically, you would not implement consumption for in-app products that can only be purchased once in your application and provide a permanent benefit. Once purchased, these items will be permanently associated to the user's Google account. An example of a non-consumable in-app product is a premium upgrade or a level pack.</dd>
 <dt>Consumable items</dt>
 <dd>In contrast, you can implement consumption for items that can be made available for purchase multiple times. Typically, these items provide certain temporary effects. For example, the user's in-game character might gain life points or gain extra gold coins in their inventory. Dispensing the benefits or effects of the purchased item in your application is called <em>provisioning</em> the in-app product. You are responsible for controlling and tracking how in-app products are provisioned to the users.
-<p class="note"><strong>Important:</strong> Before provisioning the consumable item in your application, you must send a consumption request to Google Play and receive a successful response indicating that the consumption was recorded.</p>
+<p class="note"><strong>Important:</strong> Before provisioning the consumable in-app product in your application, you must send a consumption request to Google Play and receive a successful response indicating that the consumption was recorded.</p>
 </dd>
 </dl>
 <h3 id="managingconsumables">Managing consumable purchases in your application</h3>
-<p>Here is the basic flow for purchasing a consumable item:</p>
+<p>Here is the basic flow for purchasing a consumable in-app product:</p>
 <ol>
 <li>Launch a purchase flow with a {@code getBuyIntent} call</li>
 <li>Get a response {@code Bundle}from Google Play indicating if the purchase completed successfully.</li>
@@ -102,10 +123,10 @@
 <li>Get a response code from Google Play indicating if the consumption completed successfully.</li>
 <li>If the consumption was successful, provision the product in your application.</li>
 </ol>
-<p>Subsequently, when the user starts up or logs in to your application, you should check if the user owns any outstanding consumable items; if so, make sure to consume and provision those items. Here's the recommended application startup flow if you implement consumable items in your application:</p>
+<p>Subsequently, when the user starts up or logs in to your application, you should check if the user owns any outstanding consumable in-app products; if so, make sure to consume and provision those items. Here's the recommended application startup flow if you implement consumable in-app products in your application:</p>
 <ol>
-<li>Send a {@code getPurchases} request to query the owned items for the user.</li>
-<li>If there are any consumable items, consume the items by calling {@code consumePurchase}. This step is necessary because the application might have completed the purchase order for the consumable item, but stopped or got disconnected before the application had the chance to send a consumption request.</li>
+<li>Send a {@code getPurchases} request to query the owned in-app products for the user.</li>
+<li>If there are any consumable in-app products, consume the items by calling {@code consumePurchase}. This step is necessary because the application might have completed the purchase order for the consumable item, but stopped or got disconnected before the application had the chance to send a consumption request.</li>
 <li>Get a response code from Google Play indicating if the consumption completed successfully.</li>
 <li>If the consumption was successful, provision the product in your application.</li>
 </ol>
diff --git a/docs/html/google/play/billing/billing_integrate.jd b/docs/html/google/play/billing/billing_integrate.jd
index 315befa..297e906 100644
--- a/docs/html/google/play/billing/billing_integrate.jd
+++ b/docs/html/google/play/billing/billing_integrate.jd
@@ -16,6 +16,7 @@
        <li><a href="#Purchase">Purchasing an Item</a></li>
        <li><a href="#QueryPurchases">Querying Purchased Items</a></li>
        <li><a href="#Consume">Consuming a Purchase</a><li>
+       <li><a href="#Subs">Implementing Subscriptions</a><li>
        </ol>
     </li>
   </ol>
@@ -176,7 +177,7 @@
 </pre>
 
 <h3 id="Purchase">Purchasing an Item</h3>
-<p>To start a purchase request from your app, call the {@code getBuyIntent} method on the In-app Billing service. Pass in to the method the In-app Billing API version (“3”), the package name of your calling app, the product ID for the item to purchase, the purchase type (“inapp”), and a {@code developerPayload} String. The {@code developerPayload} String is used to  specify any additional arguments that you want Google Play to send back along with the purchase information.</p>
+<p>To start a purchase request from your app, call the {@code getBuyIntent} method on the In-app Billing service. Pass in to the method the In-app Billing API version (“3”), the package name of your calling app, the product ID for the item to purchase, the purchase type (“inapp” or "subs"), and a {@code developerPayload} String. The {@code developerPayload} String is used to  specify any additional arguments that you want Google Play to send back along with the purchase information.</p>
 
 <pre>
 Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(),
@@ -238,7 +239,7 @@
 <p class="note"><strong>Security Recommendation:</strong> When you send a purchase request, create a String token that uniquely identifies this purchase request and include this token in the {@code developerPayload}.You can use a randomly generated string as the token. When you receive the purchase response from Google Play, make sure to check the returned data signature, the {@code orderId}, and the {@code developerPayload} String. For added security, you should perform the checking on your own secure server. Make sure to verify that the {@code orderId} is a unique value that you have not previously processed, and the {@code developerPayload} String matches the token that you sent previously with the purchase request.</p>
 
 <h3 id="QueryPurchases">Querying for Purchased Items</h3>
-<p>To retrieve information about purchases made by a user from your app, call the {@code getPurchases} method on the In-app Billing Version 3 service. Pass in to the method the In-app Billing API version (“3”), the package name of your calling app, and the purchase type (“inapp”).</p>
+<p>To retrieve information about purchases made by a user from your app, call the {@code getPurchases} method on the In-app Billing Version 3 service. Pass in to the method the In-app Billing API version (“3”), the package name of your calling app, and the purchase type (“inapp” or "subs").</p>
 <pre>
 Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
 </pre>
@@ -273,8 +274,26 @@
 </pre>
 
 <h3 id="Consume">Consuming a Purchase</h3>
-<p>You can use the In-app Billing Version 3 API to track the ownership of purchased items in Google Play. Once an item is purchased, it is considered to be "owned" and cannot be purchased from Google Play. You must send a consumption request for the item before Google Play makes it available for purchase again. All managed in-app products are consumable.  How you use the consumption mechanism in your app is up to you. Typically, you would implement consumption for products with temporary benefits that users may want to purchase multiple times (for example, in-game currency or equipment). You would typically not want to implement consumption for products that are purchased once and provide a permanent effect (for example, a premium upgrade).</p>
-<p>To record a purchase consumption, send the {@code consumePurchase} method to the In-app Billing service and pass in the {@code purchaseToken} String value that identifies the purchase to be removed. The {@code purchaseToken} is part of the data returned in the {@code INAPP_PURCHASE_DATA} String by the Google Play service following a successful purchase request. In this example, you are recording the consumption of a product that is identified with the {@code purchaseToken} in the {@code token} variable.</p>
+<p>You can use the In-app Billing Version 3 API to track the ownership of 
+purchased in-app products in Google Play. Once an in-app product is purchased, 
+it is considered to be "owned" and cannot be purchased from Google Play. You 
+must send a consumption request for the in-app product before Google Play makes 
+it available for purchase again.</p>
+<p class="caution"><strong>Important</strong>: Managed in-app products are 
+consumable, but subscriptions are not.</p>
+<p>How you use the consumption mechanism in your app is up to you. Typically, 
+you would implement consumption for in-app products with temporary benefits that 
+users may want to purchase multiple times (for example, in-game currency or 
+equipment). You would typically not want to implement consumption for in-app 
+products that are purchased once and provide a permanent effect (for example, 
+a premium upgrade).</p>
+<p>To record a purchase consumption, send the {@code consumePurchase} method to 
+the In-app Billing service and pass in the {@code purchaseToken} String value 
+that identifies the purchase to be removed. The {@code purchaseToken} is part 
+of the data returned in the {@code INAPP_PURCHASE_DATA} String by the Google 
+Play service following a successful purchase request. In this example, you are 
+recording the consumption of a product that is identified with the 
+{@code purchaseToken} in the {@code token} variable.</p>
 <pre>
 int response = mService.consumePurchase(3, getPackageName(), token);
 </pre>
@@ -282,6 +301,33 @@
 <p>It's your responsibility to control and track how the in-app product is provisioned to the user. For example, if the user purchased in-game currency, you should update the player's inventory with the amount of currency purchased.</p>
 <p class="note"><strong>Security Recommendation:</strong> You must send a consumption request before provisioning the benefit of the consumable in-app purchase to the user. Make sure that you have received a successful consumption response from Google Play before you provision the item.</p>
 
+<h3 id="Subs">Implementing Subscriptions</h3>
+<p>Launching a purchase flow for a subscription is similar to launching the 
+purchase flow for a product, with the exception that the product type must be set 
+to "subs". The purchase result is delivered to your Activity's 
+{@link android.app.Activity#onActivityResult onActivityResult} method, exactly 
+as in the case of in-app products.</p>
+<pre>
+Bundle bundle = mService.getBuyIntent(3, "com.example.myapp",
+   MY_SKU, "subs", developerPayload);
+
+PendingIntent pendingIntent = bundle.getParcelable(RESPONSE_BUY_INTENT);
+if (bundle.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) {
+   // Start purchase flow (this brings up the Google Play UI).
+   // Result will be delivered through onActivityResult().
+   startIntentSenderForResult(pendingIntent, RC_BUY, new Intent(),
+       Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
+}
+</pre>
+<p>To query for active subscriptions, use the {@code getPurchases} method, again 
+with the product type parameter set to "subs".</p>
+<pre>
+Bundle activeSubs = mService.getPurchases(3, "com.example.myapp",
+                   "subs", continueToken);
+</pre>
+<p>The call returns a {@code Bundle} with all the active subscriptions owned by 
+the user. Once a subscription expires without renewal, it will no longer appear 
+in the returned {@code Bundle}.</p>
 
 
 
diff --git a/docs/html/google/play/billing/billing_overview.jd b/docs/html/google/play/billing/billing_overview.jd
index aa48fc8..14cbfdf 100644
--- a/docs/html/google/play/billing/billing_overview.jd
+++ b/docs/html/google/play/billing/billing_overview.jd
@@ -7,9 +7,12 @@
 <div id="qv">
   <h2>Quickview</h2>
   <ul>
-    <li>Use In-app Billing to sell digital goods, including one-time items and recurring subscriptions.</li>
-    <li>Supported for any app published on Google Play. You only need a Google Play publisher account and a Google Checkout Merchant account.</li>
-    <li>Checkout processing is automatically handled by Google Play, with the same look-and-feel as for app purchases.</li>
+    <li>Use In-app Billing to sell digital goods, including one-time items and 
+recurring subscriptions.</li>
+    <li>Supported for any app published on Google Play. You only need a Google 
+Play Developer Console account and a Google Checkout Merchant account.</li>
+    <li>Checkout processing is automatically handled by Google Play, with the 
+same look-and-feel as for app purchases.</li>
   </ul>
   <h2>In this document</h2>
   <ol>
@@ -21,14 +24,12 @@
     </li>
     <li><a href="#console">Google Play Developer Console</a></li>
     <li><a href="#checkout">Google Play Purchase Flow</a></li>
-    <li><a href="#samples">Sample Apps</a></li> 
+    <li><a href="#samples">Sample App</a></li> 
     <li><a href="#migration">Migration Considerations</a></li>
   </ol>
    <h2>Related Samples</h2>
   <ol>
     <li><a href="{@docRoot}training/in-app-billing/preparing-iab-app.html#GetSample">Sample Application (V3)</a></li>
-    <li><a href="{@docRoot}google/play/billing/v2/billing_integrate.html#billing-download">Sample
-    Application (V2)</a></li>
   </ol> 
 </div>
 </div>
@@ -51,10 +52,12 @@
 through Google Play. To complete in-app purchase requests, the Google Play app 
 must be able to access the Google Play server over the network.</p>
 
-<p>Currently, Google Play supports two versions of the In-app Billing API. 
-To determine which version you should use, see <a href="#migration">Migration 
-Considerations</a>.</p>
-<h4><a href="{@docRoot}google/play/billing/api.html">Version 3</a> (recommended)</h4>
+<p>In-app billing Version 3 is the latest version, and maintains very broad 
+compatibility across the range of Android devices. In-app Billing Version 3 is 
+supported on devices running Android 2.2 or higher that have the latest version 
+of the Google Play store installed (<a href="{@docRoot}about/dashboards/index.html">a vast majority</a> of active devices).</p>
+
+<h4>Version 3 features</h4>
 <ul>
 <li>Requests are sent through a streamlined API that allows you to easily request 
 product details from Google Play, order in-app products, and quickly restore 
@@ -66,21 +69,11 @@
 item; only one copy can be owned at any point in time</li>
 <li>Purchased items can be consumed. When consumed, the item reverts to the 
 "unowned" state and can be purchased again from Google Play</li>
+<li>Provides support for <a
+  href="{@docRoot}google/play/billing/billing_subscriptions.html">subscriptions</a></li>
 </ul>
-<h4><a href="{@docRoot}google/play/billing/v2/api.html">Version 2</a></h4>
-<ul>
-<li>Requests are sent via a single API interface ({@code sendBillingRequest})</li>
-<li>Responses from Google Play are asynchronous, in the form of broadcast intents</li>
-<li>No consumption model provided. You have to implement your own solution</li>
-<li>Provides support for subscriptions and unmanaged in-app purchase items, 
-as well as managed in-app products</li>
-</ul>
-<p>Both versions offer very broad compatibility across the range of Android 
-devices. In-app Billing Version 3 is supported on devices running Android 2.2 or 
-higher that have the latest version of the Google Play store installed 
-(over 90% of active devices). Version 2 offers similar compatibility. See 
-<a href="{@docRoot}google/play/billing/versions.html">Version Notes</a> for 
-more details.</p>
+<p>For details about other versions of In-app Billing, see the 
+<a href="{@docRoot}google/play/billing/versions.html">Version Notes</a>.</p>
 
 <h2 id="products">In-app Products</h2>
 <p>In-app products are the digital goods that you offer for sale from inside your 
@@ -102,12 +95,9 @@
 how you monetize your application. In all cases, you define your products using 
 the Google Play Developer Console.</p>
 <p>You can specify these types of products for your In-app Billing application  
-— <em>managed in-app products</em>, <em>subscriptions</em>, and <em>unmanaged 
-in-app products</em>.  The term “managed” indicates that Google Play handles and 
-tracks ownership for in-app products on your application on a per user account 
-basis, while “unmanaged” indicates that you will manage the ownership  information yourself.</p>
-<p>To learn more about the product types supported by the different API versions, 
-see the related documentation for <a href="{@docRoot}google/play/billing/v2/api.html#billing-types">Version 2</a> and <a href="{@docRoot}google/play/billing/api.html#producttypes">Version 3</a>.</p>
+— <em>managed in-app products</em> and <em>subscriptions</em>. Google Play 
+handles and tracks ownership for in-app products and subscriptions on your 
+application on a per user account basis. <a href="{@docRoot}google/play/billing/api.html#producttypes">Learn more about the product types supported by In-app Billing Version 3</a>.</p>
 
 <h2 id="console">Google Play Developer Console</h2>
 <p>The Developer Console is where you can publish your 
@@ -148,70 +138,31 @@
 complete, the application resumes.
 </p>
 
-<h2 id="samples">Sample Applications</h2>
+<h2 id="samples">Sample Application</h2>
 <p>To help you integrate In-app Billing into your application, the Android SDK 
-provides two sample applications that demonstrate how to sell in-app products 
+provides a sample application that demonstrates how to sell in-app products and subscriptions 
 from inside an app.</p>
 
-<dl>
-<dt><a href="{@docRoot}training/in-app-billing/preparing-iab-app.html#GetSample">TrivialDrive sample for the Version 3 API</a></dt>
-<dd>This sample shows how to use the In-app Billing Version 3 API to implement 
-in-app product purchases for a driving game. The application demonstrates how to 
-send In-app Billing requests, and handle synchronous responses from Google Play. 
-The application also shows how to record item consumption with the API. The 
-Version 3 sample includes convenience classes for processing In-app Billing 
-operations as well as perform automatic signature verification.</dd>
+<p>The <a href="{@docRoot}training/in-app-billing/preparing-iab-app.html#GetSample">TrivialDrive sample for the Version 3 API</a> sample shows how to use the In-app Billing Version 3 API 
+to implement in-app product and subscription purchases for a driving game. The 
+application demonstrates how to send In-app Billing requests, and handle 
+synchronous responses from Google Play. The application also shows how to record 
+item consumption with the API. The Version 3 sample includes convenience classes 
+for processing In-app Billing operations as well as perform automatic signature 
+verification.</p>
 
-<dt><a href="{@docRoot}google/play/billing/v2/billing_integrate.html#billing-download">Dungeons sample for the Version 2 API</a></dt>
-<dd>This sample demonstrates how to use the In-app Billing Version 2 API to sell 
-standard in-app products and subscriptions for an adventuring game. It also 
-contains examples of the database, user interface, and business logic you might 
-use to implement In-app Billing.</dd>
-</dl>
-<p class="caution"><strong>Important</strong>: It's <em>strongly recommended</em> 
-that you obfuscate the code in your application before you publish it. For 
-more information, see
+<p class="caution"><strong>Recommendation</strong>: Make sure to obfuscate the 
+code in your application before you publish it. For more information, see
 <a href="{@docRoot}google/play/billing/billing_best_practices.html">Security 
 and Design</a>.</p>
 
 <h2 id="migration">Migration Considerations</h2>
-<p>The following considerations may be applicable if you are planning to create a new 
-in-app biling application, or migrate your existing In-app Billing implementation 
-from the <a href="{@docRoot}google/play/billing/v2/api.html">Version 2</a> or 
-earlier API to the <a href="{@docRoot}google/play/billing/api.html">Version 3</a> API.</p>
-<p>Google Play will continue to support both the Version 2 and Version 3 APIs for 
-some time, so you can plan to migrate to Version 3 at your own pace. The Google 
-Play team will give advance notice of any upcoming changes to the support 
-status of In-app Billing Version 2.</p>
-<p>You can use the following table to decide which version of the API to use, 
-depending on the needs of your application.</p>
-<p class="table-caption" id="table1">
-  <strong>Table 1.</strong> Selecting the In-app Billing API Version for Your 
-Project</p>
+<p>If you have an existing In-app Billing implementation that uses Version 2 or
+earlier, it is strongly recommended that you migrate to <a href="{@docRoot}google/play/billing/api.html">In-app Billing Version 3</a> at your earliest convenience.</p>
 
-<table>
-<tr>
-<th scope="col">Choose Version 3 if ...</th>
-<th scope="col">Choose Version 2 if ...</th>
-</tr>
-<tr>
-<td>
-  <ul>
-  <li>You want to sell in-app products only (and not subscriptions)</li>
-  <li>You need synchronous order confirmations when purchases complete</li>
-  <li>You need to synchronously restore a user's current purchases</li>
-  </ul>
-</td>
-<td>
-  <ul>
-  <li>You want to sell subscriptions in your app</li>
-  </ul>
-</td>
-</tr>
-</table>
 <p>If you have published apps selling in-app products, note that:</p>
 <ul>
-<li>Managed items that you have previously defined in the Developer Console will 
+<li>Managed items and subscriptions that you have previously defined in the Developer Console will 
 work with Version 3 as before.</li>
 <li>Unmanaged items that you have defined for existing applications will be 
 treated as managed products if you make a purchase request for these items using 
diff --git a/docs/html/google/play/billing/billing_reference.jd b/docs/html/google/play/billing/billing_reference.jd
index 758e21d..ae41521 100644
--- a/docs/html/google/play/billing/billing_reference.jd
+++ b/docs/html/google/play/billing/billing_reference.jd
@@ -102,11 +102,13 @@
   </tr>
   <tr>
     <td>{@code type}</td>
-    <td>Value must be “inapp” for an in-app purchase type.</td>
+    <td>Value must be “inapp” for an in-app product or "subs" for 
+subscriptions.</td>
   </tr>
   <tr>
     <td>{@code price}</td>
-    <td>Formatted price of the item, including its currency sign. The price does not include tax.</td>
+    <td>Formatted price of the item, including its currency sign. The price 
+does not include tax.</td>
   </tr>
   <tr>
     <td>{@code title}</td>
diff --git a/docs/html/google/play/billing/billing_subscriptions.jd b/docs/html/google/play/billing/billing_subscriptions.jd
new file mode 100644
index 0000000..c2bbb49
--- /dev/null
+++ b/docs/html/google/play/billing/billing_subscriptions.jd
@@ -0,0 +1,433 @@
+page.title=Subscriptions
+parent.title=In-app Billing
+parent.link=index.html
+@jd:body
+
+<!--notice block -->
+    <div style="background-color:#fffbd9;width:100%;margin-bottom:1em;padding:8px 8px 1px;">
+      <p><em>15 February 2013</em></p>
+      <p>In-app Billing V3 now supports subscriptions and you can get
+        started developing today. A small app update is currently being
+        rolled out to Android devices. This process is automatic and
+        most devices will get the update in the next few days. However,
+        if you wish to get the update today to start developing right
+        away, simply reboot your device. </p>
+
+      <p>However, we recommend that you <em>do not publish</em> an app with 
+        V3 subscriptions until all Android devices have received the update. We'll
+        notify you here that all devices have received the update and its safe
+        to publish your apps that use V3 subscriptions. </p>
+    </div>
+
+<!-- Use non-standard wrapper to support notice block. Restore standard 
+     wrapper when notice is removed. -->
+<!--<div id="qv-wrapper"> -->
+<div id="qv-wrapper" style="margin-top:.25em;">
+<div id="qv">
+  <h2>Quickview</h2>
+  <ul>
+     <li>Users purchase your subscriptions from inside your apps, rather than 
+directly from Google Play.</li>
+     <li>Subscriptions let you sell products with automated, recurring billing
+(monthly or annual).</li>
+     <li>You can offer a configurable trial period for any subscription.</li>
+
+  </ul>
+  <h2>In this document</h2>
+  <ol>
+    <li><a href="#overview">Overview</a></li>
+    <li><a href="#administering">Configuring Subscriptions Items</a></li>
+    <li><a href="#cancellation">Cancellation</a></li>
+    <li><a href="#payment">Payment Processing</a></li>
+    <li><a href="#play-dev-api">Google Play Android Developer API</a></li>
+  </ol>
+  <h2>See also</h2>
+  <ol>
+    <li><a href="{@docRoot}google/play/billing/billing_integrate.html#Subs">Implementing Subscriptions (V3)</a></li>
+  </ol>
+</div>
+</div>
+
+<p>Subscriptions let you sell content, services, or features in your app with
+automated, recurring billing. You can easily adapt an existing In-app Billing 
+implementation to sell subscriptions.</p>
+<p>This document is focused on highlighting implementation details that are 
+specific to subscriptions, along with some strategies for the associated billing 
+and business models.</p>
+
+<h2 id="overview">Overview of Subscriptions</h2>
+<p>A <em>subscription</em> is a product type offered in In-app Billing that 
+lets you sell content, services, or features to users from inside your app with 
+recurring monthly or annual billing. You can sell subscriptions to almost any 
+type of digital content, from any type of app or game.</p>
+
+<p>As with other in-app products, you configure and publish subscriptions using
+the Developer Console and then sell them from inside apps installed on 
+Android devices. In the Developer console, you create subscription
+products and add them to a product list, then set a price and optional trial
+period for each, choose a billing interval (monthly or annual), and then 
+publish. For more information about using the Developer Console, see 
+<a href="#administering">Configuring Subscription Items</a>.</p>
+
+<p>When users purchase subscriptions in your apps, Google Play handles all 
+checkout details so your apps never have to directly process any financial 
+transactions. Google Play processes all payments for subscriptions through 
+Google Checkout, just as it does for standard in-app products and app purchases. 
+This ensures a consistent and familiar purchase flow for your users.</p>
+
+<img src="{@docRoot}images/in-app-billing/v3/billing_subscription_v3.png" style="float:right; border:4px solid ddd;">
+
+<p>After users have purchase subscriptions, they can view the subscriptions and 
+cancel them from the <strong>My Apps</strong> screen in the Play Store app or 
+from the app's product details page in the Play Store app. For more information 
+about handling user cancellations, see <a href="#cancellation">Subscription Cancellation</a>.</p>
+
+<p>In adddition to client-side API calls, you can use the server-side API for 
+In-app Billing to provide subscription purchasers with extended access to 
+content (for example, from your web site or another service).
+The server-side API lets you validate the status of a subscription when users
+sign into your other services. For more information about the API, see <a
+href="#play-dev-api">Google Play Android Developer API</a>. </p>
+
+<p>You can also build on your existing external subscriber base from inside your
+Android apps.</p>
+<ul>
+<li>If you sell subscriptions on a web site, for example, you can add
+your own business logic to your Android app to determine whether the user has
+already purchased a subscription elsewhere, then allow access to your content if
+so or offer a subscription purchase from Google Play if not.</li>
+<li>You can implement your own solution for sharing subscriptions across as 
+many different apps or products as you want. For example, you could sell a 
+subscription that gives a subscriber access to an entire collection of apps, 
+games, or other content for a monthly or annual fee. To implement this solution, 
+you could add your own business logic to your app to determine whether the user 
+has already purchased a given subscription and if so, allow access to your 
+content.</li>
+</ul>
+</p>
+
+<p>In general the same basic policies and terms apply to subscriptions as to
+standard in-app products, however there are some differences. For complete
+information about the current policies and terms, please read the <a
+href="http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en
+&answer=140504">policies document</a>.</p>
+
+<p>To learn about the minimum system requirements for 
+subscriptions, see the <a href="{@docRoot}google/play/billing/versions.html#Subs">Version Notes</a>.</p>
+
+<h2 id="administering">Configuring Subscription Items</h2>
+<p>To create and manage subscriptions, use the Developer Console to set up a 
+product list for the app then configure these attributes for each subscription 
+product:</p>
+
+<ul>
+<li>Purchase Type: always set to <strong>Subscription</strong></li>
+<li>Subscription ID:  An identifier for the subscription</li>
+<li>Publishing State: Unpublished/Published</li>
+<li>Language: The default language for displaying the subscription</li>
+<li>Title: The title of the subscription product</li>
+<li>Description: Details that tell the user about the subscription</li>
+<li>Price: USD price of subscription per recurrence</li>
+<li>Recurrence: monthly or yearly</li>
+<li>Additional currency pricing (can be auto-filled)</li>
+</ul>
+
+<p>For details on how to add and configure products in the Developer Console, 
+see <a href="{@docRoot}google/play/billing/billing_admin.html">Administering
+In-app Billing</a>.</p>
+
+<h3 id="pricing">Subscription pricing</h3>
+
+<p>When you create a subscription in the Developer Console, you can set a price
+for it in any available currencies. Each subscription must have a non-zero
+price. You can price multiple subscriptions for the same content differently
+&mdash; for example you could offer a discount on an annual subscription
+relative to the monthly equivalent. </p>
+
+<p class="caution"><strong>Important</strong>: To change the price of a 
+subscription, you can publish a new subscription product ID at a new price, 
+then offer it in your app instead of the original product. Users who have 
+already purchased will continue to be charged at the 
+original price, but new users will be charged at the new price.</p>
+
+<h3 id="user-billing">User billing</h3>
+
+<p>In the Developer Console, you can configure subscription products with 
+automated recurring billing at either of two intervals:</p>
+
+<ul>
+  <li>Monthly &mdash; Google Play bills the customer’s Google Checkout account at
+  the time of purchase and monthly subsequent to the purchase date (exact billing
+  intervals can vary slightly over time)</li>
+  <li>Annually &mdash; Google Play bills the customer's Google Checkout account at
+  the time of purchase and again on the same date in subsequent years.</li>
+</ul>
+
+<p>Billing continues indefinitely at the interval and price specified for the
+subscription. At each subscription renewal, Google Play charges the user account
+automatically, then notifies the user of the charges afterward by email. Billing
+cycles will always match subscription cycles, based on the purchase date.</p>
+
+<p>Over the life of a subscription, the form of payment billed remains the same
+&mdash; Google Play always bills the same form of payment (such as credit card
+or by Direct Carrier Billing) that was originally used to purchase the
+subscription.</p>
+
+<p>When the subscription payment is approved by Google Checkout, Google Play
+provides a purchase token back to the purchasing app through the In-app Billing
+API. Your apps can store the token locally or pass it to your backend servers, 
+which can then use it to validate or cancel the subscription remotely using the <a
+href="#play-dev-api">Google Play Android Developer API</a>.</p>
+
+<p>If a recurring payment fails (for example, because the customer’s credit
+card has become invalid), the subscription does not renew. How your app is 
+notified depends on the In-app Billing API version that you are using:</p>
+<ul>
+<li>With In-app Billing Version 3, the failed or expired subscription is no longer 
+returned when you call {@code getPurchases}.</li>
+<li>With In-app Billing Version 2, Google Play notifies your app at the end of 
+the active cycle that the purchase state of the subscription is now "Expired". 
+</li>
+</ul>
+
+<p class="note"><strong>Recommendation</strong>: Include business logic in your 
+app to notify your backend servers of subscription purchases, tokens, and any 
+billing errors that may occur. Your backend servers can use the server-side API 
+to query and update your records and follow up with customers directly, if needed.</p>
+
+<h3 id="trials">Free trials</h3>
+
+<p>In the Developer Console, you can set up a free trial period that lets users
+try your subscription content before buying it. The trial period runs for the 
+period of time that you set and then automatically converts to a full 
+subscription managed according to the subscription's billing interval and 
+price.</p>
+
+<p>To take advantage of a free trial, a user must "purchase" the full
+subscription through the standard In-app Billing flow, providing a valid form of
+payment to use for billing and completing the normal purchase transaction.
+However, the user is not charged any money, since the initial period corresponds
+to the free trial. Instead, Google Play records a transaction of $0.00 and the
+subscription is marked as purchased for the duration of the trial period or
+until cancellation. When the transaction is complete, Google Play notifies users
+by email that they have purchased a subscription that includes a free trial
+period and that the initial charge was $0.00. </p>
+
+<p>When the trial period ends, Google Play automatically initiates billing
+against the credit card that the user provided during the initial purchase, at 
+the amount set
+for the full subscription, and continuing at the subscription interval. If
+necessary, the user can cancel the subscription at any time during the trial
+period. In this case, Google Play <em>marks the subscription as expired immediately</em>,
+rather than waiting until the end of the trial period. The user has not
+paid for the trial period and so is not entitled to continued access after
+cancellation.</p>
+
+<p>You can set up a trial period for a subscription in the Developer Console,
+without needing to modify or update your APK. Just locate and edit the
+subscription in your product list, set a valid number of days for the trial
+(must be 7 days or longer), and publish. You can change the period any time,
+although note that Google Play does not apply the change to users who have
+already "purchased" a trial period for the subscription. Only new subscription
+purchases will use the updated trial period. You can create one free trial
+period per subscription product.</p>
+
+<h3 id="publishing">Subscription publishing</h3>
+<p>When you have finished configuring your subscription product details in the
+Developer Console, you can publish the subscription in the app product list.</p>
+
+<p>In the product list, you can add subscriptions, in-app products, or both. You
+can add multiple subscriptions that give access to different content or
+services, or you can add multiple subscriptions that give access to the same
+content but for different intervals or different prices, such as for a
+promotion. For example, a news outlet might decide to offer both monthly and
+annual subscriptions to the same content, with annual having a discount. You can
+also offer in-app purchase equivalents for subscription products, to ensure that
+your content is available to users of older devices that do not support
+subscriptions.</p>
+
+<p>After you add a subscription or in-app product to the product list, you must
+publish the product before Google Play can make it available for purchase. Note
+that you must also publish the app itself before Google Play will make the
+products available for purchase inside the app. </p>
+
+<p class="caution"><strong>Important</strong>: You can remove the subscription 
+product from the product list offered in your app to prevent users from seeing 
+or purchasing it.</p>
+
+<h2 id="cancellation">Subscription Cancellation</h2>
+
+<p>Users can view the status of all of their subscriptions and cancel them if
+necessary from the <strong>My Apps</strong> screen in the Play Store app. 
+Currently, the In-app Billing API does not provide support for programatically 
+canceling subscriptions from inside the purchasing app.</p>
+
+<p>When the user cancels a subscription, Google Play does not offer a refund for
+the current billing cycle. Instead, it allows the user to have access to the
+cancelled subscription until the end of the current billing cycle, at which time
+it terminates the subscription. For example, if a user purchases a monthly
+subscription and cancels it on the 15th day of the cycle, Google Play will
+consider the subscription valid until the end of the 30th day (or other day,
+depending on the month).</p>
+
+<p>In some cases, the user may contact you directly to request cancellation of a
+subscription. In this and similar cases, you can use the server-side API to
+query and directly cancel the user’s subscription from your servers.
+
+<p class="caution"><strong>Important:</strong> In all cases, you must continue
+to offer the content that your subscribers have purchased through their
+subscriptions, for as long any users are able to access it. That is, you must
+not remove any subscriber’s content while any user still has an active
+subscription to it, even if that subscription will terminate at the end of the
+current billing cycle. Removing content that a subscriber is entitled to access
+will result in penalties. Please see the <a
+href="http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en&answer=140504">policies document</a> for more information. </p>
+
+<h3 id="uninstall">App uninstallation</h3>
+
+<p>When the user uninstalls an app that includes purchased subscriptions, the 
+Play Store app will notify the user that there are active subscriptions. If the 
+user chooses to continue with the uninstallation, the app is removed and the 
+subscriptions remain active and recurring billing continues. The user can return 
+to cancel the associated subscriptions at any time in the <strong>My Apps</strong> 
+screen of the Play Store app. If the user chooses to cancel the uninstallation, 
+the app and subscriptions remain as they were.</p>
+
+<h3 id="refunds">Refunds</h3>
+
+<p>With subscriptions, Google Play does not provide a refund window, so users 
+will need to contact you directly to request a refund.
+
+<p>If you receive requests for refunds, you can use the server-side API to
+cancel the subscription or verify that it is already cancelled. However, keep in
+mind that Google Play considers cancelled subscriptions valid until the end of
+their current billing cycles, so even if you grant a refund and cancel the
+subscription, the user will still have access to the content.
+
+<p class="caution"><strong>Important:</strong> Partial refunds for canceled
+subscriptions are not available at this time.</p>
+
+<h2 id="payment">Payment Processing and Policies</h2>
+
+<p>In general, the terms of Google Play allow you to sell in-app subscriptions
+only through the standard payment processor, Google Checkout. For purchases of 
+any subscription products, the transaction fee is the same as the transaction 
+fee for application purchases (30%).</p>
+
+<p>Apps published on Google Play that are selling subscriptions must use In-app
+Billing to handle the transaction and may not provide links to a purchase flow
+outside of the app and Google Play (such as to a web site).</p>
+
+<p>For complete details about terms and policies, see the <a
+href="http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en&answer=140504">policies
+document</a>.</p>
+
+<h3 id="orderId">Subscription order numbers</h3>
+
+<p>To help you track transactions relating to a given subscription, Google
+Checkout provides a base Merchant Order Number for all recurrences of the 
+subscription and denotes
+each recurring transaction by appending an integer as follows: </p>
+
+<p><span style="color:#777"><code style="color:#777">12999556515565155651.5565135565155651</code> (base order number)</span><br />
+<code>12999556515565155651.5565135565155651..0</code> (initial purchase orderID)<br />
+<code>12999556515565155651.5565135565155651..1</code> (first recurrence orderID)<br />
+<code>12999556515565155651.5565135565155651..2</code> (second recurrence orderID)<br />
+...<br /></p>
+
+<p>Google Play provides the order number as the value of the 
+{@code orderId} field of the {@code INAPP_PURCHASE_DATA} JSON field (in V3) 
+or the {@code PURCHASE_STATE_CHANGED} intent (in V2).</p>
+
+<h2 id="play-dev-api">Google Play Android Developer API</h2>
+
+<p>Google Play offers an HTTP-based API that you can use to remotely query the
+validity of a specific subscription at any time or cancel a subscription. The
+API is designed to be used from your backend servers as a way of securely
+managing subscriptions, as well as extending and integrating subscriptions with
+other services.</p>
+
+<h3 id="using">Using the API</h3>
+
+<p>To use the API, you must first register a project at the <a
+href="https://code.google.com/apis/console">Google APIs Console</a> and receive
+a Client ID and shared secret that  your app will present when calling the
+Google Play Android Developer API. All calls to the API are authenticated with
+OAuth 2.0.</p>
+
+<p>Once your app is registered, you can access the API directly, using standard
+HTTP methods to retrieve and manipulate resources, or you can use the Google
+APIs Client Libraries, which are extended to support the API.</p>
+
+<p>The Google Play Android Developer API is built on a RESTful design that uses
+HTTP and JSON, so any standard web stack can send requests and parse the
+responses. However, if you don’t want to send HTTP requests and parse responses
+manually, you can access the API using the client libraries, which provide
+better language integration, improved security, and support for making calls
+that require user authorization.</p>
+
+<p>For more information about the API and how to access it through the Google
+APIs Client Libraries, see the documentation at:</p> 
+
+<p style="margin-left:1.5em;"><a
+href="https://developers.google.com/android-publisher/v1/">https://developers.
+google.com/android-publisher/v1/</a></p>
+
+<h3 id="quota">Quota</h3>
+
+<p>Applications using the Google Play Android Developer API are limited to an
+initial courtesy usage quota of <strong>15000 requests per day</strong> (per
+application). This should provide enough access for normal
+subscription-validation needs, assuming that you follow the recommendation in
+this section.</p>
+
+<p>If you need to request a higher limit for your application, please use the
+“Request more” link in the <a
+href="https://code.google.com/apis/console/#:quotas">Google APIs Console</a>.
+Also, please read the section below on design best practices for minimizing your
+use of the API.</p>
+
+<h3 id="auth">Authorization</h3>
+
+<p>Calls to the Google Play Android Developer API require authorization. Google
+uses the OAuth 2.0 protocol to allow authorized applications to access user
+data. To learn more, see <a
+href="https://developers.google.com/android-publisher/authorization">Authorization</a>
+in the Google Play Android Developer API documentation.</p>
+
+<h3 id="practices">Using the API efficiently</h3>
+
+<p>Access to the Google Play Android Developer API is regulated to help ensure a
+high-performance environment for all applications that use it. While you can
+request a higher daily quota for your application, we highly recommend that you
+minimize your access using the technique(s) below. </p>
+
+<ul>
+  <li><em>Store subscription expiry on your servers</em> &mdash; your servers
+  should use the Google Play Android Developer API to query the expiration date
+  for new subscription tokens, then store the expiration date locally. This allows
+  you to check the status of subscriptions only at or after the expiration (see
+  below). </li>
+  <li><em>Cache expiration and purchaseState</em> &mdash; If your app contacts
+  your backend servers at runtime to verify subscription validity, your server
+  should cache the expiration and purchaseState to ensure the fastest possible
+  response (and best experience) for the user.</li>
+  <li><em>Query for subscription status only at expiration</em> &mdash; Once your
+  server has retrieved the expiration date of subscription tokens, it should not
+  query the Google Play servers for the subscription status again until the
+  subscription is reaching or has passed the expiration date. Typically, your
+  servers would run a batch query each day to check the status of
+  <em>expiring</em> subscriptions, then update the database. Note that: 
+  <ul>
+    <li>Your servers should not query all subscriptions every day</li>
+    <li>Your servers should never query subscription status dynamically, based on
+    individual requests from your Android application. </li>
+  </ul>
+  </li>
+</ul>
+
+<p>By following those general guidelines, your implementation will offer the
+best possible performance for users and minimize use of the Google Play Android
+Developer API.</p>
+
+
diff --git a/docs/html/google/play/billing/index.jd b/docs/html/google/play/billing/index.jd
index b0d1d13..44aa001 100644
--- a/docs/html/google/play/billing/index.jd
+++ b/docs/html/google/play/billing/index.jd
@@ -10,8 +10,8 @@
 <div class="sidebox">
   <h2><strong>New in In-App Billing</strong></h2>
   <ul>
-  <li><strong>In-app Billing Version 3</strong>&mdash;The <a href="{@docRoot}google/play/billing/api.html">latest version</a> of In-app Billing features a synchronous API that is easier to implement and lets you manage products and purchases more effectively.</li>
-  <li><strong>New order number format</strong>&mdash;Starting 5 December, orders are reported in Merchant Order Number format. See <a href="/google/play/billing/billing_admin.html#orderId">Working with Order Numbers</a> for an example.</li>
+  <li><strong>In-app Billing Version 3</strong>&mdash;The <a href="{@docRoot}google/play/billing/api.html">latest version</a> of In-app Billing features a synchronous API that is easier to implement and lets you manage in-app products and subscriptions more effectively.</li>
+  <li><strong>Subscriptions now supported in Version 3</strong>&mdash;You can query and launch purchase flows for subscription items using the V3 API.</li>
   <li><strong>Free trials</strong>&mdash;You can now offer users a configurable <a href="/google/play/billing/v2/billing_subscriptions.html#trials">free trial period</a> for your in-app subscriptions. You can set up trials with a simple change in the Developer Console&mdash;no change to your app code is needed.</li>
  </ul>
 </div>
@@ -30,7 +30,7 @@
 familiar purchase flow.</p>
 
 <p>Any application that you publish through Google Play can implement In-app Billing. No special
-account or registration is required other than an Android Market publisher account and a Google
+account or registration is required other than a Google Play Developer Console account and a Google
 Checkout merchant account.</p>
 
 <p>To help you integrate in-app billing into your application, the Android SDK
diff --git a/docs/html/google/play/billing/v2/api.jd b/docs/html/google/play/billing/v2/api.jd
index 6b3b758..9d3a045 100644
--- a/docs/html/google/play/billing/v2/api.jd
+++ b/docs/html/google/play/billing/v2/api.jd
@@ -39,15 +39,6 @@
 <p>If you do not need to sell subscriptions, you
 should implement In-app Billing Version 3 instead.</p>
 
-<div class="sidebox-wrapper">
-<div class="sidebox">
-  <h2>New in In-app Billing V2</h2>
-  <p><strong>Free trials</strong>—You can now offer users a configurable free trial period for
-  your in-app subscriptions. You can set up trials with a simple change in the Developer
-  Console—no change to your app code is needed.</p>
-</div>
-</div>
-
 <h2 id="billing-types">Product Types</h2>
 
 <p>In-app Billing Version supports three different product types
diff --git a/docs/html/google/play/billing/v2/billing_subscriptions.jd b/docs/html/google/play/billing/v2/billing_subscriptions.jd
index 82a662f..5e3bd28 100644
--- a/docs/html/google/play/billing/v2/billing_subscriptions.jd
+++ b/docs/html/google/play/billing/v2/billing_subscriptions.jd
@@ -1,4 +1,4 @@
-page.title=Subscriptions  <span style="font-size:16px;">(IAB Version 2)</span>
+page.title=Implementing Subscriptions  <span style="font-size:16px;">(IAB Version 2)</span>
 @jd:body
 
 <div style="background-color:#fffdeb;width:100%;margin-bottom:1em;padding:.5em;">In-app Billing Version 2 is superseded. Please <a href="{@docRoot}google/play/billing/billing_overview.html#migration">migrate to Version 3</a> at your earliest convenience.</div>
@@ -6,404 +6,26 @@
 <div id="qv">
   <h2>In this document</h2>
   <ol>
-    <li><a href="#overview">Overview of Subscriptions</a>
-    <!--<ol>
-        <li><a href="#publishing">Subscription publishing and unpublishing</a></li>
-        <li><a href="#pricing">Subscription pricing</a></li>
-        <li><a href="#user-billing">User billing</a></li>
-        <li><a href="#trials">Free trial period</a></li>
-        <li><a href="#cancellation">Subscription cancellation</a></li>
-        <li><a href="#uninstallation">App uninstallation</a></li>
-        <li><a href="#refunds">Refunds</a></li>
-        <li><a href="#payment">Payment processing and policies</a></li>
-        <li><a href="#requirements">System requirements for subscriptions</a></li>
-        <li><a href="#compatibility">Compatibility considerations</a></li>
-      </ol> -->
-    </li>
-    <li><a href="#implementing">Implementing Subscriptions</a>
-      <!-- <ol>
-        <li><a href="#sample">Sample application</a></li>
-        <li><a href="#model">Application model</a></li>
-        <li><a href="#token">Purchase token</a></li>
-        <li><a href="#version">Checking the In-app Billing API version</a></li>
-        <li><a href="purchase">Requesting purchase of a subscription</a></li>
-        <li><a href="#restore">Restoring transactions</a></li>
-        <li><a href="#validity">Checking subscription validity</a></li>
-        <li><a href="#viewstatus">Launching your product page to let the user cancel or view status</a></li>
-        <li><a href="#purchase-state-changes">Recurring billing and changes in purchase state</a></li>
-        <li><a href="modifying">Modifying your app for subscriptions</a></li>
-      </ol> -->
-    </li>
-    <li><a href="#administering">Administering Subscriptions</a></li>
-    
-    <li><a href="#play-dev-api">Google Play Android Developer API</a>
-      <!-- <ol>
-        <li><a href="#using">Using the API</a></li>
-        <li><a href="#quota">Quota</a></li>
-        <li><a href="#auth">Authorization</a></li>
-        <li><a href="#practices">Using the API efficiently</a></li>
-      </ol> -->
-    </li>
-</ol>
+        <li><a href="#sample">Sample Application</a></li>
+        <li><a href="#model">Application Model</a></li>
+        <li><a href="#token">Purchase Token</a></li>
+        <li><a href="#version">Checking the In-app Billing API Version</a></li>
+        <li><a href="purchase">Purchasing a Subscription</a></li>
+        <li><a href="#restore">Restoring Transactions</a></li>
+        <li><a href="#validity">Checking Subscription Validity</a></li>
+        <li><a href="#viewstatus">Letting Users Cancel or View Status</a></li>
+        <li><a href="#purchase-state-changes">Recurring Billing and Changes in Purchase State</a></li>
+        <li><a href="modifying">Modifying Your App for Subscriptions</a></li>
+   </ol>
 </div>
 </div>
 
-<p class="note"><strong>Important:</strong> This documentation describes how to implement subscriptions with the Version 2 API. Subscription support for the in-app billing <a href="{@docRoot}google/play/billing/api.html">Version 3 API</a> is coming soon.</p></li>
+<p>This document is focused on highlighting implementation details that are 
+specific to subscriptions with the Version 2 API. To understand how  
+subscriptions work, see <a href="{@docRoot}google/play/billing/billing_subscriptions.html">In-app Billing Subscriptions</a>.</p>
 
-<p>Subscriptions let you sell content, services, or features in your app with
-automated, recurring billing. Adding support for subscriptions is
-straightforward and you can easily adapt an existing In-app Billing
-implementation to sell subscriptions. </p>
 
-<p>If you have already implemented In-app Billing for one-time purchase
-products, you will find that you can add support for subscriptions with minimal
-impact on your code. If you are new to In-app Billing, you can implement
-subscriptions using the standard communication model, data structures, and user
-interactions as for other in-app products.subscriptions. Because the
-implementation of subscriptions follows the same path as for other in-app
-products, details are provided outside of this document, starting with the <a
-href="{@docRoot}google/play/billing/v2/api.html">In-app Billing
-Overview</a>. </p>
-
-<p>This document is focused on highlighting implementation details that are
-specific to subscriptions, along with some strategies for the associated billing
-and business models.</p>
-
-<p class="note"><strong>Note:</strong> Subscriptions are supported in In-app Billing Version 2 only. Support for subscriptions will be added to Version 3 in the weeks ahead.</p>
-
-<h2 id="overview">Overview of Subscriptions</h2>
-
-<p>A <em>subscription</em> is a new product type offered in In-app Billing that lets you
-sell content, services, or features to users from inside your app with recurring
-monthly or annual billing. You can sell subscriptions to almost any type of
-digital content, from any type of app or game.</p>
-
-<p>As with other in-app products, you configure and publish subscriptions using
-the Developer Console and then sell them from inside apps installed on an
-Android-powered devices. In the Developer console, you create subscription
-products and add them to a product list, then set a price and optional trial
-period for each, choose a billing interval (monthly or annual), and then publish.</p>
-
-<p>In your apps, it’s
-straightforward to add support for subscription purchases. The implementation
-extends the standard In-app Billing API to support a new product type but uses
-the same communication model, data structures, and user interactions as for
-other in-app products.</p>
-
-<p>When users purchase subscriptions in your apps, Google Play handles all
-checkout details so your apps never have to directly process any financial
-transactions. Google Play processes all payments for subscriptions through
-Google Checkout, just as it does for standard in-app products and app purchases.
-This ensures a consistent and familiar purchase flow for your users.</p>
-
-<img src="{@docRoot}images/billing_subscription_flow.png" style="border:4px solid ddd;">
-
-
-<p>After users have purchase subscriptions, they can view the subscriptions and
-cancel them, if necessary, from the My Apps screen in the Play Store app or
-from the app's product details page in the Play Store app.</p>
-
-<!--<img src="{@docRoot}images/billing_subscription_cancel.png" style="border:4px solid ddd;">-->
-
-<p>Once users have purchased a subscription through In-app Billing, you can
-easily give them extended access to additional content on your web site (or
-other service) through the use of a server-side API provided for In-app Billing.
-The server-side API lets you validate the status of a subscription when users
-sign into your other services. For more information about the API, see <a
-href="#play-dev-api">Google Play Android Developer API</a>, below. </p>
-
-<p>You can also build on your existing external subscriber base from inside your
-Android apps. If you sell subscriptions on a web site, for example, you can add
-your own business logic to your Android app to determine whether the user has
-already purchased a subscription elsewhere, then allow access to your content if
-so or offer a subscription purchase from Google Play if not.</p>
-
-<p>With the flexibility of In-app Billing, you can even implement your own
-solution for sharing subscriptions across as many different apps or products as
-you want. For example, you could sell a subscription that gives a subscriber
-access to an entire collection of apps, games, or other content for a monthly or
-annual fee. To implement this solution, you could add your own business logic to
-your app to determine whether the user has already purchased a given
-subscription and if so, allow access to your content. </p>
-
-<div class="sidebox-wrapper">
-<div class="sidebox">
-  <h2>Subscriptions at a glance</h2>
-  <ul>
-    <li>Subscriptions let you sell products with automated, recurring billing</li>
-    <li>You can set up subscriptions with either monthly or annual billing</li>
-    <li>You can sell multiple subscription items in an app with various billing
-    intervals or prices, such as for promotions</li>
-    <li>You can offer a configurable trial period for any subscription. <span class="new" style="font-size:.78em;">New!</span></li>
-    <li>Users purchase your subscriptions from inside your apps, rather than
-    directly from Google Play</li>
-    <li>Users manage their purchased subscriptions from the My Apps screen in
-    the Play Store app</li>
-    <li>Google Play uses the original form of payment for recurring billing</li>
-    <li>If a user cancels a subscription, Google Play considers the subscription valid
-    until the end of the current billing cycle. The user continues to enjoy the content
-    for the rest of the cycle and is not granted a refund.</li>
-  </ul>
-</div>
-</div>
-
-<p>In general the same basic policies and terms apply to subscriptions as to
-standard in-app products, however there are some differences. For complete
-information about the current policies and terms, please read the <a
-href="http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en
-&answer=140504">policies document</a>.</p>
-
-
-<h3 id="publishing">Subscription publishing and unpublishing</h3>
-
-<p>To sell a subscription in an app, you use the tools in the Developer Console
-to set up a product list for the app and then create and configure a new
-subscription. In the subscription, you set the price and billing interval and
-define a subscription ID, title, and description. When you are ready, you can
-then publish the subscription in the app product list.</p>
-
-<p>In the product list, you can add subscriptions, in-app products, or both. You
-can add multiple subscriptions that give access to different content or
-services, or you can add multiple subscriptions that give access to the same
-content but for different intervals or different prices, such as for a
-promotion. For example, a news outlet might decide to offer both monthly and
-annual subscriptions to the same content, with annual having a discount. You can
-also offer in-app purchase equivalents for subscription products, to ensure that
-your content is available to users of older devices that do not support
-subscriptions.</p>
-
-<p>After you add a subscription or in-app product to the product list, you must
-publish the product before Google Play can make it available for purchase. Note
-that you must also publish the app itself before Google Play will make the
-products available for purchase inside the app. </p>
-
-<p class="caution"><strong>Important:</strong> At this time, the capability to
-unpublish a subscription is not available. Support for unpublishing a
-subscription is coming to the Developer Console in the weeks ahead, so this is a
-temporary limitation. In the short term, instead of unpublishing,
-you can remove the subscription product from the product list offered in your
-app to prevent users from seeing or purchasing it.</p>
-
-<h3 id="pricing">Subscription pricing</h3>
-
-<p>When you create a subscription in the Developer Console, you can set a price
-for it in any available currencies. Each subscription must have a non-zero
-price. You can price multiple subscriptions for the same content differently
-&mdash; for example you could offer a discount on an annual subscription
-relative to the monthly equivalent. </p>
-
-<p class="caution"><strong>Important:</strong> At this time, once you publish a
-subscription product, you cannot change its price in any currency. Support for
-changing the price of published subscriptions is coming to the Developer Console
-in the weeks ahead. In the short term, you can work around this limitation by
-publishing a new subscription product ID at a new price, then offer it in your
-app instead of the original product. Users who have already purchased will
-continue to be charged at the original price, but new users will be charged at
-the new price.</p>
-
-<h3 id="user-billing">User billing</h3>
-
-<p>You can sell subscription products with automated recurring billing at
-either of two intervals:</p>
-
-<ul>
-  <li>Monthly &mdash; Google Play bills the customer’s Google Checkout account at
-  the time of purchase and monthly subsequent to the purchase date (exact billing
-  intervals can vary slightly over time)</li>
-  <li>Annually &mdash; Google Play bills the customer's Google Checkout account at
-  the time of purchase and again on the same date in subsequent years.</li>
-</ul>
-
-<p>Billing continues indefinitely at the interval and price specified for the
-subscription. At each subscription renewal, Google Play charges the user account
-automatically, then notifies the user of the charges afterward by email. Billing
-cycles will always match subscription cycles, based on the purchase date.</p>
-
-<p>Over the life of a subscription, the form of payment billed remains the same
-&mdash; Google Play always bills the same form of payment (such as credit card,
-Direct Carrier Billing) that was originally used to purchase the
-subscription.</p>
-
-<p>When the subscription payment is approved by Google Checkout, Google Play
-provides a purchase token back to the purchasing app through the In-app Billing
-API. For details, see <a href="#token">Purchase token</a>, below. Your apps can
-store the token locally or pass it to your backend servers, which can then use
-it to validate or cancel the subscription remotely using the <a
-href="#play-dev-api">Google Play Android Developer API</a>.</p>
-
-<p>If a recurring payment fails, such as could happen if the customer’s credit
-card has become invalid, the subscription does not renew. Google Play notifies your
-app at the end of the active cycle that the purchase state of the subscription is now "Expired".
-Your app does not need to grant the user further access to the subscription content.</p>
-
-<p>As a best practice, we recommend that your app includes business logic to
-notify your backend servers of subscription purchases, tokens, and any billing
-errors that may occur. Your backend servers can use the server-side API to query
-and update your records and follow up with customers directly, if needed.</p>
-
-<h3 id="trials">Free Trial Period</h3>
-
-<p>For any subscription, you can set up a free trial period that lets users
-try your subscription content before buying it. The trial period
-runs for the period of time that you set and then automatically converts to a full subscription
-managed according to the subscription's billing interval and price.</p>
-
-<p>To take advantage of a free trial, a user must "purchase" the full
-subscription through the standard In-app Billing flow, providing a valid form of
-payment to use for billing and completing the normal purchase transaction.
-However, the user is not charged any money, since the initial period corresponds
-to the free trial. Instead, Google Play records a transaction of $0.00 and the
-subscription is marked as purchased for the duration of the trial period or
-until cancellation. When the transaction is complete, Google Play notifies users
-by email that they have purchased a subscription that includes a free trial
-period and that the initial charge was $0.00. </p>
-
-<p>When the trial period ends, Google Play automatically initiates billing
-against the credit card that the user provided during the initial purchase, at the amount set
-for the full subscription, and continuing at the subscription interval. If
-necessary, the user can cancel the subscription at any time during the trial
-period. In this case, Google Play <em>marks the subscription as expired immediately</em>,
-rather than waiting until the end of the trial period. The user has not
-paid for the trial period and so is not entitled to continued access after
-cancellation.</p>
-
-<p>You can set up a trial period for a subscription in the Developer Console,
-without needing to modify or update your APK. Just locate and edit the
-subscription in your product list, set a valid number of days for the trial
-(must be 7 days or longer), and publish. You can change the period any time,
-although note that Google Play does not apply the change to users who have
-already "purchased" a trial period for the subscription. Only new subscription
-purchases will use the updated trial period. You can create one free trial
-period per subscription product.</p>
-
-<h3 id="cancellation">Subscription cancellation</h3>
-
-<p>Users can view the status of all of their subscriptions and cancel them if
-necessary from the My Apps screen in the Play Store app. Currently, the In-app
-Billing API does not provide support for canceling subscriptions direct from
-inside the purchasing app, although your app can broadcast an Intent to launch
-the Play Store app directly to the My Apps screen.</p>
-
-<p>When the user cancels a subscription, Google Play does not offer a refund for
-the current billing cycle. Instead, it allows the user to have access to the
-cancelled subscription until the end of the current billing cycle, at which time
-it terminates the subscription. For example, if a user purchases a monthly
-subscription and cancels it on the 15th day of the cycle, Google Play will
-consider the subscription valid until the end of the 30th day (or other day,
-depending on the month).</p>
-
-<p>In some cases, the user may contact you directly to request cancellation of a
-subscription. In this and similar cases, you can use the server-side API to
-query and directly cancel the user’s subscription from your servers.
-
-<p class="caution"><strong>Important:</strong> In all cases, you must continue
-to offer the content that your subscribers have purchased through their
-subscriptions, for as long any users are able to access it. That is, you must
-not remove any subscriber’s content while any user still has an active
-subscription to it, even if that subscription will terminate at the end of the
-current billing cycle. Removing content that a subscriber is entitled to access
-will result in penalties. Please see the <a
-href="http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en&answer=140504">policies document</a> for more information. </p>
-
-<h3 id="uninstall">App uninstallation</h3>
-
-<p>When the user uninstalls an app that includes purchased subscriptions, the Play Store app will notify the user that there are active subscriptions. If the user chooses to continue with the uninstalltion, the app is removed and the subscriptions remain active and recurring billing continues. The user can return to cancel the associated subscriptions at any time in the My Apps screen of the Play Store app. If the user chooses to cancel the uninstallation, the app and subscriptions remain as they were.</p>
-
-<h3 id="refunds">Refunds</h3>
-
-<p>As with other in-app products, Google Play does not provide a refund window
-for subscription purchases. For example, users who purchase an app can ask for a
-refund from Google Play within a 15-minute window. With subscriptions, Google
-Play does not provide a refund window, so users will need to contact you
-directly to request a refund.
-
-<p>If you receive requests for refunds, you can use the server-side API to
-cancel the subscription or verify that it is already cancelled. However, keep in
-mind that Google Play considers cancelled subscriptions valid until the end of
-their current billing cycles, so even if you grant a refund and cancel the
-subscription, the user will still have access to the content.
-
-<p class="note"><strong>Note:</strong> Partial refunds for canceled
-subscriptions are not available at this time.</p>
-
-<h3 id="payment">Payment processing and policies</h3>
-
-<p>In general, the terms of Google Play allow you to sell in-app subscriptions
-only through the standard payment processor, Google Checkout. For purchases of any
-subscription products, just as for other in-app products and apps, the
-transaction fee for subscriptions, just as for other in-app purchases, is the
-same as the transaction fee for application purchases (30%).</p>
-
-<p>Apps published on Google Play that are selling subscriptions must use In-app
-Billing to handle the transaction and may not provide links to a purchase flow
-outside of the app and Google Play (such as to a web site).</p>
-
-<p>For complete details about terms and policies, see the <a
-href="http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en&answer=140504">policies
-document</a>.</p>
-
-<h3 id="orderId">Subscription Order Numbers</h3>
-
-<p>To help you track transactions relating to a given subscription, Google
-Checkout provides a base Merchant Order Number for all recurrences of the subscription and denotes
-each recurring transaction by appending an integer as follows: </p>
-
-<p><span style="color:#777"><code style="color:#777">12999556515565155651.5565135565155651</code> (base order number)</span><br />
-<code>12999556515565155651.5565135565155651..0</code> (initial purchase orderID)<br />
-<code>12999556515565155651.5565135565155651..1</code> (first recurrence orderID)<br />
-<code>12999556515565155651.5565135565155651..2</code> (second recurrence orderID)<br />
-...<br /></p>
-
-<p>Google Play provides that order number to as the value of the
-<code>orderId</code> field of the <code>PURCHASE_STATE_CHANGED</code>
-intent.</p>
-
-<h3 id="requirements">System requirements for subscriptions</h3>
-
-<p>In-app purchases of subscriptions are supported only on devices that meet
-these minimum requirements:</p>
-
-<ul>
-  <li>Must run Android 2.2 or higher</li>
-  <li>Google Play Store app, Version 3.5 or higher, must be installed</li>
-</ul>
-
-<p>Google Play 3.5 and later versions include support for the In-app Billing
-v2 API or higher, which is needed to support handling of subscription
-products.</p>
-
-<h3 id="compatibility">Compatibility considerations</h3>
-
-<p>As noted in the previous section, support for subscriptions is available only
-on devices that meet the system requirements. Not all devices will receive or
-install Google Play 3.5, so not all users who install your apps will have access
-to the In-app Billing API and subscriptions.</p>
-
-<p>If you are targeting older devices that run Android 2.1 or earlier, we
-recommend that you offer those users an alternative way buy the content that is
-available through subscriptions. For example, you could create standard in-app
-products (one-time purchases) that give access to similar content as your
-subscriptions, possibly for a longer interval such as a year. </p>
-
-
-<h2 id="implementing">Implementing Subscriptions</h2>
-
-<p>Subscriptions are a standard In-app Billing product type. If you have already
-implemented In-app Billing for one-time purchase products, you will find that
-adding support for subscriptions is straightforward, with minimal impact on your
-code. If you are new to In-app Billing, you can implement subscriptions using
-the standard communication model, data structures, and user interactions as for
-other in-app products.subscriptions. </p>
-
-<p>The full implementation details for In-app Billing are provided outside of
-this document, starting with the <a
-href="{@docRoot}google/play/billing/v2/api.html">In-app Billing
-Overview</a>. This document is focused on highlighting implementation details
-that are specific to subscriptions, along with some strategies for the
-associated billing and business models.</p>
-
-
-<h3 id="sample">Sample application</h3>
+<h2 id="sample">Sample Application</h2>
 
 <p>To help you get started with your In-app Billing implementation and
 subscriptions, an updated Version of the In-app Billing sample app is available.
@@ -412,7 +34,7 @@
 href="{@docRoot}google/play/billing/v2/billing_integrate.html#billing-download">
 Downloading the Sample Application</a>.</p>
 
-<h3 id="model">Application model</h3>
+<h2 id="model">Application Model</h2>
 
 <p>With subscriptions, your app uses the standard In-app Billing application
 model, sending billing requests to the Play Store application over interprocess
@@ -436,7 +58,7 @@
 responses. Inside the requests and responses are two new fields described below.
 </p>
 
-<h3 id="token">Purchase token</h3>
+<h2 id="token">Purchase Token</h2>
 
 <p>Central to the end-to-end architecture for subscriptions is the purchase
 token, a string value that uniquely identifies (and associates) a user ID and a
@@ -476,7 +98,7 @@
 Design</a> document for best practices for maintaining the security of your
 data.</p>
 
-<h3 id="version">Checking the In-app Billing API version</h3>
+<h2 id="version">Checking the In-app Billing API Version</h2>
 
 <p>Subscriptions support is available only in versions of Google Play that
 support the In-app Billing v2 API (Google Play 3.5 and higher). For your app,
@@ -555,7 +177,7 @@
    }
 </pre>
 
-<h3 id="purchase">Requesting a subscription purchase</h3>
+<h2 id="purchase">Requesting a Subscription Purchase</h2>
 
 <p>Once you’ve checked the API Version as described above and determined that
 subscriptions are supported, you can present subscription products to the user
@@ -630,7 +252,7 @@
    }
 </pre>
 
-<h3 id="restoring">Restoring transactions</h3>
+<h2 id="restoring">Restoring Transactions</h2>
 
 <p>Subscriptions always use  the <em>managed by user account</em> purchase type,
 so that you can restore a record of subscription transactions on the device when
@@ -660,7 +282,7 @@
 Design</a> document for best practices for maintaining the security of your
 data.</p>
 
-<h3 id="validity">Checking subscription validity</h3>
+<h2 id="validity">Checking Subscription Validity</h2>
 
 <p>Subscriptions are time-bound purchases that require successful billing
 recurrences over time to remain valid. Your app should check the validity of
@@ -736,7 +358,7 @@
 </table>
 
 
-<h3 id="viewstatus">Launching your product page to let the user cancel or view subscriptions</h3>
+<h2 id="viewstatus">Letting the User Cancel or View Subscriptions</h2>
 
 <p>In-app Billing does not currently provide an API to let users directly view or cancel
 subscriptions from within the purchasing app. Instead, users can launch the Play
@@ -761,7 +383,7 @@
 <p>For more information, see 
   <a href="{@docRoot}distribute/googleplay/promote/linking.html">Linking to Your Products</a>.</p>
 
-<h3 id="purchase-state-changes">Recurring billing, cancellation, and changes in purchase state</h3>
+<h2 id="purchase-state-changes">Recurring Billing, Cancellation, and Changes In Purchase State</h2>
 
 <p>Google Play notifies your app when the user completes the purchase of a
 subscription, but the purchase state does not change over time, provided that
@@ -786,7 +408,7 @@
 a change to the same "Expired" purchase state. Once the purchase state has become "Expired",
 your app does not need to grant further access to the subscription content.</p>
 
-<h3 id="modifying">Modifying your app for subscriptions</h3>
+<h2 id="modifying">Modifying Your App for Subscriptions</h2>
 
 <p>For subscriptions, you make the same types of modifications to your app as
 are described in <a
@@ -798,118 +420,7 @@
 them. Your UI should not present subscriptions if the user has already purchased
 them.</p>
 
-<h2 id="administering">Administering Subscriptions</h2>
-
-<p>To create and manage subscriptions, you use the tools in the Developer
-Console, just as for other in-app products.</p>
-
-<p>At the Developer Console, you can configure these attributes for each
-subscription product:</p>
-
-<ul>
-<li>Purchase Type: always set to “subscription”</li>
-<li>Subscription ID:  An identifier for the subscription</li>
-<li>Publishing State: Unpublished/Published</li>
-<li>Language: The default language for displaying the subscription</li>
-<li>Title: The title of the subscription product</li>
-<li>Description: Details that tell the user about the subscription</li>
-<li>Price: USD price of subscription per recurrence</li>
-<li>Recurrence: monthly or yearly</li>
-<li>Additional currency pricing (can be auto-filled)</li>
-</ul>
-
-<p>For details, please see <a href="{@docRoot}google/play/billing/billing_admin.html">Administering
-In-app Billing</a>.</p>
 
 
-<h2 id="play-dev-api">Google Play Android Developer API</h2>
 
-<p>Google Play offers an HTTP-based API that you can use to remotely query the
-validity of a specific subscription at any time or cancel a subscription. The
-API is designed to be used from your backend servers as a way of securely
-managing subscriptions, as well as extending and integrating subscriptions with
-other services.</p>
-
-<h3 id="using">Using the API</h3>
-
-<p>To use the API, you must first register a project at the <a
-href="https://code.google.com/apis/console">Google APIs Console</a> and receive
-a Client ID and shared secret that  your app will present when calling the
-Google Play Android Developer API. All calls to the API are authenticated with
-OAuth 2.0.</p>
-
-<p>Once your app is registered, you can access the API directly, using standard
-HTTP methods to retrieve and manipulate resources, or you can use the Google
-APIs Client Libraries, which are extended to support the API.</p>
-
-<p>The Google Play Android Developer API is built on a RESTful design that uses
-HTTP and JSON, so any standard web stack can send requests and parse the
-responses. However, if you don’t want to send HTTP requests and parse responses
-manually, you can access the API using the client libraries, which provide
-better language integration, improved security, and support for making calls
-that require user authorization.</p>
-
-<p>For more information about the API and how to access it through the Google
-APIs Client Libraries, see the documentation at:</p> 
-
-<p style="margin-left:1.5em;"><a
-href="https://developers.google.com/android-publisher/v1/">https://developers.
-google.com/android-publisher/v1/</a></p>
-
-<h3 id="quota">Quota</h3>
-
-<p>Applications using the Google Play Android Developer API are limited to an
-initial courtesy usage quota of <strong>15000 requests per day</strong> (per
-application). This should provide enough access for normal
-subscription-validation needs, assuming that you follow the recommendation in
-this section.</p>
-
-<p>If you need to request a higher limit for your application, please use the
-“Request more” link in the <a
-href="https://code.google.com/apis/console/#:quotas">Google APIs Console</a>.
-Also, please read the section below on design best practices for minimizing your
-use of the API.</p>
-
-<h3 id="auth">Authorization</h3>
-
-<p>Calls to the Google Play Android Developer API require authorization. Google
-uses the OAuth 2.0 protocol to allow authorized applications to access user
-data. To learn more, see <a
-href="https://developers.google.com/android-publisher/authorization">Authorization</a>
-in the Google Play Android Developer API documentation.</p>
-
-<h3 id="practices">Using the API efficiently</h3>
-
-<p>Access to the Google Play Android Developer API is regulated to help ensure a
-high-performance environment for all applications that use it. While you can
-request a higher daily quota for your application, we highly recommend that you
-minimize your access using the technique(s) below. </p>
-
-<ul>
-  <li><em>Store subscription expiry on your servers</em> &mdash; your servers
-  should use the Google Play Android Developer API to query the expiration date
-  for new subscription tokens, then store the expiration date locally. This allows
-  you to check the status of subscriptions only at or after the expiration (see
-  below). </li>
-  <li><em>Cache expiration and purchaseState</em> &mdash; If your app contacts
-  your backend servers at runtime to verify subscription validity, your server
-  should cache the expiration and purchaseState to ensure the fastest possible
-  response (and best experience) for the user.</li>
-  <li><em>Query for subscription status only at expiration</em> &mdash; Once your
-  server has retrieved the expiration date of subscription tokens, it should not
-  query the Google Play servers for the subscription status again until the
-  subscription is reaching or has passed the expiration date. Typically, your
-  servers would run a batch query each day to check the status of
-  <em>expiring</em> subscriptions, then update the database. Note that: 
-  <ul>
-    <li>Your servers should not query all subscriptions every day</li>
-    <li>Your servers should never query subscription status dynamically, based on
-    individual requests from your Android application. </li>
-  </ul>
-  </li>
-</ul>
-
-<p>By following those general guidelines, your implementation will offer the
-best possible performance for users and minimize use of the Google Play Android
-Developer API.</p>
 
diff --git a/docs/html/google/play/billing/versions.jd b/docs/html/google/play/billing/versions.jd
index ac7761f..1271a15 100644
--- a/docs/html/google/play/billing/versions.jd
+++ b/docs/html/google/play/billing/versions.jd
@@ -15,9 +15,12 @@
 </ul>
 
 <h3 id="version_3">In-app Billing version 3</h3>
-<p><em>December 2012</em></p>
+<p><em>February 2013</em></p>
 <ul>
-<li>Requires Google Play client version 3.9.16 or higher.
+<li>Purchasing and querying managed in-app items requires Google Play client 
+version 3.9.16 or higher.</li>
+<li>Purchasing and querying subscription items requires Google Play client 
+version 3.10.10 or higher.</li>
 <li>Provides a new Android Interface Definition Language (AIDL) file named {@code IInAppBillingService.aidl}. The new interface offers these features:
 <ul>
 <li>Provides a new API to get details of in-app items published for the app including price, type, title and description.</li>
@@ -27,7 +30,6 @@
 <li>An API to get current purchases of the user immediately. This list will not contain any consumed purchases.</li>
 </ul>
 </li>
-<li>Subscriptions are not yet supported in this version of the API.</li>
 </ul>
 
 <h3 id="version_2">In-app Billing version 2</h3>
diff --git a/docs/html/images/in-app-billing/v3/billing_subscription_v3.png b/docs/html/images/in-app-billing/v3/billing_subscription_v3.png
new file mode 100644
index 0000000..0ba472e
--- /dev/null
+++ b/docs/html/images/in-app-billing/v3/billing_subscription_v3.png
Binary files differ
diff --git a/libs/hwui/Caches.cpp b/libs/hwui/Caches.cpp
index 74201d1..88f1d83 100644
--- a/libs/hwui/Caches.cpp
+++ b/libs/hwui/Caches.cpp
@@ -365,11 +365,12 @@
     }
 }
 
-void Caches::bindTexCoordsVertexPointer(bool force, GLvoid* vertices) {
-    if (force || vertices != mCurrentTexCoordsPointer) {
+void Caches::bindTexCoordsVertexPointer(bool force, GLvoid* vertices, GLsizei stride) {
+    if (force || vertices != mCurrentTexCoordsPointer || stride != mCurrentTexCoordsStride) {
         GLuint slot = currentProgram->texCoords;
-        glVertexAttribPointer(slot, 2, GL_FLOAT, GL_FALSE, gMeshStride, vertices);
+        glVertexAttribPointer(slot, 2, GL_FLOAT, GL_FALSE, stride, vertices);
         mCurrentTexCoordsPointer = vertices;
+        mCurrentTexCoordsStride = stride;
     }
 }
 
@@ -390,7 +391,7 @@
     }
 }
 
-void Caches::disbaleTexCoordsVertexArray() {
+void Caches::disableTexCoordsVertexArray() {
     if (mTexCoordsArrayEnabled) {
         glDisableVertexAttribArray(Program::kBindingTexCoords);
         mTexCoordsArrayEnabled = false;
diff --git a/libs/hwui/Caches.h b/libs/hwui/Caches.h
index d70c0e3..0ca2ffd 100644
--- a/libs/hwui/Caches.h
+++ b/libs/hwui/Caches.h
@@ -183,7 +183,7 @@
      * Binds an attrib to the specified float vertex pointer.
      * Assumes a stride of gMeshStride and a size of 2.
      */
-    void bindTexCoordsVertexPointer(bool force, GLvoid* vertices);
+    void bindTexCoordsVertexPointer(bool force, GLvoid* vertices, GLsizei stride = gMeshStride);
 
     /**
      * Resets the vertex pointers.
@@ -192,7 +192,7 @@
     void resetTexCoordsVertexPointer();
 
     void enableTexCoordsVertexArray();
-    void disbaleTexCoordsVertexArray();
+    void disableTexCoordsVertexArray();
 
     /**
      * Activate the specified texture unit. The texture unit must
@@ -299,6 +299,7 @@
     void* mCurrentPositionPointer;
     GLsizei mCurrentPositionStride;
     void* mCurrentTexCoordsPointer;
+    GLsizei mCurrentTexCoordsStride;
 
     bool mTexCoordsArrayEnabled;
 
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index be3cff1..57d16ae 100644
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -317,7 +317,7 @@
     mCaches.unbindMeshBuffer();
     mCaches.unbindIndicesBuffer();
     mCaches.resetVertexPointers();
-    mCaches.disbaleTexCoordsVertexArray();
+    mCaches.disableTexCoordsVertexArray();
     debugOverdraw(false, false);
 }
 
@@ -1469,12 +1469,18 @@
     mDescription.hasAlpha8Texture = isAlpha8;
 }
 
+void OpenGLRenderer::setupDrawWithTextureAndColor(bool isAlpha8) {
+    mDescription.hasTexture = true;
+    mDescription.hasColors = true;
+    mDescription.hasAlpha8Texture = isAlpha8;
+}
+
 void OpenGLRenderer::setupDrawWithExternalTexture() {
     mDescription.hasExternalTexture = true;
 }
 
 void OpenGLRenderer::setupDrawNoTexture() {
-    mCaches.disbaleTexCoordsVertexArray();
+    mCaches.disableTexCoordsVertexArray();
 }
 
 void OpenGLRenderer::setupDrawAA() {
@@ -1682,6 +1688,23 @@
     mCaches.unbindIndicesBuffer();
 }
 
+void OpenGLRenderer::setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLvoid* colors) {
+    bool force = mCaches.unbindMeshBuffer();
+    GLsizei stride = sizeof(ColorTextureVertex);
+
+    mCaches.bindPositionVertexPointer(force, vertices, stride);
+    if (mCaches.currentProgram->texCoords >= 0) {
+        mCaches.bindTexCoordsVertexPointer(force, texCoords, stride);
+    }
+    int slot = mCaches.currentProgram->getAttrib("colors");
+    if (slot >= 0) {
+        glEnableVertexAttribArray(slot);
+        glVertexAttribPointer(slot, 4, GL_FLOAT, GL_FALSE, stride, colors);
+    }
+
+    mCaches.unbindIndicesBuffer();
+}
+
 void OpenGLRenderer::setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords) {
     bool force = mCaches.unbindMeshBuffer();
     mCaches.bindPositionVertexPointer(force, vertices);
@@ -1833,9 +1856,16 @@
 
     const uint32_t count = meshWidth * meshHeight * 6;
 
-    // TODO: Support the colors array
-    TextureVertex mesh[count];
-    TextureVertex* vertex = mesh;
+    ColorTextureVertex mesh[count];
+    ColorTextureVertex* vertex = mesh;
+
+    bool cleanupColors = false;
+    if (!colors) {
+        uint32_t colorsCount = (meshWidth + 1) * (meshHeight + 1);
+        colors = new int[colorsCount];
+        memset(colors, 0xff, colorsCount * sizeof(int));
+        cleanupColors = true;
+    }
 
     for (int32_t y = 0; y < meshHeight; y++) {
         for (int32_t x = 0; x < meshWidth; x++) {
@@ -1855,13 +1885,13 @@
             int dx = i + (meshWidth + 1) * 2 + 2;
             int dy = dx + 1;
 
-            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
-            TextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1);
-            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
+            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
+            ColorTextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2, colors[ax / 2]);
+            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
 
-            TextureVertex::set(vertex++, vertices[ax], vertices[ay], u1, v2);
-            TextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1);
-            TextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2);
+            ColorTextureVertex::set(vertex++, vertices[dx], vertices[dy], u2, v2, colors[dx / 2]);
+            ColorTextureVertex::set(vertex++, vertices[bx], vertices[by], u1, v1, colors[bx / 2]);
+            ColorTextureVertex::set(vertex++, vertices[cx], vertices[cy], u2, v1, colors[cx / 2]);
 
             left = fminf(left, fminf(vertices[ax], fminf(vertices[bx], vertices[cx])));
             top = fminf(top, fminf(vertices[ay], fminf(vertices[by], vertices[cy])));
@@ -1871,12 +1901,16 @@
     }
 
     if (quickReject(left, top, right, bottom)) {
+        if (cleanupColors) delete[] colors;
         return DrawGlInfo::kStatusDone;
     }
 
     mCaches.activeTexture(0);
     Texture* texture = mCaches.textureCache.get(bitmap);
-    if (!texture) return DrawGlInfo::kStatusDone;
+    if (!texture) {
+        if (cleanupColors) delete[] colors;
+        return DrawGlInfo::kStatusDone;
+    }
     const AutoTexture autoCleanup(texture);
 
     texture->setWrap(GL_CLAMP_TO_EDGE, true);
@@ -1886,13 +1920,35 @@
     SkXfermode::Mode mode;
     getAlphaAndMode(paint, &alpha, &mode);
 
+    float a = alpha / 255.0f;
+
     if (hasLayer()) {
         dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
     }
 
-    drawTextureMesh(0.0f, 0.0f, 1.0f, 1.0f, texture->id, alpha / 255.0f,
-            mode, texture->blend, &mesh[0].position[0], &mesh[0].texture[0],
-            GL_TRIANGLES, count, false, false, 0, false, false);
+    setupDraw();
+    setupDrawWithTextureAndColor();
+    setupDrawColor(a, a, a, a);
+    setupDrawColorFilter();
+    setupDrawBlending(true, mode, false);
+    setupDrawProgram();
+    setupDrawDirtyRegionsDisabled();
+    setupDrawModelView(0.0f, 0.0f, 1.0f, 1.0f, false);
+    setupDrawTexture(texture->id);
+    setupDrawPureColorUniforms();
+    setupDrawColorFilterUniforms();
+    setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0], &mesh[0].color[0]);
+
+    glDrawArrays(GL_TRIANGLES, 0, count);
+
+    finishDrawTexture();
+
+    int slot = mCaches.currentProgram->getAttrib("colors");
+    if (slot >= 0) {
+        glDisableVertexAttribArray(slot);
+    }
+
+    if (cleanupColors) delete[] colors;
 
     return DrawGlInfo::kStatusDrew;
 }
diff --git a/libs/hwui/OpenGLRenderer.h b/libs/hwui/OpenGLRenderer.h
index 0ad81c1..ad80d36 100644
--- a/libs/hwui/OpenGLRenderer.h
+++ b/libs/hwui/OpenGLRenderer.h
@@ -777,6 +777,7 @@
      * Various methods to setup OpenGL rendering.
      */
     void setupDrawWithTexture(bool isAlpha8 = false);
+    void setupDrawWithTextureAndColor(bool isAlpha8 = false);
     void setupDrawWithExternalTexture();
     void setupDrawNoTexture();
     void setupDrawAA();
@@ -811,6 +812,7 @@
     void setupDrawTextureTransformUniforms(mat4& transform);
     void setupDrawTextGammaUniforms();
     void setupDrawMesh(GLvoid* vertices, GLvoid* texCoords = NULL, GLuint vbo = 0);
+    void setupDrawMesh(GLvoid* vertices, GLvoid* texCoords, GLvoid* colors);
     void setupDrawMeshIndices(GLvoid* vertices, GLvoid* texCoords);
     void setupDrawVertices(GLvoid* vertices);
     void finishDrawTexture();
diff --git a/libs/hwui/Program.h b/libs/hwui/Program.h
index b1df980..7b67b3c 100644
--- a/libs/hwui/Program.h
+++ b/libs/hwui/Program.h
@@ -81,6 +81,8 @@
 
 #define PROGRAM_IS_SIMPLE_GRADIENT 41
 
+#define PROGRAM_HAS_COLORS 42
+
 ///////////////////////////////////////////////////////////////////////////////
 // Types
 ///////////////////////////////////////////////////////////////////////////////
@@ -120,6 +122,9 @@
     bool hasExternalTexture;
     bool hasTextureTransform;
 
+    // Color attribute
+    bool hasColors;
+
     // Modulate, this should only be set when setColor() return true
     bool modulate;
 
@@ -164,6 +169,8 @@
         hasExternalTexture = false;
         hasTextureTransform = false;
 
+        hasColors = false;
+
         isAA = false;
 
         modulate = false;
@@ -259,6 +266,7 @@
         if (hasTextureTransform) key |= programid(0x1) << PROGRAM_HAS_TEXTURE_TRANSFORM_SHIFT;
         if (hasGammaCorrection) key |= programid(0x1) << PROGRAM_HAS_GAMMA_CORRECTION;
         if (isSimpleGradient) key |= programid(0x1) << PROGRAM_IS_SIMPLE_GRADIENT;
+        if (hasColors) key |= programid(0x1) << PROGRAM_HAS_COLORS;
         return key;
     }
 
diff --git a/libs/hwui/ProgramCache.cpp b/libs/hwui/ProgramCache.cpp
index fb00335..74d598d 100644
--- a/libs/hwui/ProgramCache.cpp
+++ b/libs/hwui/ProgramCache.cpp
@@ -40,6 +40,8 @@
         "attribute vec4 position;\n";
 const char* gVS_Header_Attributes_TexCoords =
         "attribute vec2 texCoords;\n";
+const char* gVS_Header_Attributes_Colors =
+        "attribute vec4 colors;\n";
 const char* gVS_Header_Attributes_AAVertexShapeParameters =
         "attribute float vtxAlpha;\n";
 const char* gVS_Header_Uniforms_TextureTransform =
@@ -65,6 +67,8 @@
         "uniform mediump vec2 textureDimension;\n";
 const char* gVS_Header_Varyings_HasTexture =
         "varying vec2 outTexCoords;\n";
+const char* gVS_Header_Varyings_HasColors =
+        "varying vec4 outColors;\n";
 const char* gVS_Header_Varyings_IsAAVertexShape =
         "varying float alpha;\n";
 const char* gVS_Header_Varyings_HasBitmap =
@@ -94,6 +98,8 @@
         "\nvoid main(void) {\n";
 const char* gVS_Main_OutTexCoords =
         "    outTexCoords = texCoords;\n";
+const char* gVS_Main_OutColors =
+        "    outColors = colors;\n";
 const char* gVS_Main_OutTransformedTexCoords =
         "    outTexCoords = (mainTextureTransform * vec4(texCoords, 0.0, 1.0)).xy;\n";
 const char* gVS_Main_OutGradient[6] = {
@@ -325,6 +331,8 @@
     };
 const char* gFS_Main_FragColor =
         "    gl_FragColor = fragColor;\n";
+const char* gFS_Main_FragColor_HasColors =
+        "    gl_FragColor *= outColors;\n";
 const char* gFS_Main_FragColor_Blend =
         "    gl_FragColor = blendFramebuffer(fragColor, gl_LastFragColor);\n";
 const char* gFS_Main_FragColor_Blend_Swap =
@@ -459,6 +467,9 @@
     if (description.isAA) {
         shader.append(gVS_Header_Attributes_AAVertexShapeParameters);
     }
+    if (description.hasColors) {
+        shader.append(gVS_Header_Attributes_Colors);
+    }
     // Uniforms
     shader.append(gVS_Header_Uniforms);
     if (description.hasTextureTransform) {
@@ -480,6 +491,9 @@
     if (description.isAA) {
         shader.append(gVS_Header_Varyings_IsAAVertexShape);
     }
+    if (description.hasColors) {
+        shader.append(gVS_Header_Varyings_HasColors);
+    }
     if (description.hasGradient) {
         shader.append(gVS_Header_Varyings_HasGradient[gradientIndex(description)]);
     }
@@ -499,6 +513,9 @@
         if (description.isAA) {
             shader.append(gVS_Main_AAVertexShape);
         }
+        if (description.hasColors) {
+            shader.append(gVS_Main_OutColors);
+        }
         if (description.hasBitmap) {
             shader.append(description.isPoint ?
                     gVS_Main_OutPointBitmapTexCoords :
@@ -549,6 +566,9 @@
     if (description.isAA) {
         shader.append(gVS_Header_Varyings_IsAAVertexShape);
     }
+    if (description.hasColors) {
+        shader.append(gVS_Header_Varyings_HasColors);
+    }
     if (description.hasGradient) {
         shader.append(gVS_Header_Varyings_HasGradient[gradientIndex(description)]);
     }
@@ -583,7 +603,7 @@
     }
 
     // Optimization for common cases
-    if (!description.isAA && !blendFramebuffer &&
+    if (!description.isAA && !blendFramebuffer && !description.hasColors &&
             description.colorOp == ProgramDescription::kColorNone && !description.isPoint) {
         bool fast = false;
 
@@ -729,6 +749,9 @@
             shader.append(!description.swapSrcDst ?
                     gFS_Main_FragColor_Blend : gFS_Main_FragColor_Blend_Swap);
         }
+        if (description.hasColors) {
+            shader.append(gFS_Main_FragColor_HasColors);
+        }
     }
     // End the shader
     shader.append(gFS_Footer);
diff --git a/libs/hwui/Vertex.h b/libs/hwui/Vertex.h
index c120428..523120e 100644
--- a/libs/hwui/Vertex.h
+++ b/libs/hwui/Vertex.h
@@ -33,7 +33,7 @@
 }; // struct Vertex
 
 /**
- * Simple structure to describe a vertex with a position and a texture.
+ * Simple structure to describe a vertex with a position and texture UV.
  */
 struct TextureVertex {
     float position[2];
@@ -53,6 +53,24 @@
 }; // struct TextureVertex
 
 /**
+ * Simple structure to describe a vertex with a position, texture UV and ARGB color.
+ */
+struct ColorTextureVertex : TextureVertex {
+    float color[4];
+
+    static inline void set(ColorTextureVertex* vertex, float x, float y,
+            float u, float v, int color) {
+        TextureVertex::set(vertex, x, y, u, v);
+
+        const float a = ((color >> 24) & 0xff) / 255.0f;
+        vertex[0].color[0] = a * ((color >> 16) & 0xff) / 255.0f;
+        vertex[0].color[1] = a * ((color >>  8) & 0xff) / 255.0f;
+        vertex[0].color[2] = a * ((color      ) & 0xff) / 255.0f;
+        vertex[0].color[3] = a;
+    }
+}; // struct ColorTextureVertex
+
+/**
  * Simple structure to describe a vertex with a position and an alpha value.
  */
 struct AlphaVertex : Vertex {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
index 5d9c7bc..7b80abc 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
@@ -16,6 +16,8 @@
 
 package com.android.systemui.statusbar.phone;
 
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
 import java.util.ArrayDeque;
 import java.util.ArrayList;
 import java.util.Iterator;
@@ -594,4 +596,20 @@
             if (DEBUG) LOG("skipping expansion: is expanded");
         }
     }
+
+    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+        pw.println(String.format("[PanelView(%s): expandedHeight=%f fullHeight=%f closing=%s"
+                + " tracking=%s rubberbanding=%s justPeeked=%s peekAnim=%s%s timeAnim=%s%s"
+                + "]",
+                this.getClass().getSimpleName(),
+                getExpandedHeight(),
+                getFullHeight(),
+                mClosing?"T":"f",
+                mTracking?"T":"f",
+                mRubberbanding?"T":"f",
+                mJustPeeked?"T":"f",
+                mPeekAnimator, ((mPeekAnimator!=null && mPeekAnimator.isStarted())?" (started)":""),
+                mTimeAnimator, ((mTimeAnimator!=null && mTimeAnimator.isStarted())?" (started)":"")
+        ));
+    }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
index 01596dc..9b1c1db 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -246,16 +246,6 @@
     private ViewGroup mCling;
     private boolean mSuppressStatusBarDrags; // while a cling is up, briefly deaden the bar to give things time to settle
 
-    boolean mAnimating;
-    boolean mClosing; // only valid when mAnimating; indicates the initial acceleration
-    float mAnimY;
-    float mAnimVel;
-    float mAnimAccel;
-    long mAnimLastTimeNanos;
-    boolean mAnimatingReveal = false;
-    int mViewDelta;
-    float mFlingVelocity;
-    int mFlingY;
     int[] mAbsPos = new int[2];
     Runnable mPostCollapseCleanup = null;
 
@@ -352,7 +342,7 @@
             @Override
             public boolean onTouch(View v, MotionEvent event) {
                 if (event.getAction() == MotionEvent.ACTION_DOWN) {
-                    if (mExpandedVisible && !mAnimating) {
+                    if (mExpandedVisible) {
                         animateCollapsePanels();
                     }
                 }
@@ -963,7 +953,7 @@
                 mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
             }
 
-            if (CLOSE_PANEL_WHEN_EMPTIED && mNotificationData.size() == 0 && !mAnimating) {
+            if (CLOSE_PANEL_WHEN_EMPTIED && mNotificationData.size() == 0) {
                 animateCollapsePanels();
             }
         }
@@ -1411,10 +1401,6 @@
         if (SPEW) {
             Slog.d(TAG, "animateCollapse():"
                     + " mExpandedVisible=" + mExpandedVisible
-                    + " mAnimating=" + mAnimating
-                    + " mAnimatingReveal=" + mAnimatingReveal
-                    + " mAnimY=" + mAnimY
-                    + " mAnimVel=" + mAnimVel
                     + " flags=" + flags);
         }
 
@@ -2051,16 +2037,6 @@
                     + ", mTrackingPosition=" + mTrackingPosition);
             pw.println("  mTicking=" + mTicking);
             pw.println("  mTracking=" + mTracking);
-            pw.println("  mNotificationPanel=" + 
-                    ((mNotificationPanel == null) 
-                            ? "null" 
-                            : (mNotificationPanel + " params=" + mNotificationPanel.getLayoutParams().debug(""))));
-            pw.println("  mAnimating=" + mAnimating
-                    + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
-                    + ", mAnimAccel=" + mAnimAccel);
-            pw.println("  mAnimLastTimeNanos=" + mAnimLastTimeNanos);
-            pw.println("  mAnimatingReveal=" + mAnimatingReveal
-                    + " mViewDelta=" + mViewDelta);
             pw.println("  mDisplayMetrics=" + mDisplayMetrics);
             pw.println("  mPile: " + viewInfo(mPile));
             pw.println("  mTickerView: " + viewInfo(mTickerView));
@@ -2075,6 +2051,20 @@
             mNavigationBarView.dump(fd, pw, args);
         }
 
+        pw.println("  Panels: ");
+        if (mNotificationPanel != null) {
+            pw.println("    mNotificationPanel=" +
+                mNotificationPanel + " params=" + mNotificationPanel.getLayoutParams().debug(""));
+            pw.print  ("      ");
+            mNotificationPanel.dump(fd, pw, args);
+        }
+        if (mSettingsPanel != null) {
+            pw.println("    mSettingsPanel=" +
+                mSettingsPanel + " params=" + mSettingsPanel.getLayoutParams().debug(""));
+            pw.print  ("      ");
+            mSettingsPanel.dump(fd, pw, args);
+        }
+
         if (DUMPTRUCK) {
             synchronized (mNotificationData) {
                 int N = mNotificationData.size();
diff --git a/packages/VpnDialogs/res/layout/confirm.xml b/packages/VpnDialogs/res/layout/confirm.xml
index fef00c2..ee7f4b8 100644
--- a/packages/VpnDialogs/res/layout/confirm.xml
+++ b/packages/VpnDialogs/res/layout/confirm.xml
@@ -52,6 +52,7 @@
                 android:layout_height="wrap_content"
                 android:text="@string/accept"
                 android:textSize="20sp"
+                android:filterTouchesWhenObscured="true"
                 android:checked="false"/>
     </LinearLayout>
 </ScrollView>
diff --git a/packages/VpnDialogs/src/com/android/vpndialogs/ConfirmDialog.java b/packages/VpnDialogs/src/com/android/vpndialogs/ConfirmDialog.java
index 7a1e66c..6faf4e0 100644
--- a/packages/VpnDialogs/src/com/android/vpndialogs/ConfirmDialog.java
+++ b/packages/VpnDialogs/src/com/android/vpndialogs/ConfirmDialog.java
@@ -78,6 +78,7 @@
             getWindow().setCloseOnTouchOutside(false);
             mButton = mAlert.getButton(DialogInterface.BUTTON_POSITIVE);
             mButton.setEnabled(false);
+            mButton.setFilterTouchesWhenObscured(true);
         } catch (Exception e) {
             Log.e(TAG, "onResume", e);
             finish();
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index 6efe4c5..e3a3ca2 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -1315,7 +1315,13 @@
             if (usedNetworkType != networkType) {
                 Integer currentPid = new Integer(pid);
                 mNetRequestersPids[usedNetworkType].remove(currentPid);
-                reassessPidDns(pid, true);
+
+                final long token = Binder.clearCallingIdentity();
+                try {
+                    reassessPidDns(pid, true);
+                } finally {
+                    Binder.restoreCallingIdentity(token);
+                }
                 flushVmDnsCache();
                 if (mNetRequestersPids[usedNetworkType].size() != 0) {
                     if (VDBG) {
diff --git a/services/java/com/android/server/NetworkManagementService.java b/services/java/com/android/server/NetworkManagementService.java
index 29e4c43..25ed27a 100644
--- a/services/java/com/android/server/NetworkManagementService.java
+++ b/services/java/com/android/server/NetworkManagementService.java
@@ -1120,19 +1120,31 @@
     @Override
     public NetworkStats getNetworkStatsSummaryDev() {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
-        return mStatsFactory.readNetworkStatsSummaryDev();
+        try {
+            return mStatsFactory.readNetworkStatsSummaryDev();
+        } catch (IOException e) {
+            throw new IllegalStateException(e);
+        }
     }
 
     @Override
     public NetworkStats getNetworkStatsSummaryXt() {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
-        return mStatsFactory.readNetworkStatsSummaryXt();
+        try {
+            return mStatsFactory.readNetworkStatsSummaryXt();
+        } catch (IOException e) {
+            throw new IllegalStateException(e);
+        }
     }
 
     @Override
     public NetworkStats getNetworkStatsDetail() {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
-        return mStatsFactory.readNetworkStatsDetail(UID_ALL);
+        try {
+            return mStatsFactory.readNetworkStatsDetail(UID_ALL);
+        } catch (IOException e) {
+            throw new IllegalStateException(e);
+        }
     }
 
     @Override
@@ -1289,7 +1301,11 @@
     @Override
     public NetworkStats getNetworkStatsUidDetail(int uid) {
         mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
-        return mStatsFactory.readNetworkStatsDetail(uid);
+        try {
+            return mStatsFactory.readNetworkStatsDetail(uid);
+        } catch (IOException e) {
+            throw new IllegalStateException(e);
+        }
     }
 
     @Override
diff --git a/services/java/com/android/server/am/ActivityStack.java b/services/java/com/android/server/am/ActivityStack.java
index 84d5a72..c54cdaa 100644
--- a/services/java/com/android/server/am/ActivityStack.java
+++ b/services/java/com/android/server/am/ActivityStack.java
@@ -2145,7 +2145,6 @@
                             }
                             mHistory.remove(srcPos);
                             mHistory.add(dstPos, p);
-//                            mService.mWindowManager.moveAppToken(dstPos, p.appToken);
                             mService.mWindowManager.setAppGroupId(p.appToken, taskId);
                             dstPos++;
                             i++;
@@ -2297,7 +2296,6 @@
                         if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
                                 + " from " + srcPos + " to " + lastReparentPos
                                 + " in to resetting task " + task);
-//                        mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
                         mService.mWindowManager.setAppGroupId(p.appToken, taskId);
                     }
                     // TODO: This is wrong because it doesn't take lastReparentPos into account.
@@ -4566,7 +4564,6 @@
             updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
         }
 
-//        mService.mWindowManager.moveAppTokensToTop(moved);
         mService.mWindowManager.moveTaskToTop(task);
         if (VALIDATE_TOKENS) {
             validateAppTokensLocked();
@@ -4659,7 +4656,6 @@
             mService.mWindowManager.prepareAppTransition(
                     AppTransition.TRANSIT_TASK_TO_BACK, false);
         }
-//        mService.mWindowManager.moveAppTokensToBottom(moved);
         mService.mWindowManager.moveTaskToBottom(task);
         if (VALIDATE_TOKENS) {
             validateAppTokensLocked();
diff --git a/services/java/com/android/server/wm/DisplayContent.java b/services/java/com/android/server/wm/DisplayContent.java
index f8e779d..b48a004 100644
--- a/services/java/com/android/server/wm/DisplayContent.java
+++ b/services/java/com/android/server/wm/DisplayContent.java
@@ -16,8 +16,6 @@
 
 package com.android.server.wm;
 
-import android.os.Debug;
-import android.util.Slog;
 import android.util.SparseArray;
 import android.view.Display;
 import android.view.DisplayInfo;
@@ -38,7 +36,7 @@
  * WindowManagerService.mWindowMap.
  */
 class DisplayContent {
-    private final static String TAG = "DisplayContent";
+//    private final static String TAG = "DisplayContent";
 
     /** Unique identifier of this stack. */
     private final int mDisplayId;
@@ -73,20 +71,6 @@
     final boolean isDefaultDisplay;
 
     /**
-     * List controlling the ordering of windows in different applications which must
-     * be kept in sync with ActivityManager.
-     */
-    final AppTokenList mAppTokens = new AppTokenList();
-
-    /**
-     * AppWindowTokens in the Z order they were in at the start of an animation. Between
-     * animations this list is maintained in the exact order of mAppTokens. If tokens
-     * are added to mAppTokens during an animation an attempt is made to insert them at the same
-     * logical location in this list. Note that this list is always in sync with mWindows.
-     */
-    AppTokenList mAnimatingAppTokens = new AppTokenList();
-
-    /**
      * Window tokens that are in the process of exiting, but still
      * on screen for animations.
      */
@@ -140,18 +124,6 @@
      * @param wtoken The token to insert.
      */
     void addAppToken(final int addPos, final AppWindowToken wtoken) {
-        mAppTokens.add(addPos, wtoken);
-
-        if (addPos == 0 || addPos == mAnimatingAppTokens.size()) {
-            // It was inserted into the beginning or end of mAppTokens. Honor that.
-            mAnimatingAppTokens.add(addPos, wtoken);
-        } else {
-            // Find the item immediately above the mAppTokens insertion point and put the token
-            // immediately below that one in mAnimatingAppTokens.
-            final AppWindowToken aboveAnchor = mAppTokens.get(addPos + 1);
-            mAnimatingAppTokens.add(mAnimatingAppTokens.indexOf(aboveAnchor), wtoken);
-        }
-
         TaskList task = mTaskIdToTaskList.get(wtoken.groupId);
         if (task == null) {
             task = new TaskList(wtoken, this);
@@ -163,8 +135,6 @@
     }
 
     void removeAppToken(final AppWindowToken wtoken) {
-        mAppTokens.remove(wtoken);
-        mAnimatingAppTokens.remove(wtoken);
         final int taskId = wtoken.groupId;
         final TaskList task = mTaskIdToTaskList.get(taskId);
         if (task != null) {
@@ -177,14 +147,6 @@
         }
     }
 
-    void refillAnimatingAppTokens() {
-        mAnimatingAppTokens.clear();
-        AppTokenIterator iterator = new AppTokenIterator();
-        while (iterator.hasNext()) {
-            mAnimatingAppTokens.add(iterator.next());
-        }
-    }
-
     void setAppTaskId(AppWindowToken wtoken, int newTaskId) {
         final int taskId = wtoken.groupId;
         TaskList task = mTaskIdToTaskList.get(taskId);
@@ -307,31 +269,6 @@
         }
     }
 
-    void verifyAppTokens() {
-        AppTokenIterator iterator = new AppTokenIterator();
-        for (int i = 0; i < mAppTokens.size(); ++i) {
-            if (!iterator.hasNext()) {
-                Slog.e(TAG, "compareAppTokens: More mAppTokens than TaskList tokens. Callers="
-                        + Debug.getCallers(4));
-                while (i < mAppTokens.size()) {
-                    Slog.e(TAG, "compareAppTokens: mAppTokens[" + i + "]=" + mAppTokens.get(i));
-                    i++;
-                }
-                return;
-            }
-            AppWindowToken appToken = mAppTokens.get(i);
-            AppWindowToken taskListToken = iterator.next();
-            if (appToken != taskListToken) {
-                Slog.e(TAG, "compareAppTokens: Mismatch at " + i + " appToken=" + appToken
-                        + " taskListToken=" + taskListToken + ". Callers=" + Debug.getCallers(4));
-            }
-        }
-        if (iterator.hasNext()) {
-            Slog.e(TAG, "compareAppTokens: More TaskList tokens than mAppTokens Callers="
-                    + Debug.getCallers(4));
-        }
-    }
-
     public void dump(String prefix, PrintWriter pw) {
         pw.print(prefix); pw.print("Display: mDisplayId="); pw.println(mDisplayId);
         final String subPrefix = "  " + prefix;
diff --git a/services/java/com/android/server/wm/WindowAnimator.java b/services/java/com/android/server/wm/WindowAnimator.java
index 1821b6b..2381cde 100644
--- a/services/java/com/android/server/wm/WindowAnimator.java
+++ b/services/java/com/android/server/wm/WindowAnimator.java
@@ -26,6 +26,7 @@
 import android.view.WindowManagerPolicy;
 import android.view.animation.Animation;
 
+import com.android.server.wm.DisplayContent.AppTokenIterator;
 import com.android.server.wm.WindowManagerService.DisplayContentsIterator;
 import com.android.server.wm.WindowManagerService.LayoutFields;
 
@@ -175,10 +176,9 @@
     private void updateAppWindowsLocked(int displayId) {
         int i;
         final DisplayContent displayContent = mService.getDisplayContentLocked(displayId);
-        final AppTokenList appTokens = displayContent.mAnimatingAppTokens;
-        final int NAT = appTokens.size();
-        for (i=0; i<NAT; i++) {
-            final AppWindowAnimator appAnimator = appTokens.get(i).mAppAnimator;
+        AppTokenIterator iterator = displayContent.new AppTokenIterator();
+        while (iterator.hasNext()) {
+            final AppWindowAnimator appAnimator = iterator.next().mAppAnimator;
             final boolean wasAnimating = appAnimator.animation != null
                     && appAnimator.animation != AppWindowAnimator.sDummyAnimation;
             if (appAnimator.stepAnimationLocked(mCurrentTime)) {
@@ -459,11 +459,10 @@
     private void testTokenMayBeDrawnLocked(int displayId) {
         // See if any windows have been drawn, so they (and others
         // associated with them) can now be shown.
-        final AppTokenList appTokens =
-                mService.getDisplayContentLocked(displayId).mAnimatingAppTokens;
-        final int NT = appTokens.size();
-        for (int i=0; i<NT; i++) {
-            AppWindowToken wtoken = appTokens.get(i);
+        AppTokenIterator iterator = mService.getDisplayContentLocked(displayId).new
+                AppTokenIterator();
+        while (iterator.hasNext()) {
+            AppWindowToken wtoken = iterator.next();
             AppWindowAnimator appAnimator = wtoken.mAppAnimator;
             final boolean allDrawn = wtoken.allDrawn;
             if (allDrawn != appAnimator.allDrawn) {
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index a923604..fbfa6a1 100644
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -889,7 +889,6 @@
         final WindowList windows = win.getWindowList();
         final int N = windows.size();
         final WindowState attached = win.mAttachedWindow;
-        int i;
         WindowList tokenWindowList = getTokenWindowsOnDisplay(token, displayContent);
         if (attached == null) {
             int tokenWindowsPos = 0;
@@ -939,13 +938,12 @@
                         + client.asBinder() + " (token=" + token + ")");
                     // Figure out where the window should go, based on the
                     // order of applications.
-                    AppTokenList animatingAppTokens = displayContent.mAnimatingAppTokens;
-                    final int NA = animatingAppTokens.size();
                     WindowState pos = null;
-                    for (i=NA-1; i>=0; i--) {
-                        AppWindowToken t = animatingAppTokens.get(i);
+                    AppTokenIterator iterator =
+                            displayContent.new AppTokenIterator(true /*reverse*/);
+                    while (iterator.hasNext()) {
+                        AppWindowToken t = iterator.next();
                         if (t == token) {
-                            i--;
                             break;
                         }
 
@@ -978,15 +976,14 @@
                     } else {
                         // Continue looking down until we find the first
                         // token that has windows on this display.
-                        while (i >= 0) {
-                            AppWindowToken t = animatingAppTokens.get(i);
+                        while (iterator.hasNext()) {
+                            AppWindowToken t = iterator.next();
                             tokenWindowList = getTokenWindowsOnDisplay(t, displayContent);
                             final int NW = tokenWindowList.size();
                             if (NW > 0) {
                                 pos = tokenWindowList.get(NW-1);
                                 break;
                             }
-                            i--;
                         }
                         if (pos != null) {
                             // Move in front of any windows attached to this
@@ -1005,7 +1002,8 @@
                         } else {
                             // Just search for the start of this layer.
                             final int myLayer = win.mBaseLayer;
-                            for (i=0; i<N; i++) {
+                            int i;
+                            for (i = 0; i < N; i++) {
                                 WindowState w = windows.get(i);
                                 if (w.mBaseLayer > myLayer) {
                                     break;
@@ -1023,7 +1021,8 @@
             } else {
                 // Figure out where window should go, based on layer.
                 final int myLayer = win.mBaseLayer;
-                for (i=N-1; i>=0; i--) {
+                int i;
+                for (i = N - 1; i >= 0; i--) {
                     if (windows.get(i).mBaseLayer <= myLayer) {
                         break;
                     }
@@ -1048,7 +1047,8 @@
             final int sublayer = win.mSubLayer;
             int largestSublayer = Integer.MIN_VALUE;
             WindowState windowWithLargestSublayer = null;
-            for (i=0; i<NA; i++) {
+            int i;
+            for (i = 0; i < NA; i++) {
                 WindowState w = tokenWindowList.get(i);
                 final int wSublayer = w.mSubLayer;
                 if (wSublayer >= largestSublayer) {
@@ -2453,22 +2453,15 @@
 
     public void updateAppOpsState() {
         synchronized(mWindowMap) {
-            boolean changed = false;
-            for (int i=0; i<mDisplayContents.size(); i++) {
-                DisplayContent display = mDisplayContents.valueAt(i);
-                WindowList windows = display.getWindowList();
-                for (int j=0; j<windows.size(); j++) {
-                    final WindowState win = windows.get(j);
-                    if (win.mAppOp != AppOpsManager.OP_NONE) {
-                        changed |= win.setAppOpVisibilityLw(mAppOps.checkOpNoThrow(win.mAppOp,
-                                win.getOwningUid(),
-                                win.getOwningPackage()) == AppOpsManager.MODE_ALLOWED);
-                    }
+            AllWindowsIterator iterator = new AllWindowsIterator();
+            while (iterator.hasNext()) {
+                final WindowState win = iterator.next();
+                if (win.mAppOp != AppOpsManager.OP_NONE) {
+                    final int mode = mAppOps.checkOpNoThrow(win.mAppOp, win.getOwningUid(),
+                            win.getOwningPackage());
+                    win.setAppOpVisibilityLw(mode == AppOpsManager.MODE_ALLOWED);
                 }
             }
-            if (changed) {
-                scheduleAnimationLocked();
-            }
         }
     }
 
@@ -4377,18 +4370,6 @@
         }
     }
 
-    void dumpAnimatingAppTokensLocked() {
-        DisplayContentsIterator iterator = new DisplayContentsIterator();
-        while (iterator.hasNext()) {
-            DisplayContent displayContent = iterator.next();
-            Slog.v(TAG, "  Display " + displayContent.getDisplayId());
-            AppTokenList appTokens = displayContent.mAnimatingAppTokens;
-            for (int i=appTokens.size()-1; i>=0; i--) {
-                Slog.v(TAG, "  #" + i + ": " + appTokens.get(i).token);
-            }
-        }
-    }
-
     void dumpWindowsLocked() {
         int i = 0;
         final AllWindowsIterator iterator = new AllWindowsIterator(REVERSE_ITERATOR);
@@ -4398,61 +4379,6 @@
         }
     }
 
-    private int findWindowOffsetLocked(DisplayContent displayContent, int tokenPos) {
-        final WindowList windows = displayContent.getWindowList();
-        final int NW = windows.size();
-
-        if (tokenPos >= displayContent.mAnimatingAppTokens.size()) {
-            int i = NW;
-            while (i > 0) {
-                i--;
-                WindowState win = windows.get(i);
-                if (win.getAppToken() != null) {
-                    return i+1;
-                }
-            }
-        }
-
-        final AppTokenList appTokens = displayContent.mAppTokens;
-        while (tokenPos > 0) {
-            // Find the first app token below the new position that has
-            // a window displayed.
-            final AppWindowToken wtoken = appTokens.get(tokenPos-1);
-            if (DEBUG_REORDER) Slog.v(TAG, "Looking for lower windows @ "
-                    + tokenPos + " -- " + wtoken.token);
-            if (wtoken.sendingToBottom) {
-                if (DEBUG_REORDER) Slog.v(TAG,
-                        "Skipping token -- currently sending to bottom");
-                tokenPos--;
-                continue;
-            }
-            for (int i = wtoken.windows.size() - 1; i >= 0; --i) {
-                WindowState win = wtoken.windows.get(i);
-                for (int j = win.mChildWindows.size() - 1; j >= 0; --j) {
-                    WindowState cwin = win.mChildWindows.get(j);
-                    if (cwin.mSubLayer >= 0) {
-                        for (int pos = NW - 1; pos >= 0; pos--) {
-                            if (windows.get(pos) == cwin) {
-                                if (DEBUG_REORDER) Slog.v(TAG,
-                                        "Found child win @" + (pos + 1));
-                                return pos + 1;
-                            }
-                        }
-                    }
-                }
-                for (int pos = NW - 1; pos >= 0; pos--) {
-                    if (windows.get(pos) == win) {
-                        if (DEBUG_REORDER) Slog.v(TAG, "Found win @" + (pos + 1));
-                        return pos + 1;
-                    }
-                }
-            }
-            tokenPos--;
-        }
-
-        return 0;
-    }
-
     private int findAppWindowInsertionPointLocked(AppWindowToken target) {
         final int taskId = target.groupId;
         DisplayContent displayContent = mTaskIdToDisplayContents.get(taskId);
@@ -4548,215 +4474,6 @@
         return index;
     }
 
-    @Override
-    public void moveAppToken(int index, IBinder token) {
-        if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
-                "moveAppToken()")) {
-            throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
-        }
-
-        synchronized(mWindowMap) {
-            if (DEBUG_REORDER) Slog.v(TAG, "Initial app tokens:");
-            if (DEBUG_REORDER) dumpAppTokensLocked();
-            final AppWindowToken wtoken = findAppWindowToken(token);
-            DisplayContent displayContent = mTaskIdToDisplayContents.get(wtoken.groupId);
-            final AppTokenList appTokens = displayContent.mAppTokens;
-            final int oldIndex = appTokens.indexOf(wtoken);
-            if (DEBUG_TOKEN_MOVEMENT || DEBUG_REORDER) Slog.v(TAG,
-                    "Start moving token " + wtoken + " initially at "
-                    + oldIndex);
-            if (oldIndex > index && mAppTransition.isTransitionSet()) {
-                // animation towards back has not started, copy old list for duration of animation.
-                displayContent.refillAnimatingAppTokens();
-            }
-            if (wtoken == null || !appTokens.remove(wtoken)) {
-                Slog.w(TAG, "Attempting to reorder token that doesn't exist: "
-                      + token + " (" + wtoken + ")");
-                return;
-            }
-            appTokens.add(index, wtoken);
-            if (DEBUG_REORDER) Slog.v(TAG, "Moved " + token + " to " + index + ":");
-            else if (DEBUG_TOKEN_MOVEMENT) Slog.v(TAG, "Moved " + token + " to " + index);
-            if (DEBUG_REORDER) dumpAppTokensLocked();
-            if (!mAppTransition.isTransitionSet()) {
-                // Not animating, bring animating app list in line with mAppTokens.
-                displayContent.refillAnimatingAppTokens();
-
-                // Bring window ordering, window focus and input window in line with new app token
-                final long origId = Binder.clearCallingIdentity();
-                if (DEBUG_REORDER) Slog.v(TAG, "Removing windows in " + token + ":");
-                if (DEBUG_REORDER) dumpWindowsLocked();
-                if (tmpRemoveAppWindowsLocked(wtoken)) {
-                    if (DEBUG_REORDER) Slog.v(TAG, "Adding windows back in:");
-                    if (DEBUG_REORDER) dumpWindowsLocked();
-                    DisplayContentsIterator iterator = new DisplayContentsIterator();
-                    while(iterator.hasNext()) {
-                        displayContent = iterator.next();
-                        final int pos = findWindowOffsetLocked(displayContent, index);
-                        final int newPos = reAddAppWindowsLocked(displayContent, pos, wtoken);
-                        if (pos != newPos) {
-                            displayContent.layoutNeeded = true;
-                        }
-                    }
-                    if (DEBUG_REORDER) Slog.v(TAG, "Final window list:");
-                    if (DEBUG_REORDER) dumpWindowsLocked();
-                    updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES,
-                            false /*updateInputWindows*/);
-                    mInputMonitor.setUpdateInputWindowsNeededLw();
-                    performLayoutAndPlaceSurfacesLocked();
-                    mInputMonitor.updateInputWindowsLw(false /*force*/);
-                }
-                Binder.restoreCallingIdentity(origId);
-            }
-        }
-    }
-
-    private void removeAppTokensLocked(List<IBinder> tokens) {
-        // XXX This should be done more efficiently!
-        // (take advantage of the fact that both lists should be
-        // ordered in the same way.)
-        int N = tokens.size();
-        for (int i=0; i<N; i++) {
-            IBinder token = tokens.get(i);
-            final AppWindowToken wtoken = findAppWindowToken(token);
-            if (wtoken != null) {
-                final DisplayContent displayContent = mTaskIdToDisplayContents.get(wtoken.groupId);
-                if (DEBUG_REORDER || DEBUG_TOKEN_MOVEMENT) Slog.v(TAG, "Temporarily removing "
-                        + wtoken);
-                if (!displayContent.mAppTokens.remove(wtoken)) {
-                    Slog.w(TAG, "Attempting to reorder token that doesn't exist: "
-                            + token + " (" + wtoken + ")");
-                    i--;
-                    N--;
-                }
-            }
-        }
-    }
-
-    WindowList mSavedWindows;
-    private void moveAppWindowsLocked(List<IBinder> tokens, DisplayContent displayContent,
-            int tokenPos) {
-        if (DEBUG_TASK_MOVEMENT) {
-            mSavedWindows = new WindowList(displayContent.getWindowList());
-        }
-        // First remove all of the windows from the list.
-        final int N = tokens.size();
-        int i;
-        for (i=0; i<N; i++) {
-            WindowToken token = mTokenMap.get(tokens.get(i));
-            if (token != null) {
-                tmpRemoveAppWindowsLocked(token);
-            }
-        }
-
-        // And now add them back at the correct place.
-        // Where to start adding?
-        int pos = findWindowOffsetLocked(displayContent, tokenPos);
-        for (i=0; i<N; i++) {
-            WindowToken token = mTokenMap.get(tokens.get(i));
-            if (token != null) {
-                final int newPos = reAddAppWindowsLocked(displayContent, pos, token);
-                if (newPos != pos) {
-                    displayContent.layoutNeeded = true;
-                }
-                pos = newPos;
-            }
-        }
-        if (!updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES,
-            false /*updateInputWindows*/)) {
-            assignLayersLocked(displayContent.getWindowList());
-        }
-
-        mInputMonitor.setUpdateInputWindowsNeededLw();
-
-        // Note that the above updateFocusedWindowLocked used to sit here.
-
-        performLayoutAndPlaceSurfacesLocked();
-        mInputMonitor.updateInputWindowsLw(false /*force*/);
-
-        //dump();
-    }
-
-    @Override
-    public void moveAppTokensToTop(List<IBinder> tokens) {
-        if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
-                "moveAppTokensToTop()")) {
-            throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
-        }
-
-        final long origId = Binder.clearCallingIdentity();
-        synchronized(mWindowMap) {
-            DisplayContent displayContent = null;
-            removeAppTokensLocked(tokens);
-            final int N = tokens.size();
-            for (int i=0; i<N; i++) {
-                AppWindowToken wt = findAppWindowToken(tokens.get(i));
-                if (wt != null) {
-                    if (DEBUG_TOKEN_MOVEMENT || DEBUG_REORDER) {
-                        Slog.v(TAG, "Adding next to top: " + wt);
-                        if (displayContent != null &&
-                                displayContent != mTaskIdToDisplayContents.get(wt.groupId)) Slog.e(
-                                    TAG, "moveAppTokensToTop: Not all tokens on same display");
-                    }
-                    displayContent = mTaskIdToDisplayContents.get(wt.groupId);
-                    displayContent.mAppTokens.add(wt);
-                    if (mAppTransition.isTransitionSet()) {
-                        wt.sendingToBottom = false;
-                    }
-                }
-            }
-
-            displayContent.refillAnimatingAppTokens();
-            moveAppWindowsLocked(tokens, displayContent, displayContent.mAppTokens.size());
-        }
-        Binder.restoreCallingIdentity(origId);
-    }
-
-    @Override
-    public void moveAppTokensToBottom(List<IBinder> tokens) {
-        if (!checkCallingPermission(android.Manifest.permission.MANAGE_APP_TOKENS,
-                "moveAppTokensToBottom()")) {
-            throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
-        }
-
-        final long origId = Binder.clearCallingIdentity();
-        synchronized(mWindowMap) {
-            DisplayContent displayContent = null;
-            final int N = tokens.size();
-            if (N > 0) {
-                // animating towards back, hang onto old list for duration of animation.
-                AppWindowToken wt = findAppWindowToken(tokens.get(0));
-                if (wt != null) {
-                    displayContent = mTaskIdToDisplayContents.get(wt.groupId);
-                    displayContent.refillAnimatingAppTokens();
-                }
-            }
-            removeAppTokensLocked(tokens);
-            int pos = 0;
-            for (int i=0; i<N; i++) {
-                AppWindowToken wt = findAppWindowToken(tokens.get(i));
-                if (wt != null) {
-                    if (DEBUG_TOKEN_MOVEMENT) {
-                        Slog.v(TAG, "Adding next to bottom: " + wt + " at " + pos);
-                        if (displayContent != null &&
-                                displayContent != mTaskIdToDisplayContents.get(wt.groupId)) Slog.e(
-                                    TAG, "moveAppTokensToBottom: Not all tokens on same display");
-                    }
-                    displayContent = mTaskIdToDisplayContents.get(wt.groupId);
-                    displayContent.mAppTokens.add(pos, wt);
-                    if (mAppTransition.isTransitionSet()) {
-                        wt.sendingToBottom = true;
-                    }
-                    pos++;
-                }
-            }
-
-            displayContent.refillAnimatingAppTokens();
-            moveAppWindowsLocked(tokens, displayContent, 0);
-        }
-        Binder.restoreCallingIdentity(origId);
-    }
-
     private void moveTaskWindowsLocked(int taskId) {
         DisplayContent displayContent = mTaskIdToDisplayContents.get(taskId);
         if (displayContent == null) {
@@ -4764,15 +4481,6 @@
             return;
         }
 
-        WindowList windows;
-        WindowList windowsAtStart;
-        if (DEBUG_TASK_MOVEMENT) {
-            windows = displayContent.getWindowList();
-            windowsAtStart = new WindowList(windows);
-            windows.clear();
-            windows.addAll(mSavedWindows);
-        }
-
         TaskList taskList = displayContent.mTaskIdToTaskList.get(taskId);
         if (taskList == null) {
             Slog.w(TAG, "moveTaskWindowsLocked: can't find TaskList for taskId=" + taskId);
@@ -4801,19 +4509,6 @@
             assignLayersLocked(displayContent.getWindowList());
         }
 
-        if (DEBUG_TASK_MOVEMENT) {
-            // Compare windowsAtStart with current windows.
-            if (windowsAtStart.size() != windows.size()) {
-                Slog.e(TAG, "moveTaskWindowsLocked: Mismatch in size!");
-            }
-            for (int i = 0; i < windowsAtStart.size(); i++) {
-                if (windowsAtStart.get(i) != windows.get(i)) {
-                    Slog.e(TAG, "moveTaskWindowsLocked: Mismatch at " + i
-                            + " app=" + windowsAtStart.get(i) + " task=" + windows.get(i));
-                }
-            }
-        }
-
         updateFocusedWindowLocked(UPDATE_FOCUS_WILL_PLACE_SURFACES,
                 false /*updateInputWindows*/);
         mInputMonitor.setUpdateInputWindowsNeededLw();
@@ -4843,9 +4538,7 @@
                     Slog.e(TAG, "moveTaskToTop: taskId=" + taskId + " not found in mTaskLists");
                 }
                 displayContent.mTaskLists.add(taskList);
-                displayContent.verifyAppTokens();
 
-                displayContent.refillAnimatingAppTokens();
                 moveTaskWindowsLocked(taskId);
             }
         } finally {
@@ -4873,9 +4566,7 @@
                     Slog.e(TAG, "moveTaskToBottom: taskId=" + taskId + " not found in mTaskLists");
                 }
                 displayContent.mTaskLists.add(0, taskList);
-                displayContent.verifyAppTokens();
 
-                displayContent.refillAnimatingAppTokens();
                 moveTaskWindowsLocked(taskId);
             }
         } finally {
@@ -7125,7 +6816,6 @@
                         if (mAppTransition.isTransitionSet()) {
                             if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "*** APP TRANSITION TIMEOUT");
                             mAppTransition.setTimeout();
-                            getDefaultDisplayContentLocked().refillAnimatingAppTokens();
                             performLayoutAndPlaceSurfacesLocked();
                         }
                     }
@@ -7634,10 +7324,9 @@
         }
 
         // And add in the still active app tokens in Z order.
-        AppTokenList animatingAppTokens = displayContent.mAnimatingAppTokens;
-        NT = animatingAppTokens.size();
-        for (int j=0; j<NT; j++) {
-            i = reAddAppWindowsLocked(displayContent, i, animatingAppTokens.get(j));
+        AppTokenIterator iterator = displayContent.new AppTokenIterator();
+        while (iterator.hasNext()) {
+            i = reAddAppWindowsLocked(displayContent, i, iterator.next());
         }
 
         i -= lastBelow;
@@ -7657,7 +7346,7 @@
                 }
             }
             Slog.w(TAG, "Current app token list:");
-            dumpAnimatingAppTokensLocked();
+            dumpAppTokensLocked();
             Slog.w(TAG, "Final window list:");
             dumpWindowsLocked();
         }
@@ -8308,11 +7997,10 @@
         mAppTransition.setIdle();
         // Restore window app tokens to the ActivityManager views
         final DisplayContent displayContent = getDefaultDisplayContentLocked();
-        final AppTokenList animatingAppTokens = displayContent.mAnimatingAppTokens;
-        for (int i = animatingAppTokens.size() - 1; i >= 0; i--) {
-            animatingAppTokens.get(i).sendingToBottom = false;
+        AppTokenIterator iterator = displayContent.new AppTokenIterator();
+        while (iterator.hasNext()) {
+            iterator.next().sendingToBottom = false;
         }
-        displayContent.refillAnimatingAppTokens();
         rebuildAppWindowListLocked();
 
         changes |= PhoneWindowManager.FINISH_LAYOUT_REDO_LAYOUT;
@@ -8469,10 +8157,9 @@
     private void updateAllDrawnLocked(DisplayContent displayContent) {
         // See if any windows have been drawn, so they (and others
         // associated with them) can now be shown.
-        final AppTokenList appTokens = displayContent.mAnimatingAppTokens;
-        final int NT = appTokens.size();
-        for (int i=0; i<NT; i++) {
-            AppWindowToken wtoken = appTokens.get(i);
+        AppTokenIterator iterator = displayContent.new AppTokenIterator();
+        while (iterator.hasNext()) {
+            AppWindowToken wtoken = iterator.next();
             if (!wtoken.allDrawn) {
                 int numInteresting = wtoken.numInterestingWindows;
                 if (numInteresting > 0 && wtoken.numDrawnWindows >= numInteresting) {
@@ -9833,23 +9520,6 @@
                 }
             }
         }
-        final AppTokenList animatingAppTokens =
-                getDefaultDisplayContentLocked().mAnimatingAppTokens;
-        if (mAppTransition.isRunning() && animatingAppTokens.size() > 0) {
-            pw.println();
-            pw.println("  Application tokens during animation:");
-            for (int i=animatingAppTokens.size()-1; i>=0; i--) {
-                WindowToken token = animatingAppTokens.get(i);
-                pw.print("  App moving to bottom #"); pw.print(i);
-                        pw.print(' '); pw.print(token);
-                if (dumpAll) {
-                    pw.println(':');
-                    token.dump(pw, "    ");
-                } else {
-                    pw.println();
-                }
-            }
-        }
         if (mOpeningApps.size() > 0 || mClosingApps.size() > 0) {
             pw.println();
             if (mOpeningApps.size() > 0) {
diff --git a/services/java/com/android/server/wm/WindowState.java b/services/java/com/android/server/wm/WindowState.java
index e49d20b..f0045b1 100644
--- a/services/java/com/android/server/wm/WindowState.java
+++ b/services/java/com/android/server/wm/WindowState.java
@@ -1064,7 +1064,7 @@
         return true;
     }
 
-    public boolean setAppOpVisibilityLw(boolean state) {
+    public void setAppOpVisibilityLw(boolean state) {
         if (mAppOpVisibility != state) {
             mAppOpVisibility = state;
             if (state) {
@@ -1074,13 +1074,11 @@
                 // ops modifies they should only be hidden by policy due to the
                 // lock screen, and the user won't be changing this if locked.
                 // Plus it will quickly be fixed the next time we do a layout.
-                showLw(true, false);
+                showLw(true, true);
             } else {
-                hideLw(true, false);
+                hideLw(true, true);
             }
-            return true;
         }
-        return false;
     }
 
     @Override
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/BitmapMeshActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/BitmapMeshActivity.java
index 854dd69..69d34a5 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/BitmapMeshActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/BitmapMeshActivity.java
@@ -54,7 +54,7 @@
                 0.0f, height * 2, width, height * 2, width * 2, height * 2, width * 3, height * 2,
                 0.0f, height * 4, width, height * 4, width * 2, height * 4, width * 4, height * 4,
             };
-            
+
             mColors = new int[] {
                 0xffff0000, 0xff00ff00, 0xff0000ff, 0xffff0000,
                 0xff0000ff, 0xffff0000, 0xff00ff00, 0xff00ff00,
diff --git a/tests/RenderScriptTests/LivePreview/res/layout/cf_main.xml b/tests/RenderScriptTests/LivePreview/res/layout/cf_main.xml
index c7dcca5..ecb736b 100644
--- a/tests/RenderScriptTests/LivePreview/res/layout/cf_main.xml
+++ b/tests/RenderScriptTests/LivePreview/res/layout/cf_main.xml
@@ -53,7 +53,7 @@
             android:layout_height="fill_parent"
             android:layout_weight="3" >
 
-            <ImageView
+            <TextureView
                 android:id="@+id/format_view"
                 android:layout_height="0dp"
                 android:layout_width="fill_parent"
diff --git a/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/CameraPreviewActivity.java b/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/CameraPreviewActivity.java
index 89eec2c..62dcaa8 100644
--- a/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/CameraPreviewActivity.java
+++ b/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/CameraPreviewActivity.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 The Android Open Source Project
+ * Copyright (C) 2013 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.
@@ -65,7 +65,7 @@
     private int mPreviewTexWidth;
     private int mPreviewTexHeight;
 
-    private ImageView mFormatView;
+    //private TextureView mFormatView;
 
     private Spinner mCameraSpinner;
     private Spinner mResolutionSpinner;
@@ -77,7 +77,8 @@
     private Camera.Size mNextPreviewSize;
     private Camera.Size mPreviewSize;
 
-    private Bitmap mCallbackBitmap;
+    private TextureView mOutputView;
+    //private Bitmap mCallbackBitmap;
 
     private static final int STATE_OFF = 0;
     private static final int STATE_PREVIEW = 1;
@@ -97,7 +98,7 @@
         setContentView(R.layout.cf_main);
 
         mPreviewView = (TextureView) findViewById(R.id.preview_view);
-        mFormatView = (ImageView) findViewById(R.id.format_view);
+        mOutputView = (TextureView) findViewById(R.id.format_view);
 
         mPreviewView.setSurfaceTextureListener(this);
 
@@ -115,8 +116,9 @@
         mResolutionSpinner = (Spinner) findViewById(R.id.resolution_selection);
         mResolutionSpinner.setOnItemSelectedListener(mResolutionSelectedListener);
 
-
         mRS = RenderScript.create(this);
+        mFilterYuv = new RsYuv(mRS);
+        mOutputView.setSurfaceTextureListener(mFilterYuv);
     }
 
     @Override
@@ -227,8 +229,8 @@
 
         // Set initial values
 
-        mNextPreviewSize = mPreviewSizes.get(0);
-        mResolutionSpinner.setSelection(0);
+        mNextPreviewSize = mPreviewSizes.get(15);
+        mResolutionSpinner.setSelection(15);
 
         if (mPreviewTexture != null) {
             startPreview();
@@ -271,6 +273,7 @@
                 mPreviewTexHeight * (1 - heightRatio/widthRatio)/2);
 
         mPreviewView.setTransform(transform);
+        mOutputView.setTransform(transform);
 
         mPreviewSize   = mNextPreviewSize;
 
@@ -305,7 +308,7 @@
 
             long t1 = java.lang.System.currentTimeMillis();
 
-            mFilterYuv.execute(data, mCallbackBitmap);
+            mFilterYuv.execute(data);
 
             long t2 = java.lang.System.currentTimeMillis();
             mTiming[mTimingSlot++] = t2 - t1;
@@ -325,7 +328,7 @@
         }
 
         protected void onPostExecute(Boolean result) {
-            mFormatView.invalidate();
+            mOutputView.invalidate();
         }
 
     }
@@ -355,21 +358,13 @@
 
         mProcessInProgress = true;
 
-        if (mCallbackBitmap == null ||
-                mPreviewSize.width != mCallbackBitmap.getWidth() ||
-                mPreviewSize.height != mCallbackBitmap.getHeight() ) {
-            mCallbackBitmap =
-                    Bitmap.createBitmap(
-                        mPreviewSize.width, mPreviewSize.height,
-                        Bitmap.Config.ARGB_8888);
-            mFilterYuv = new RsYuv(mRS, getResources(), mPreviewSize.width, mPreviewSize.height);
-            mFormatView.setImageBitmap(mCallbackBitmap);
+        if ((mFilterYuv == null) ||
+            (mPreviewSize.width != mFilterYuv.getWidth()) ||
+            (mPreviewSize.height != mFilterYuv.getHeight()) ) {
+
+            mFilterYuv.reset(mPreviewSize.width, mPreviewSize.height);
         }
 
-
-        mFormatView.invalidate();
-
-        mCamera.addCallbackBuffer(data);
         mProcessInProgress = true;
         new ProcessPreviewDataTask().execute(data);
     }
diff --git a/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/RsYuv.java b/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/RsYuv.java
index 978ae12..4d1627d 100644
--- a/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/RsYuv.java
+++ b/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/RsYuv.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 The Android Open Source Project
+ * Copyright (C) 2013 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.
@@ -34,7 +34,7 @@
 
 import android.graphics.Bitmap;
 
-public class RsYuv
+public class RsYuv implements TextureView.SurfaceTextureListener
 {
     private int mHeight;
     private int mWidth;
@@ -43,36 +43,104 @@
     private Allocation mAllocationIn;
     private ScriptC_yuv mScript;
     private ScriptIntrinsicYuvToRGB mYuv;
+    private boolean mHaveSurface;
+    private SurfaceTexture mSurface;
+    private ScriptGroup mGroup;
 
-    RsYuv(RenderScript rs, Resources res, int width, int height) {
+    RsYuv(RenderScript rs) {
+        mRS = rs;
+        mScript = new ScriptC_yuv(mRS);
+        mYuv = ScriptIntrinsicYuvToRGB.create(rs, Element.RGBA_8888(mRS));
+    }
+
+    void setupSurface() {
+        if (mAllocationOut != null) {
+            mAllocationOut.setSurfaceTexture(mSurface);
+        }
+        if (mSurface != null) {
+            mHaveSurface = true;
+        } else {
+            mHaveSurface = false;
+        }
+    }
+
+    void reset(int width, int height) {
+        if (mAllocationOut != null) {
+            mAllocationOut.destroy();
+        }
+
+        android.util.Log.v("cpa", "reset " + width + ", " + height);
         mHeight = height;
         mWidth = width;
-        mRS = rs;
-        mScript = new ScriptC_yuv(mRS, res, R.raw.yuv);
         mScript.invoke_setSize(mWidth, mHeight);
 
-        mYuv = ScriptIntrinsicYuvToRGB.create(rs, Element.RGBA_8888(mRS));
-
         Type.Builder tb = new Type.Builder(mRS, Element.RGBA_8888(mRS));
         tb.setX(mWidth);
         tb.setY(mHeight);
-
-        mAllocationOut = Allocation.createTyped(rs, tb.create());
-        mAllocationIn = Allocation.createSized(rs, Element.U8(mRS), (mHeight * mWidth) +
+        Type t = tb.create();
+        mAllocationOut = Allocation.createTyped(mRS, t, Allocation.USAGE_SCRIPT |
+                                                        Allocation.USAGE_IO_OUTPUT);
+        mAllocationIn = Allocation.createSized(mRS, Element.U8(mRS), (mHeight * mWidth) +
                                                ((mHeight / 2) * (mWidth / 2) * 2));
-
         mYuv.setInput(mAllocationIn);
+        setupSurface();
+
+
+        ScriptGroup.Builder b = new ScriptGroup.Builder(mRS);
+        b.addKernel(mScript.getKernelID_root());
+        b.addKernel(mYuv.getKernelID());
+        b.addConnection(t, mYuv.getKernelID(), mScript.getKernelID_root());
+        mGroup = b.create();
+    }
+
+    public int getWidth() {
+        return mWidth;
+    }
+    public int getHeight() {
+        return mHeight;
     }
 
     private long mTiming[] = new long[50];
     private int mTimingSlot = 0;
 
-    void execute(byte[] yuv, Bitmap b) {
+    void execute(byte[] yuv) {
         mAllocationIn.copyFrom(yuv);
-        mYuv.forEach(mAllocationOut);
-        mScript.forEach_root(mAllocationOut, mAllocationOut);
-        mAllocationOut.copyTo(b);
+        if (mHaveSurface) {
+            mGroup.setOutput(mScript.getKernelID_root(), mAllocationOut);
+            mGroup.execute();
+
+            //mYuv.forEach(mAllocationOut);
+            //mScript.forEach_root(mAllocationOut, mAllocationOut);
+            mAllocationOut.ioSendOutput();
+        }
     }
 
+
+
+    @Override
+    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
+        android.util.Log.v("cpa", "onSurfaceTextureAvailable " + surface);
+        mSurface = surface;
+        setupSurface();
+    }
+
+    @Override
+    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
+        android.util.Log.v("cpa", "onSurfaceTextureSizeChanged " + surface);
+        mSurface = surface;
+        setupSurface();
+    }
+
+    @Override
+    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
+        android.util.Log.v("cpa", "onSurfaceTextureDestroyed " + surface);
+        mSurface = surface;
+        setupSurface();
+        return true;
+    }
+
+    @Override
+    public void onSurfaceTextureUpdated(SurfaceTexture surface) {
+    }
 }
 
diff --git a/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/yuv.rs b/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/yuv.rs
index 884812d..c4f698f 100644
--- a/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/yuv.rs
+++ b/tests/RenderScriptTests/LivePreview/src/com/android/rs/livepreview/yuv.rs
@@ -1,7 +1,7 @@
 
 #pragma version(1)
 #pragma rs java_package_name(com.android.rs.livepreview)
-#pragma rs_fp_relaxed
+//#pragma rs_fp_relaxed
 
 static int gWidth;
 static int gHeight;
diff --git a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
index 746ac06..03871f6 100644
--- a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
+++ b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
@@ -222,37 +222,7 @@
         } catch (RemoteException e) {
             fail("Unexpected remote exception");
         }
-        
-        try {
-            mWm.moveAppToken(0, null);
-            fail("IWindowManager.moveAppToken did not throw SecurityException as"
-                    + " expected");
-        } catch (SecurityException e) {
-            // expected
-        } catch (RemoteException e) {
-            fail("Unexpected remote exception");
-        }
-        
-        try {
-            mWm.moveAppTokensToTop(null);
-            fail("IWindowManager.moveAppTokensToTop did not throw SecurityException as"
-                    + " expected");
-        } catch (SecurityException e) {
-            // expected
-        } catch (RemoteException e) {
-            fail("Unexpected remote exception");
-        }
-        
-        try {
-            mWm.moveAppTokensToBottom(null);
-            fail("IWindowManager.moveAppTokensToBottom did not throw SecurityException as"
-                    + " expected");
-        } catch (SecurityException e) {
-            // expected
-        } catch (RemoteException e) {
-            fail("Unexpected remote exception");
-        }
-	}    
+    }
 
     @SmallTest
     public void testDISABLE_KEYGUARD() {
diff --git a/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java b/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java
index 9f116fc..ed44b04 100644
--- a/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java
+++ b/tools/layoutlib/bridge/src/android/view/IWindowManagerImpl.java
@@ -204,24 +204,6 @@
     }
 
     @Override
-    public void moveAppToken(int arg0, IBinder arg1) throws RemoteException {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void moveAppTokensToBottom(List<IBinder> arg0) throws RemoteException {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
-    public void moveAppTokensToTop(List<IBinder> arg0) throws RemoteException {
-        // TODO Auto-generated method stub
-
-    }
-
-    @Override
     public IWindowSession openSession(IInputMethodClient arg0, IInputContext arg1)
             throws RemoteException {
         // TODO Auto-generated method stub