Merge "Update preloaded-classes for KLP" into klp-dev
diff --git a/api/current.txt b/api/current.txt
index 9251d39..a8b5efd 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -20,13 +20,10 @@
     field public static final java.lang.String BATTERY_STATS = "android.permission.BATTERY_STATS";
     field public static final java.lang.String BIND_ACCESSIBILITY_SERVICE = "android.permission.BIND_ACCESSIBILITY_SERVICE";
     field public static final java.lang.String BIND_APPWIDGET = "android.permission.BIND_APPWIDGET";
-    field public static final java.lang.String BIND_CALL_SERVICE = "android.permission.BIND_CALL_SERVICE";
     field public static final java.lang.String BIND_DEVICE_ADMIN = "android.permission.BIND_DEVICE_ADMIN";
     field public static final java.lang.String BIND_INPUT_METHOD = "android.permission.BIND_INPUT_METHOD";
-    field public static final java.lang.String BIND_NFC_SERVICE = "android.permission.BIND_NFC_SERVICE";
     field public static final java.lang.String BIND_NOTIFICATION_LISTENER_SERVICE = "android.permission.BIND_NOTIFICATION_LISTENER_SERVICE";
     field public static final java.lang.String BIND_PRINT_SERVICE = "android.permission.BIND_PRINT_SERVICE";
-    field public static final java.lang.String BIND_PRINT_SPOOLER_SERVICE = "android.permission.BIND_PRINT_SPOOLER_SERVICE";
     field public static final java.lang.String BIND_REMOTEVIEWS = "android.permission.BIND_REMOTEVIEWS";
     field public static final java.lang.String BIND_TEXT_SERVICE = "android.permission.BIND_TEXT_SERVICE";
     field public static final java.lang.String BIND_VPN_SERVICE = "android.permission.BIND_VPN_SERVICE";
@@ -79,7 +76,6 @@
     field public static final java.lang.String LOCATION_HARDWARE = "android.permission.LOCATION_HARDWARE";
     field public static final java.lang.String MANAGE_ACCOUNTS = "android.permission.MANAGE_ACCOUNTS";
     field public static final java.lang.String MANAGE_APP_TOKENS = "android.permission.MANAGE_APP_TOKENS";
-    field public static final java.lang.String MANAGE_DEVICE_ADMINS = "android.permission.MANAGE_DEVICE_ADMINS";
     field public static final java.lang.String MANAGE_DOCUMENTS = "android.permission.MANAGE_DOCUMENTS";
     field public static final java.lang.String MASTER_CLEAR = "android.permission.MASTER_CLEAR";
     field public static final java.lang.String MEDIA_CONTENT_CONTROL = "android.permission.MEDIA_CONTENT_CONTROL";
@@ -4368,6 +4364,8 @@
     method public void clear() throws java.io.IOException;
     method public void clearWallpaperOffsets(android.os.IBinder);
     method public void forgetLoadedWallpaper();
+    method public android.graphics.drawable.Drawable getBuiltInDrawable();
+    method public android.graphics.drawable.Drawable getBuiltInDrawable(int, int, boolean, float, float);
     method public android.content.Intent getCropAndSetWallpaperIntent(android.net.Uri);
     method public int getDesiredMinimumHeight();
     method public int getDesiredMinimumWidth();
@@ -5759,6 +5757,7 @@
     method public static java.util.List<android.content.SyncInfo> getCurrentSyncs();
     method public static int getIsSyncable(android.accounts.Account, java.lang.String);
     method public static boolean getMasterSyncAutomatically();
+    method public java.util.List<android.content.UriPermission> getOutgoingPersistedUriPermissions();
     method public static java.util.List<android.content.PeriodicSync> getPeriodicSyncs(android.accounts.Account, java.lang.String);
     method public java.util.List<android.content.UriPermission> getPersistedUriPermissions();
     method public java.lang.String[] getStreamTypes(android.net.Uri, java.lang.String);
@@ -28397,6 +28396,7 @@
     field public static final int SYSTEM_UI_FLAG_FULLSCREEN = 4; // 0x4
     field public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 2; // 0x2
     field public static final int SYSTEM_UI_FLAG_IMMERSIVE = 2048; // 0x800
+    field public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 4096; // 0x1000
     field public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 1024; // 0x400
     field public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 512; // 0x200
     field public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 256; // 0x100
@@ -29285,6 +29285,7 @@
 
   public final class AccessibilityManager {
     method public boolean addAccessibilityStateChangeListener(android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener);
+    method public boolean addTouchExplorationStateChangeListener(android.view.accessibility.AccessibilityManager.TouchExplorationStateChangeListener);
     method public deprecated java.util.List<android.content.pm.ServiceInfo> getAccessibilityServiceList();
     method public java.util.List<android.accessibilityservice.AccessibilityServiceInfo> getEnabledAccessibilityServiceList(int);
     method public java.util.List<android.accessibilityservice.AccessibilityServiceInfo> getInstalledAccessibilityServiceList();
@@ -29292,6 +29293,7 @@
     method public boolean isEnabled();
     method public boolean isTouchExplorationEnabled();
     method public boolean removeAccessibilityStateChangeListener(android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener);
+    method public boolean removeTouchExplorationStateChangeListener(android.view.accessibility.AccessibilityManager.TouchExplorationStateChangeListener);
     method public void sendAccessibilityEvent(android.view.accessibility.AccessibilityEvent);
   }
 
@@ -29299,6 +29301,10 @@
     method public abstract void onAccessibilityStateChanged(boolean);
   }
 
+  public static abstract interface AccessibilityManager.TouchExplorationStateChangeListener {
+    method public abstract void onTouchExplorationStateChanged(boolean);
+  }
+
   public class AccessibilityNodeInfo implements android.os.Parcelable {
     method public void addAction(int);
     method public void addChild(android.view.View);
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index a38fbbf..e29f8ea 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -1455,12 +1455,14 @@
     }
 
     /**
-     * Report to the system that your app is now fully drawn.  This is only used
-     * to help instrument app launch times, so that the app can report when it is
-     * fully in a usable state; without this, all the system can determine is when
-     * its window is first drawn and displayed.  To participate in app launch time
+     * Report to the system that your app is now fully drawn, purely for diagnostic
+     * purposes (calling it does not impact the visible behavior of the activity).
+     * This is only used to help instrument application launch times, so that the
+     * app can report when it is fully in a usable state; without this, the only thing
+     * the system itself can determine is the point at which the activity's window
+     * is <em>first</em> drawn and displayed.  To participate in app launch time
      * measurement, you should always call this method after first launch (when
-     * {@link #onCreate(android.os.Bundle)} is called) at the point where you have
+     * {@link #onCreate(android.os.Bundle)} is called), at the point where you have
      * entirely drawn your UI and populated with all of the significant data.  You
      * can safely call this method any time after first launch as well, in which case
      * it will simply be ignored.
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index 1e65098..1067eb1 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -1463,7 +1463,10 @@
 
     /**
      * Permits an application to erase its own data from disk.  This is equivalent to
-     * the user choosing to clear the app's data from within the device settings UI.
+     * the user choosing to clear the app's data from within the device settings UI.  It
+     * erases all dynamic data associated with the app -- its private data and data in its
+     * private area on external storage -- but does not remove the installed application
+     * itself, nor any OBB files.
      *
      * @return {@code true} if the application successfully requested that the application's
      *     data be erased; {@code false} otherwise.
@@ -2253,7 +2256,9 @@
      * not be done on a UI thread.  The data will be written to the given file
      * descriptor as text.  An application must hold the
      * {@link android.Manifest.permission#DUMP} permission to make this call.
-     * @param fd The file descriptor that the dump should be written to.
+     * @param fd The file descriptor that the dump should be written to.  The file
+     * descriptor is <em>not</em> closed by this function; the caller continues to
+     * own it.
      * @param packageName The name of the package that is to be dumped.
      */
     public void dumpPackageState(FileDescriptor fd, String packageName) {
diff --git a/core/java/android/app/ActivityManagerNative.java b/core/java/android/app/ActivityManagerNative.java
index 961ee57..74266cc 100644
--- a/core/java/android/app/ActivityManagerNative.java
+++ b/core/java/android/app/ActivityManagerNative.java
@@ -1160,7 +1160,10 @@
 
         case GET_PERSISTED_URI_PERMISSIONS_TRANSACTION: {
             data.enforceInterface(IActivityManager.descriptor);
-            final ParceledListSlice<UriPermission> perms = getPersistedUriPermissions();
+            final String packageName = data.readString();
+            final boolean incoming = data.readInt() != 0;
+            final ParceledListSlice<UriPermission> perms = getPersistedUriPermissions(
+                    packageName, incoming);
             reply.writeNoException();
             perms.writeToParcel(reply, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
             return true;
@@ -3500,10 +3503,13 @@
     }
 
     @Override
-    public ParceledListSlice<UriPermission> getPersistedUriPermissions() throws RemoteException {
+    public ParceledListSlice<UriPermission> getPersistedUriPermissions(
+            String packageName, boolean incoming) throws RemoteException {
         Parcel data = Parcel.obtain();
         Parcel reply = Parcel.obtain();
         data.writeInterfaceToken(IActivityManager.descriptor);
+        data.writeString(packageName);
+        data.writeInt(incoming ? 1 : 0);
         mRemote.transact(GET_PERSISTED_URI_PERMISSIONS_TRANSACTION, data, reply, 0);
         reply.readException();
         final ParceledListSlice<UriPermission> perms = ParceledListSlice.CREATOR.createFromParcel(
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index e07b50f..df63ab3 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -95,6 +95,7 @@
 import com.android.internal.util.FastPrintWriter;
 import com.android.internal.util.Objects;
 import com.android.org.conscrypt.OpenSSLSocketImpl;
+import com.google.android.collect.Lists;
 
 import java.io.File;
 import java.io.FileDescriptor;
@@ -1277,6 +1278,11 @@
                 }
             }
         }
+
+        @Override
+        public void scheduleInstallProvider(ProviderInfo provider) {
+            queueOrSendMessage(H.INSTALL_PROVIDER, provider);
+        }
     }
 
     private class H extends Handler {
@@ -1325,6 +1331,7 @@
         public static final int UNSTABLE_PROVIDER_DIED  = 142;
         public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
         public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
+        public static final int INSTALL_PROVIDER        = 145;
         String codeToString(int code) {
             if (DEBUG_MESSAGES) {
                 switch (code) {
@@ -1373,6 +1380,7 @@
                     case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
                     case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
                     case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
+                    case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
                 }
             }
             return Integer.toString(code);
@@ -1590,6 +1598,9 @@
                 case TRANSLUCENT_CONVERSION_COMPLETE:
                     handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
                     break;
+                case INSTALL_PROVIDER:
+                    handleInstallProvider((ProviderInfo) msg.obj);
+                    break;
             }
             if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
         }
@@ -2330,6 +2341,10 @@
         }
     }
 
+    public void handleInstallProvider(ProviderInfo info) {
+        installContentProviders(mInitialApplication, Lists.newArrayList(info));
+    }
+
     private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
 
     /**
diff --git a/core/java/android/app/ApplicationThreadNative.java b/core/java/android/app/ApplicationThreadNative.java
index e40a04b..347d43f 100644
--- a/core/java/android/app/ApplicationThreadNative.java
+++ b/core/java/android/app/ApplicationThreadNative.java
@@ -618,6 +618,15 @@
             reply.writeNoException();
             return true;
         }
+
+        case SCHEDULE_INSTALL_PROVIDER_TRANSACTION:
+        {
+            data.enforceInterface(IApplicationThread.descriptor);
+            ProviderInfo provider = ProviderInfo.CREATOR.createFromParcel(data);
+            scheduleInstallProvider(provider);
+            reply.writeNoException();
+            return true;
+        }
         }
 
         return super.onTransact(code, data, reply, flags);
@@ -1248,4 +1257,13 @@
         mRemote.transact(SET_PROCESS_STATE_TRANSACTION, data, null, IBinder.FLAG_ONEWAY);
         data.recycle();
     }
+
+    @Override
+    public void scheduleInstallProvider(ProviderInfo provider) throws RemoteException {
+        Parcel data = Parcel.obtain();
+        data.writeInterfaceToken(IApplicationThread.descriptor);
+        provider.writeToParcel(data, 0);
+        mRemote.transact(SCHEDULE_INSTALL_PROVIDER_TRANSACTION, data, null, IBinder.FLAG_ONEWAY);
+        data.recycle();
+    }
 }
diff --git a/core/java/android/app/IActivityManager.java b/core/java/android/app/IActivityManager.java
index dfea736..77c2ea0 100644
--- a/core/java/android/app/IActivityManager.java
+++ b/core/java/android/app/IActivityManager.java
@@ -215,7 +215,8 @@
             int mode) throws RemoteException;
     public void takePersistableUriPermission(Uri uri, int modeFlags) throws RemoteException;
     public void releasePersistableUriPermission(Uri uri, int modeFlags) throws RemoteException;
-    public ParceledListSlice<UriPermission> getPersistedUriPermissions() throws RemoteException;
+    public ParceledListSlice<UriPermission> getPersistedUriPermissions(
+            String packageName, boolean incoming) throws RemoteException;
 
     public void showWaitingForDebugger(IApplicationThread who, boolean waiting)
             throws RemoteException;
diff --git a/core/java/android/app/IApplicationThread.java b/core/java/android/app/IApplicationThread.java
index 43a5fbd..d0cc1bb 100644
--- a/core/java/android/app/IApplicationThread.java
+++ b/core/java/android/app/IApplicationThread.java
@@ -137,6 +137,7 @@
     void scheduleTranslucentConversionComplete(IBinder token, boolean timeout)
             throws RemoteException;
     void setProcessState(int state) throws RemoteException;
+    void scheduleInstallProvider(ProviderInfo provider) throws RemoteException;
 
     String descriptor = "android.app.IApplicationThread";
 
@@ -189,4 +190,5 @@
     int REQUEST_ASSIST_CONTEXT_EXTRAS_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+47;
     int SCHEDULE_TRANSLUCENT_CONVERSION_COMPLETE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+48;
     int SET_PROCESS_STATE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+49;
+    int SCHEDULE_INSTALL_PROVIDER_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+50;
 }
diff --git a/core/java/android/app/WallpaperManager.java b/core/java/android/app/WallpaperManager.java
index 2bc7cbf..c39415f 100644
--- a/core/java/android/app/WallpaperManager.java
+++ b/core/java/android/app/WallpaperManager.java
@@ -16,7 +16,6 @@
 
 package android.app;
 
-import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
@@ -24,13 +23,16 @@
 import android.content.res.Resources;
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
+import android.graphics.BitmapRegionDecoder;
 import android.graphics.Canvas;
 import android.graphics.ColorFilter;
+import android.graphics.Matrix;
 import android.graphics.Paint;
 import android.graphics.PixelFormat;
 import android.graphics.PorterDuff;
 import android.graphics.PorterDuffXfermode;
 import android.graphics.Rect;
+import android.graphics.RectF;
 import android.graphics.drawable.BitmapDrawable;
 import android.graphics.drawable.Drawable;
 import android.net.Uri;
@@ -47,6 +49,7 @@
 import android.view.WindowManager;
 import android.view.WindowManagerGlobal;
 
+import java.io.BufferedInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
@@ -367,7 +370,7 @@
     
     /**
      * Retrieve the current system wallpaper; if
-     * no wallpaper is set, the system default wallpaper is returned.
+     * no wallpaper is set, the system built-in static wallpaper is returned.
      * This is returned as an
      * abstract Drawable that you can install in a View to display whatever
      * wallpaper the user has currently set. 
@@ -385,6 +388,178 @@
     }
 
     /**
+     * Returns a drawable for the system built-in static wallpaper .
+     *
+     */
+    public Drawable getBuiltInDrawable() {
+        return getBuiltInDrawable(0, 0, false, 0, 0);
+    }
+
+    /**
+     * Returns a drawable for the system built-in static wallpaper. Based on the parameters, the
+     * drawable can be cropped and scaled
+     *
+     * @param outWidth The width of the returned drawable
+     * @param outWidth The height of the returned drawable
+     * @param scaleToFit If true, scale the wallpaper down rather than just cropping it
+     * @param horizontalAlignment A float value between 0 and 1 specifying where to crop the image;
+     *        0 for left-aligned, 0.5 for horizontal center-aligned, and 1 for right-aligned
+     * @param verticalAlignment A float value between 0 and 1 specifying where to crop the image;
+     *        0 for top-aligned, 0.5 for vertical center-aligned, and 1 for bottom-aligned
+     *
+     */
+    public Drawable getBuiltInDrawable(int outWidth, int outHeight,
+            boolean scaleToFit, float horizontalAlignment, float verticalAlignment) {
+        if (sGlobals.mService == null) {
+            Log.w(TAG, "WallpaperService not running");
+            return null;
+        }
+        Resources resources = mContext.getResources();
+        horizontalAlignment = Math.max(0, Math.min(1, horizontalAlignment));
+        verticalAlignment = Math.max(0, Math.min(1, verticalAlignment));
+
+        InputStream is = new BufferedInputStream(
+                resources.openRawResource(com.android.internal.R.drawable.default_wallpaper));
+
+        if (is == null) {
+            Log.e(TAG, "default wallpaper input stream is null");
+            return null;
+        } else {
+            if (outWidth <= 0 || outHeight <= 0) {
+                Bitmap fullSize = BitmapFactory.decodeStream(is, null, null);
+                return new BitmapDrawable(resources, fullSize);
+            } else {
+                int inWidth;
+                int inHeight;
+                {
+                    BitmapFactory.Options options = new BitmapFactory.Options();
+                    options.inJustDecodeBounds = true;
+                    BitmapFactory.decodeStream(is, null, options);
+                    if (options.outWidth != 0 && options.outHeight != 0) {
+                        inWidth = options.outWidth;
+                        inHeight = options.outHeight;
+                    } else {
+                        Log.e(TAG, "default wallpaper dimensions are 0");
+                        return null;
+                    }
+                }
+
+                is = new BufferedInputStream(resources.openRawResource(
+                        com.android.internal.R.drawable.default_wallpaper));
+
+                RectF cropRectF;
+
+                outWidth = Math.min(inWidth, outWidth);
+                outHeight = Math.min(inHeight, outHeight);
+                if (scaleToFit) {
+                    cropRectF = getMaxCropRect(inWidth, inHeight, outWidth, outHeight,
+                        horizontalAlignment, verticalAlignment);
+                } else {
+                    float left = (inWidth - outWidth) * horizontalAlignment;
+                    float right = left + outWidth;
+                    float top = (inHeight - outHeight) * verticalAlignment;
+                    float bottom = top + outHeight;
+                    cropRectF = new RectF(bottom, left, right, top);
+                }
+                Rect roundedTrueCrop = new Rect();
+                cropRectF.roundOut(roundedTrueCrop);
+
+                if (roundedTrueCrop.width() <= 0 || roundedTrueCrop.height() <= 0) {
+                    Log.w(TAG, "crop has bad values for full size image");
+                    return null;
+                }
+
+                // See how much we're reducing the size of the image
+                int scaleDownSampleSize = Math.min(roundedTrueCrop.width() / outWidth,
+                        roundedTrueCrop.height() / outHeight);
+
+                // Attempt to open a region decoder
+                BitmapRegionDecoder decoder = null;
+                try {
+                    decoder = BitmapRegionDecoder.newInstance(is, true);
+                } catch (IOException e) {
+                    Log.w(TAG, "cannot open region decoder for default wallpaper");
+                }
+
+                Bitmap crop = null;
+                if (decoder != null) {
+                    // Do region decoding to get crop bitmap
+                    BitmapFactory.Options options = new BitmapFactory.Options();
+                    if (scaleDownSampleSize > 1) {
+                        options.inSampleSize = scaleDownSampleSize;
+                    }
+                    crop = decoder.decodeRegion(roundedTrueCrop, options);
+                    decoder.recycle();
+                }
+
+                if (crop == null) {
+                    // BitmapRegionDecoder has failed, try to crop in-memory
+                    is = new BufferedInputStream(resources.openRawResource(
+                            com.android.internal.R.drawable.default_wallpaper));
+                    Bitmap fullSize = null;
+                    if (is != null) {
+                        BitmapFactory.Options options = new BitmapFactory.Options();
+                        if (scaleDownSampleSize > 1) {
+                            options.inSampleSize = scaleDownSampleSize;
+                        }
+                        fullSize = BitmapFactory.decodeStream(is, null, options);
+                    }
+                    if (fullSize != null) {
+                        crop = Bitmap.createBitmap(fullSize, roundedTrueCrop.left,
+                                roundedTrueCrop.top, roundedTrueCrop.width(),
+                                roundedTrueCrop.height());
+                    }
+                }
+
+                if (crop == null) {
+                    Log.w(TAG, "cannot decode default wallpaper");
+                    return null;
+                }
+
+                // Scale down if necessary
+                if (outWidth > 0 && outHeight > 0 &&
+                        (crop.getWidth() != outWidth || crop.getHeight() != outHeight)) {
+                    Matrix m = new Matrix();
+                    RectF cropRect = new RectF(0, 0, crop.getWidth(), crop.getHeight());
+                    RectF returnRect = new RectF(0, 0, outWidth, outHeight);
+                    m.setRectToRect(cropRect, returnRect, Matrix.ScaleToFit.FILL);
+                    Bitmap tmp = Bitmap.createBitmap((int) returnRect.width(),
+                            (int) returnRect.height(), Bitmap.Config.ARGB_8888);
+                    if (tmp != null) {
+                        Canvas c = new Canvas(tmp);
+                        Paint p = new Paint();
+                        p.setFilterBitmap(true);
+                        c.drawBitmap(crop, m, p);
+                        crop = tmp;
+                    }
+                }
+
+                return new BitmapDrawable(resources, crop);
+            }
+        }
+    }
+
+    private static RectF getMaxCropRect(int inWidth, int inHeight, int outWidth, int outHeight,
+                float horizontalAlignment, float verticalAlignment) {
+        RectF cropRect = new RectF();
+        // Get a crop rect that will fit this
+        if (inWidth / (float) inHeight > outWidth / (float) outHeight) {
+             cropRect.top = 0;
+             cropRect.bottom = inHeight;
+             float cropWidth = outWidth * (inHeight / (float) outHeight);
+             cropRect.left = (inWidth - cropWidth) * horizontalAlignment;
+             cropRect.right = cropRect.left + cropWidth;
+        } else {
+            cropRect.left = 0;
+            cropRect.right = inWidth;
+            float cropHeight = outHeight * (inWidth / (float) outWidth);
+            cropRect.top = (inHeight - cropHeight) * verticalAlignment;
+            cropRect.bottom = cropRect.top + cropHeight;
+        }
+        return cropRect;
+    }
+
+    /**
      * Retrieve the current system wallpaper; if there is no wallpaper set,
      * a null pointer is returned. This is returned as an
      * abstract Drawable that you can install in a View to display whatever
@@ -519,7 +694,7 @@
      *
      * @param resid The bitmap to save.
      *
-     * @throws IOException If an error occurs reverting to the default
+     * @throws IOException If an error occurs reverting to the built-in
      * wallpaper.
      */
     public void setResource(int resid) throws IOException {
@@ -558,7 +733,7 @@
      *
      * @param bitmap The bitmap to save.
      *
-     * @throws IOException If an error occurs reverting to the default
+     * @throws IOException If an error occurs reverting to the built-in
      * wallpaper.
      */
     public void setBitmap(Bitmap bitmap) throws IOException {
@@ -597,7 +772,7 @@
      *
      * @param data A stream containing the raw data to install as a wallpaper.
      *
-     * @throws IOException If an error occurs reverting to the default
+     * @throws IOException If an error occurs reverting to the built-in
      * wallpaper.
      */
     public void setStream(InputStream data) throws IOException {
@@ -819,14 +994,14 @@
     }
     
     /**
-     * Remove any currently set wallpaper, reverting to the system's default
+     * Remove any currently set wallpaper, reverting to the system's built-in
      * wallpaper. On success, the intent {@link Intent#ACTION_WALLPAPER_CHANGED}
      * is broadcast.
      *
      * <p>This method requires the caller to hold the permission
      * {@link android.Manifest.permission#SET_WALLPAPER}.
      *
-     * @throws IOException If an error occurs reverting to the default
+     * @throws IOException If an error occurs reverting to the built-in
      * wallpaper.
      */
     public void clear() throws IOException {
diff --git a/core/java/android/content/ContentResolver.java b/core/java/android/content/ContentResolver.java
index 916a6cd..49dfdb5 100644
--- a/core/java/android/content/ContentResolver.java
+++ b/core/java/android/content/ContentResolver.java
@@ -1659,8 +1659,9 @@
     }
 
     /**
-     * Return list of all Uri permission grants that have been persisted for the
-     * calling app. Only persistable grants taken with
+     * Return list of all Uri permission grants that have been persisted by the
+     * calling app. That is, the returned permissions have been granted
+     * <em>to</em> the calling app. Only persistable grants taken with
      * {@link #takePersistableUriPermission(Uri, int)} are returned.
      *
      * @see #takePersistableUriPermission(Uri, int)
@@ -1668,7 +1669,23 @@
      */
     public List<UriPermission> getPersistedUriPermissions() {
         try {
-            return ActivityManagerNative.getDefault().getPersistedUriPermissions().getList();
+            return ActivityManagerNative.getDefault()
+                    .getPersistedUriPermissions(mPackageName, true).getList();
+        } catch (RemoteException e) {
+            throw new RuntimeException("Activity manager has died", e);
+        }
+    }
+
+    /**
+     * Return list of all persisted Uri permission grants that are hosted by the
+     * calling app. That is, the returned permissions have been granted
+     * <em>from</em> the calling app. Only grants taken with
+     * {@link #takePersistableUriPermission(Uri, int)} are returned.
+     */
+    public List<UriPermission> getOutgoingPersistedUriPermissions() {
+        try {
+            return ActivityManagerNative.getDefault()
+                    .getPersistedUriPermissions(mPackageName, false).getList();
         } catch (RemoteException e) {
             throw new RuntimeException("Activity manager has died", e);
         }
diff --git a/core/java/android/content/IntentFilter.java b/core/java/android/content/IntentFilter.java
index 5760a5d..dad0dfb 100644
--- a/core/java/android/content/IntentFilter.java
+++ b/core/java/android/content/IntentFilter.java
@@ -722,6 +722,14 @@
      * included in the filter, then an Intent's data must match one of
      * them.  If no scheme specific parts are included, then only the scheme must match.
      *
+     * <p>The "scheme specific part" that this matches against is the string returned
+     * by {@link android.net.Uri#getSchemeSpecificPart() Uri.getSchemeSpecificPart}.
+     * For Uris that contain a path, this kind of matching is not generally of interest,
+     * since {@link #addDataAuthority(String, String)} and
+     * {@link #addDataPath(String, int)} can provide a better mechanism for matching
+     * them.  However, for Uris that do not contain a path, the authority and path
+     * are empty, so this is the only way to match against the non-scheme part.</p>
+     *
      * @param ssp Either a raw string that must exactly match the scheme specific part
      * path, or a simple pattern, depending on <var>type</var>.
      * @param type Determines how <var>ssp</var> will be compared to
diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java
index f30bcc5..898f123 100644
--- a/core/java/android/hardware/camera2/CaptureRequest.java
+++ b/core/java/android/hardware/camera2/CaptureRequest.java
@@ -82,6 +82,7 @@
     private CaptureRequest(CaptureRequest source) {
         mSettings = new CameraMetadataNative(source.mSettings);
         mSurfaceSet = (HashSet<Surface>) source.mSurfaceSet.clone();
+        mUserTag = source.mUserTag;
     }
 
     /**
diff --git a/core/java/android/inputmethodservice/InputMethodService.java b/core/java/android/inputmethodservice/InputMethodService.java
index 9319d4a..1b7d9ea 100644
--- a/core/java/android/inputmethodservice/InputMethodService.java
+++ b/core/java/android/inputmethodservice/InputMethodService.java
@@ -687,6 +687,8 @@
         mThemeAttrs = obtainStyledAttributes(android.R.styleable.InputMethodService);
         mRootView = mInflater.inflate(
                 com.android.internal.R.layout.input_method, null);
+        mRootView.setSystemUiVisibility(
+                View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
         mWindow.setContentView(mRootView);
         mRootView.getViewTreeObserver().addOnComputeInternalInsetsListener(mInsetsComputer);
         if (Settings.Global.getInt(getContentResolver(),
diff --git a/core/java/android/provider/DocumentsContract.java b/core/java/android/provider/DocumentsContract.java
index 1c14c38..c5e4f21 100644
--- a/core/java/android/provider/DocumentsContract.java
+++ b/core/java/android/provider/DocumentsContract.java
@@ -23,8 +23,7 @@
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.ProviderInfo;
+import android.content.pm.ResolveInfo;
 import android.content.res.AssetFileDescriptor;
 import android.database.Cursor;
 import android.graphics.Bitmap;
@@ -69,16 +68,15 @@
     private DocumentsContract() {
     }
 
-    /** {@hide} */
-    @Deprecated
-    public static final String META_DATA_DOCUMENT_PROVIDER = "android.content.DOCUMENT_PROVIDER";
-
     /**
      * Intent action used to identify {@link DocumentsProvider} instances.
      */
     public static final String PROVIDER_INTERFACE = "android.content.action.DOCUMENTS_PROVIDER";
 
     /** {@hide} */
+    public static final String EXTRA_PACKAGE_NAME = "android.content.extra.PACKAGE_NAME";
+
+    /** {@hide} */
     public static final String ACTION_MANAGE_ROOT = "android.provider.action.MANAGE_ROOT";
     /** {@hide} */
     public static final String ACTION_MANAGE_DOCUMENT = "android.provider.action.MANAGE_DOCUMENT";
@@ -565,11 +563,13 @@
             return false;
         }
 
-        final ProviderInfo info = context.getPackageManager()
-                .resolveContentProvider(uri.getAuthority(), PackageManager.GET_META_DATA);
-        if (info != null && info.metaData != null && info.metaData.containsKey(
-                DocumentsContract.META_DATA_DOCUMENT_PROVIDER)) {
-            return true;
+        final Intent intent = new Intent(PROVIDER_INTERFACE);
+        final List<ResolveInfo> infos = context.getPackageManager()
+                .queryIntentContentProviders(intent, 0);
+        for (ResolveInfo info : infos) {
+            if (uri.getAuthority().equals(info.providerInfo.authority)) {
+                return true;
+            }
         }
         return false;
     }
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index c45307b..01da6b3 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -2423,6 +2423,16 @@
 
     /**
      * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
+     * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  If this flag is
+     * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any
+     * user interaction.
+     * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only
+     * has an effect when used in combination with that flag.</p>
+     */
+    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
+
+    /**
+     * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when
      * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation
      * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  Use this flag to create an immersive
      * experience while also hiding the system bars.  If this flag is not set,
@@ -2437,7 +2447,7 @@
      * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination
      * with one or both of those flags.</p>
      */
-    public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800;
+    public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000;
 
     /**
      * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
@@ -8885,10 +8895,10 @@
              */
             mPrivateFlags |= PFLAG_DRAWN;
 
-            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
+            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) {
                 // root view becoming invisible shouldn't clear focus and accessibility focus
                 if (getRootView() != this) {
-                    clearFocus();
+                    if (hasFocus()) clearFocus();
                     clearAccessibilityFocus();
                 }
             }
@@ -16934,7 +16944,8 @@
      * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
      * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
      * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
-     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, and {@link #SYSTEM_UI_FLAG_IMMERSIVE}.
+     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
+     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
      */
     public void setSystemUiVisibility(int visibility) {
         if (visibility != mSystemUiVisibility) {
@@ -16950,7 +16961,8 @@
      * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
      * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
      * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
-     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, and {@link #SYSTEM_UI_FLAG_IMMERSIVE}.
+     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE},
+     * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}.
      */
     public int getSystemUiVisibility() {
         return mSystemUiVisibility;
diff --git a/core/java/android/view/accessibility/AccessibilityManager.java b/core/java/android/view/accessibility/AccessibilityManager.java
index 04ce7e2..00f4adb 100644
--- a/core/java/android/view/accessibility/AccessibilityManager.java
+++ b/core/java/android/view/accessibility/AccessibilityManager.java
@@ -91,25 +91,45 @@
 
     boolean mIsTouchExplorationEnabled;
 
-    final CopyOnWriteArrayList<AccessibilityStateChangeListener> mAccessibilityStateChangeListeners =
-        new CopyOnWriteArrayList<AccessibilityStateChangeListener>();
+    private final CopyOnWriteArrayList<AccessibilityStateChangeListener>
+            mAccessibilityStateChangeListeners = new CopyOnWriteArrayList<
+                    AccessibilityStateChangeListener>();
+
+    private final CopyOnWriteArrayList<TouchExplorationStateChangeListener>
+            mTouchExplorationStateChangeListeners = new CopyOnWriteArrayList<
+                    TouchExplorationStateChangeListener>();
 
     /**
-     * Listener for the system accessibility state. To listen for changes to the accessibility
-     * state on the device, implement this interface and register it with the system by
-     * calling {@link AccessibilityManager#addAccessibilityStateChangeListener
-     * addAccessibilityStateChangeListener()}.
+     * Listener for the system accessibility state. To listen for changes to the
+     * accessibility state on the device, implement this interface and register
+     * it with the system by calling {@link #addAccessibilityStateChangeListener}.
      */
     public interface AccessibilityStateChangeListener {
 
         /**
-         * Called back on change in the accessibility state.
+         * Called when the accessibility enabled state changes.
          *
          * @param enabled Whether accessibility is enabled.
          */
         public void onAccessibilityStateChanged(boolean enabled);
     }
 
+    /**
+     * Listener for the system touch exploration state. To listen for changes to
+     * the touch exploration state on the device, implement this interface and
+     * register it with the system by calling
+     * {@link #addTouchExplorationStateChangeListener}.
+     */
+    public interface TouchExplorationStateChangeListener {
+
+        /**
+         * Called when the touch exploration enabled state changes.
+         *
+         * @param enabled Whether touch exploration is enabled.
+         */
+        public void onTouchExplorationStateChanged(boolean enabled);
+    }
+
     final IAccessibilityManagerClient.Stub mClient = new IAccessibilityManagerClient.Stub() {
         public void setState(int state) {
             mHandler.obtainMessage(DO_SET_STATE, state, 0).sendToTarget();
@@ -363,34 +383,61 @@
     }
 
     /**
-     * Sets the current state.
+     * Registers a {@link TouchExplorationStateChangeListener} for changes in
+     * the global touch exploration state of the system.
+     *
+     * @param listener The listener.
+     * @return True if successfully registered.
+     */
+    public boolean addTouchExplorationStateChangeListener(
+            TouchExplorationStateChangeListener listener) {
+        return mTouchExplorationStateChangeListeners.add(listener);
+    }
+
+    /**
+     * Unregisters a {@link TouchExplorationStateChangeListener}.
+     *
+     * @param listener The listener.
+     * @return True if successfully unregistered.
+     */
+    public boolean removeTouchExplorationStateChangeListener(
+            TouchExplorationStateChangeListener listener) {
+        return mTouchExplorationStateChangeListeners.remove(listener);
+    }
+
+    /**
+     * Sets the current state and notifies listeners, if necessary.
      *
      * @param stateFlags The state flags.
      */
     private void setState(int stateFlags) {
-        final boolean accessibilityEnabled = (stateFlags & STATE_FLAG_ACCESSIBILITY_ENABLED) != 0;
-        setAccessibilityState(accessibilityEnabled);
-        mIsTouchExplorationEnabled = (stateFlags & STATE_FLAG_TOUCH_EXPLORATION_ENABLED) != 0;
-    }
-
-    /**
-     * Sets the enabled state.
-     *
-     * @param isEnabled The accessibility state.
-     */
-    private void setAccessibilityState(boolean isEnabled) {
+        final boolean enabled = (stateFlags & STATE_FLAG_ACCESSIBILITY_ENABLED) != 0;
+        final boolean touchExplorationEnabled =
+                (stateFlags & STATE_FLAG_TOUCH_EXPLORATION_ENABLED) != 0;
         synchronized (mHandler) {
-            if (isEnabled != mIsEnabled) {
-                mIsEnabled = isEnabled;
-                notifyAccessibilityStateChanged();
+            final boolean wasEnabled = mIsEnabled;
+            final boolean wasTouchExplorationEnabled = mIsTouchExplorationEnabled;
+
+            // Ensure listeners get current state from isZzzEnabled() calls.
+            mIsEnabled = enabled;
+            mIsTouchExplorationEnabled = touchExplorationEnabled;
+
+            if (wasEnabled != enabled) {
+                notifyAccessibilityStateChangedLh();
+            }
+
+            if (wasTouchExplorationEnabled != touchExplorationEnabled) {
+                notifyTouchExplorationStateChangedLh();
             }
         }
     }
 
     /**
      * Notifies the registered {@link AccessibilityStateChangeListener}s.
+     * <p>
+     * The caller must be locked on {@link #mHandler}.
      */
-    private void notifyAccessibilityStateChanged() {
+    private void notifyAccessibilityStateChangedLh() {
         final int listenerCount = mAccessibilityStateChangeListeners.size();
         for (int i = 0; i < listenerCount; i++) {
             mAccessibilityStateChangeListeners.get(i).onAccessibilityStateChanged(mIsEnabled);
@@ -398,6 +445,19 @@
     }
 
     /**
+     * Notifies the registered {@link TouchExplorationStateChangeListener}s.
+     * <p>
+     * The caller must be locked on {@link #mHandler}.
+     */
+    private void notifyTouchExplorationStateChangedLh() {
+        final int listenerCount = mTouchExplorationStateChangeListeners.size();
+        for (int i = 0; i < listenerCount; i++) {
+            mTouchExplorationStateChangeListeners.get(i)
+                    .onTouchExplorationStateChanged(mIsTouchExplorationEnabled);
+        }
+    }
+
+    /**
      * Adds an accessibility interaction connection interface for a given window.
      * @param windowToken The window token to which a connection is added.
      * @param connection The connection.
diff --git a/core/java/android/view/accessibility/AccessibilityNodeInfoCache.java b/core/java/android/view/accessibility/AccessibilityNodeInfoCache.java
index 6bef78e..7dd1e8a 100644
--- a/core/java/android/view/accessibility/AccessibilityNodeInfoCache.java
+++ b/core/java/android/view/accessibility/AccessibilityNodeInfoCache.java
@@ -86,7 +86,9 @@
                     refreshCachedNode(event.getSourceNodeId());
                 } break;
                 case AccessibilityEvent.TYPE_VIEW_SCROLLED: {
-                    clearSubTreeLocked(event.getSourceNodeId());
+                    synchronized (mLock) {
+                        clearSubTreeLocked(event.getSourceNodeId());
+                    }
                 } break;
                 case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: {
                     synchronized (mLock) {
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index 2cbe0e2..5bc39f15 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -670,7 +670,6 @@
      */
     @Deprecated
     public static void enablePlatformNotifications() {
-        checkThread();
         getFactory().getStatics().setPlatformNotificationsEnabled(true);
     }
 
@@ -683,7 +682,6 @@
      */
     @Deprecated
     public static void disablePlatformNotifications() {
-        checkThread();
         getFactory().getStatics().setPlatformNotificationsEnabled(false);
     }
 
@@ -1691,7 +1689,6 @@
      * @param enabled whether to enable web contents debugging
      */
     public static void setWebContentsDebuggingEnabled(boolean enabled) {
-        checkThread();
         getFactory().getStatics().setWebContentsDebuggingEnabled(enabled);
     }
 
@@ -1704,7 +1701,6 @@
      */
     @Deprecated
     public static synchronized PluginList getPluginList() {
-        checkThread();
         return new PluginList();
     }
 
@@ -2058,13 +2054,18 @@
         return WebViewFactory.getProvider();
     }
 
-    private static void checkThread() {
-        if (Looper.myLooper() != Looper.getMainLooper()) {
+    private final Looper mWebViewThread = Looper.myLooper();
+
+    private void checkThread() {
+        // Ignore mWebViewThread == null because this can be called during in the super class
+        // constructor, before this class's own constructor has even started.
+        if (mWebViewThread != null && Looper.myLooper() != mWebViewThread) {
             Throwable throwable = new Throwable(
-                    "Warning: A WebView method was called on thread '" +
+                    "A WebView method was called on thread '" +
                     Thread.currentThread().getName() + "'. " +
-                    "All WebView methods must be called on the UI thread. " +
-                    "Future versions of WebView may not support use on other threads.");
+                    "All WebView methods must be called on the same thread. " +
+                    "(Expected Looper " + mWebViewThread + " called on " + Looper.myLooper() +
+                    ", FYI main Looper is " + Looper.getMainLooper() + ")");
             Log.w(LOGTAG, Log.getStackTraceString(throwable));
             StrictMode.onWebViewMethodCalledOnWrongThread(throwable);
 
diff --git a/core/java/com/android/internal/inputmethod/InputMethodRoot.java b/core/java/com/android/internal/inputmethod/InputMethodRoot.java
new file mode 100644
index 0000000..f070a58
--- /dev/null
+++ b/core/java/com/android/internal/inputmethod/InputMethodRoot.java
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+package com.android.internal.inputmethod;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.util.AttributeSet;
+import android.widget.LinearLayout;
+
+public class InputMethodRoot extends LinearLayout {
+    private final Rect mGuardRect = new Rect();
+    private final Paint mGuardPaint = new Paint();
+
+    public InputMethodRoot(Context context) {
+        this(context, null);
+    }
+
+    public InputMethodRoot(Context context, AttributeSet attrs) {
+        this(context, attrs, 0);
+    }
+
+    public InputMethodRoot(Context context, AttributeSet attrs, int defStyle) {
+        super(context, attrs);
+        setWillNotDraw(false);
+        mGuardPaint.setColor(context.getResources()
+                .getColor(com.android.internal.R.color.input_method_navigation_guard));
+    }
+
+    @Override
+    protected boolean fitSystemWindows(Rect insets) {
+        setPadding(0, 0, 0, insets.bottom);
+        return true;
+    }
+
+    @Override
+    protected void onDraw(Canvas canvas) {
+        super.onDraw(canvas);
+
+        // draw navigation bar guard
+        final int w = getMeasuredWidth();
+        final int h = getMeasuredHeight();
+        mGuardRect.set(0, h - getPaddingBottom(), w, h);
+        canvas.drawRect(mGuardRect, mGuardPaint);
+    }
+}
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 15e1d0f..768fefc 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -773,7 +773,8 @@
         android:description="@string/permdesc_bluetoothAdmin"
         android:label="@string/permlab_bluetoothAdmin" />
 
-    <!-- Allows applications to pair bluetooth devices without user interaction -->
+    <!-- Allows applications to pair bluetooth devices without user interaction.
+         This is not available to third party applications. -->
     <permission android:name="android.permission.BLUETOOTH_PRIVILEGED"
         android:permissionGroup="android.permission-group.BLUETOOTH_NETWORK"
         android:protectionLevel="system|signature"
@@ -1110,7 +1111,8 @@
         android:description="@string/permdesc_use_sip"
         android:label="@string/permlab_use_sip" />
 
-    <!-- Allows an application to request CallHandlerService implementations. -->
+    <!-- Allows an application to request CallHandlerService implementations.
+         @hide -->
     <permission android:name="android.permission.BIND_CALL_SERVICE"
         android:permissionGroup="android.permission-group.PHONE_CALLS"
         android:protectionLevel="system|signature"
@@ -1956,13 +1958,15 @@
 
     <!-- Must be required by a {@link android.nfc.cardemulation.HostApduService}
          or {@link android.nfc.cardemulation.OffHostApduService} to ensure that only
-         the system can bind to it. -->
+         the system can bind to it.
+         @hide -->
     <permission android:name="android.permission.BIND_NFC_SERVICE"
         android:label="@string/permlab_bindNfcService"
         android:description="@string/permdesc_bindNfcService"
         android:protectionLevel="signature" />
 
-    <!-- Must be required by the PrintSpooler to ensure that only the system can bind to it. -->
+    <!-- Must be required by the PrintSpooler to ensure that only the system can bind to it.
+         @hide -->
     <permission android:name="android.permission.BIND_PRINT_SPOOLER_SERVICE"
         android:label="@string/permlab_bindPrintSpoolerService"
         android:description="@string/permdesc_bindPrintSpoolerService"
@@ -1997,7 +2001,8 @@
         android:protectionLevel="signature" />
 
     <!-- Required to add or remove another application as a device admin.
-         <p/>Not for use by third-party applications. -->
+         <p>Not for use by third-party applications.
+         @hide -->
     <permission android:name="android.permission.MANAGE_DEVICE_ADMINS"
         android:label="@string/permlab_manageDeviceAdmins"
         android:description="@string/permdesc_manageDeviceAdmins"
diff --git a/core/res/res/layout/input_method.xml b/core/res/res/layout/input_method.xml
index f80d628..23d7189 100644
--- a/core/res/res/layout/input_method.xml
+++ b/core/res/res/layout/input_method.xml
@@ -18,7 +18,7 @@
 */
 -->
 
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+<com.android.internal.inputmethod.InputMethodRoot xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/parentPanel"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
@@ -52,4 +52,4 @@
         android:layout_height="wrap_content"
         android:visibility="gone">
     </FrameLayout>
-</LinearLayout>
+</com.android.internal.inputmethod.InputMethodRoot>
diff --git a/core/res/res/values/colors.xml b/core/res/res/values/colors.xml
index 81ee3af..28e7af7 100644
--- a/core/res/res/values/colors.xml
+++ b/core/res/res/values/colors.xml
@@ -78,6 +78,7 @@
 
     <drawable name="input_method_fullscreen_background">#fff9f9f9</drawable>
     <drawable name="input_method_fullscreen_background_holo">@drawable/screen_background_holo_dark</drawable>
+    <color name="input_method_navigation_guard">#ff000000</color>
 
     <!-- For date picker widget -->
     <drawable name="selected_day_background">#ff0092f4</drawable>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index ad9144c..edfdcc2 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -1441,6 +1441,7 @@
   <java-symbol type="bool" name="config_wimaxEnabled" />
   <java-symbol type="bool" name="show_ongoing_ime_switcher" />
   <java-symbol type="color" name="config_defaultNotificationColor" />
+  <java-symbol type="color" name="input_method_navigation_guard" />
   <java-symbol type="drawable" name="ic_notification_ime_default" />
   <java-symbol type="drawable" name="ic_notify_wifidisplay" />
   <java-symbol type="drawable" name="ic_menu_refresh" />
diff --git a/docs/html/training/basics/fragments/fragment-ui.jd b/docs/html/training/basics/fragments/fragment-ui.jd
index db3119b..14469bf 100644
--- a/docs/html/training/basics/fragments/fragment-ui.jd
+++ b/docs/html/training/basics/fragments/fragment-ui.jd
@@ -122,11 +122,11 @@
                 return;
             }
 
-            // Create an instance of ExampleFragment
+            // Create a new Fragment to be placed in the activity layout
             HeadlinesFragment firstFragment = new HeadlinesFragment();
             
-            // In case this activity was started with special instructions from an Intent,
-            // pass the Intent's extras to the fragment as arguments
+            // In case this activity was started with special instructions from an
+            // Intent, pass the Intent's extras to the fragment as arguments
             firstFragment.setArguments(getIntent().getExtras());
             
             // Add the fragment to the 'fragment_container' FrameLayout
diff --git a/docs/html/training/beam-files/index.jd b/docs/html/training/beam-files/index.jd
new file mode 100644
index 0000000..7155092
--- /dev/null
+++ b/docs/html/training/beam-files/index.jd
@@ -0,0 +1,61 @@
+page.title=Sharing Files with NFC
+
+trainingnavtop=true
+startpage=true
+
+
+@jd:body
+
+<div id="tb-wrapper">
+<div id="tb">
+
+<h2>Dependencies and prerequisites</h2>
+<ul>
+  <li>Android 4.1 (API Level 16) or higher</li>
+  <li>At least two NFC-enabled Android devices (NFC is not supported in the emulator)</li>
+</ul>
+
+<h2>You should also read</h2>
+<ul>
+  <li>
+    <a href="{@docRoot}guide/topics/data/data-storage.html#filesExternal"
+    >Using the External Storage</a>
+  </li>
+</ul>
+
+</div>
+</div>
+
+<p>
+    Android allows you to transfer large files between devices using the Android Beam file transfer
+    feature. This feature has a simple API and allows users to start the transfer process by simply
+    touching devices. In response, Android Beam file transfer automatically copies files from one
+    device to the other and notifies the user when it's finished.
+</p>
+<p>
+    While the Android Beam file transfer API handles large amounts of data, the Android Beam NDEF
+    transfer API introduced in Android 4.0 (API level 14) handles small amounts of data such as
+    URIs or other small messages. In addition, Android Beam is only one of the features available
+    in the Android NFC framework, which allows you to read NDEF messages from NFC tags. To learn
+    more about Android Beam, see the topic
+    <a href="{@docRoot}guide/topics/connectivity/nfc/nfc.html#p2p"
+    >Beaming NDEF Messages to Other Devices</a>. To learn more about the NFC framework, see the
+    <a href="{@docRoot}guide/topics/connectivity/nfc/index.html"
+    >Near Field Communication</a> API guide.
+</p>
+<h2>Lessons</h2>
+<dl>
+    <dt>
+        <b><a href="send-files.html">Sending Files to Another Device</a></b>
+    </dt>
+    <dd>Learn how to set up your app to send files to another device.</dd>
+
+    <dt>
+        <b><a href="receive-files.html">Receiving Files from Another Device</a></b>
+    </dt>
+    <dd>
+        Learn how to set up your app to receive files sent by another device.
+    </dd>
+</dl>
+
+
diff --git a/docs/html/training/beam-files/receive-files.jd b/docs/html/training/beam-files/receive-files.jd
new file mode 100644
index 0000000..0613612
--- /dev/null
+++ b/docs/html/training/beam-files/receive-files.jd
@@ -0,0 +1,313 @@
+page.title=Receiving Files from Another Device
+
+trainingnavtop=true
+@jd:body
+
+<div id="tb-wrapper">
+<div id="tb">
+
+<h2>This lesson teaches you to</h2>
+<ol>
+    <li><a href="#IntentFilter">Respond to a Request to Display Data</a></li>
+    <li><a href="#RequestPermissions">Request File Permissions</a></li>
+    <li><a href="#GetFilePath">Get the Directory for Copied Files</a></li>
+</ol>
+<h2>You should also read</h2>
+<ul>
+    <li>
+        <a href="{@docRoot}guide/topics/providers/content-provider-basics.html#ContentURIs"
+        >Content URIs</a>
+    </li>
+    <li>
+        <a href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filters</a>
+    </li>
+    <li>
+        <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Notifications</a>
+    </li>
+    <li>
+        <a href="{@docRoot}guide/topics/data/data-storage.html#filesExternal"
+        >Using the External Storage</a>
+    </li>
+</ul>
+
+</div>
+</div>
+
+<p>
+    Android Beam file transfer copies files to a special directory on the receiving device. It also
+    scans the copied files using the Android Media Scanner and adds entries for media files to
+    the {@link android.provider.MediaStore} provider. This lesson shows you how to respond when the
+    file copy is complete, and how to locate the copied files on the receiving device.
+</p>
+<h2 id="IntentFilter">Respond to a Request to Display Data</h2>
+<p>
+    When Android Beam file transfer finishes copying files to the receiving device, it posts a
+    notification containing an {@link android.content.Intent} with the action
+    {@link android.content.Intent#ACTION_VIEW ACTION_VIEW}, the MIME type of the first file that
+    was transferred, and a URI that points to the first file. When the user clicks the notification,
+    this intent is sent out to the system. To have your app respond to this intent, add an
+    <code><a href="{@docRoot}guide/topics/manifest/intent-filter-element.html"
+    >&lt;intent-filter&gt;</a></code> element for the
+    <code><a href="{@docRoot}guide/topics/manifest/activity-element.html"
+    >&lt;activity&gt;</a></code> element of the {@link android.app.Activity} that should respond.
+    In the <code><a href="{@docRoot}guide/topics/manifest/intent-filter-element.html"
+    >&lt;intent-filter&gt;</a></code> element, add the following child elements:
+</p>
+<dl>
+    <dt>
+        <code><a href="{@docRoot}guide/topics/manifest/action-element.html"
+        >&lt;action android:name="android.intent.action.VIEW" /&gt;</a></code>
+    </dt>
+    <dd>
+        Matches the {@link android.content.Intent#ACTION_VIEW ACTION_VIEW} intent sent from the
+        notification.
+    </dd>
+    <dt>
+        <code><a href="{@docRoot}guide/topics/manifest/category-element.html"
+        >&lt;category android:name="android.intent.category.CATEGORY_DEFAULT" /&gt;</a></code>
+    </dt>
+    <dd>
+        Matches an {@link android.content.Intent} that doesn't have an explicit category.
+    </dd>
+    <dt>
+        <code><a href="{@docRoot}guide/topics/manifest/data-element.html"
+        >&lt;data android:mimeType="<i>mime-type</i>" /&gt;</a></code>
+    </dt>
+    <dd>
+        Matches a MIME type. Specify only those MIME types that your app can handle.
+    </dd>
+</dl>
+<p>
+    For example, the following snippet shows you how to add an intent filter that
+    triggers the activity <code>com.example.android.nfctransfer.ViewActivity</code>:
+</p>
+<pre>
+    &lt;activity
+        android:name="com.example.android.nfctransfer.ViewActivity"
+        android:label="Android Beam Viewer" &gt;
+        ...
+        &lt;intent-filter&gt;
+            &lt;action android:name="android.intent.action.VIEW"/&gt;
+            &lt;category android:name="android.intent.category.DEFAULT"/&gt;
+            ...
+        &lt;/intent-filter&gt;
+    &lt;/activity&gt;
+</pre>
+<p class="note">
+    <strong>Note:</strong> Android Beam file transfer is not the only source of an
+    {@link android.content.Intent#ACTION_VIEW ACTION_VIEW} intent. Other apps on the receiving
+    device can also send an {@link android.content.Intent} with this action.
+    Handling this situation is discussed in the section <a href="#GetDirectory"
+    >Get the directory from a content URI</a>.
+</p>
+<h2 id="RequestPermissions">Request File Permissions</h2>
+<p>
+    To read files that Android Beam file transfer copies to the device, request the permission
+    {@link android.Manifest.permission#READ_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE}. For example:
+</p>
+<pre>
+    &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt;</pre>
+<p>
+    If you want to copy transferred files to your app's own storage area, request the permission
+    {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE WRITE_EXTERNAL_STORAGE} instead.
+    {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE WRITE_EXTERNAL_STORAGE} includes
+    {@link android.Manifest.permission#READ_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE}.
+</p>
+<p class="note">
+    <strong>Note:</strong> As of Android 4.2.2 (API level 17), the permission
+    {@link android.Manifest.permission#READ_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE} is
+    only enforced if the user chooses to do so. Future versions of the platform may require this
+    permission in all cases. To ensure forward compatibility, request the permission now, before it
+    becomes required.
+</p>
+<p>
+    Since your app has control over its internal storage area, you don't need to request
+    write permission to copy a transferred file to your internal storage area.
+</p>
+<h2 id="GetFilePath">Get the Directory for Copied Files</h2>
+<p>
+    Android Beam file transfer copies all the files in a single transfer to one directory
+    on the receiving device. The URI in the content {@link android.content.Intent} sent by the
+    Android Beam file transfer notification points to the first transferred file. However, your
+    app may also receive an {@link android.content.Intent#ACTION_VIEW ACTION_VIEW} intent from a
+    source other than Android Beam file transfer. To determine how you should handle the incoming
+    {@link android.content.Intent}, you need to examine its scheme and authority.
+</p>
+<p>
+    To get the scheme for the URI, call {@link android.net.Uri#getScheme() Uri.getScheme()}. The
+    following code snippet shows you how to determine the scheme and handle the URI accordingly:
+</p>
+<pre>
+public class MainActivity extends Activity {
+    ...
+    // A File object containing the path to the transferred files
+    private File mParentPath;
+    // Incoming Intent
+    private Intent mIntent;
+    ...
+    /*
+     * Called from onNewIntent() for a SINGLE_TOP Activity
+     * or onCreate() for a new Activity. For onNewIntent(),
+     * remember to call setIntent() to store the most
+     * current Intent
+     *
+     */
+    private void handleViewIntent() {
+        ...
+        // Get the Intent action
+        mIntent = getIntent();
+        String action = mIntent.getAction();
+        /*
+         * For ACTION_VIEW, the Activity is being asked to display data.
+         * Get the URI.
+         */
+        if (TextUtils.equals(action, Intent.ACTION_VIEW)) {
+            // Get the URI from the Intent
+            Uri beamUri = mIntent.getData();
+            /*
+             * Test for the type of URI, by getting its scheme value
+             */
+            if (TextUtils.equals(beamUri.getScheme(), "file")) {
+                mParentPath = handleFileUri(beamUri);
+            } else if (TextUtils.equals(
+                    beamUri.getScheme(), "content")) {
+                mParentPath = handleContentUri(beamUri);
+            }
+        }
+        ...
+    }
+    ...
+}
+</pre>
+<h3>Get the directory from a file URI</h3>
+<p>
+    If the incoming {@link android.content.Intent} contains a file URI, the URI contains the
+    absolute file name of a file, including the full directory path and file name. For Android Beam
+    file transfer, the directory path points to the location of the other transferred files, if
+    any. To get the directory path, get the path part of the URI, which contains all of the URI
+    except the <code>file:</code> prefix. Create a {@link java.io.File} from the path part, then
+    get the parent path of the {@link java.io.File}:
+</p>
+<pre>
+    ...
+    public String handleFileUri(Uri beamUri) {
+        // Get the path part of the URI
+        String fileName = beamUri.getPath();
+        // Create a File object for this filename
+        File copiedFile = new File(fileName);
+        // Get a string containing the file's parent directory
+        return copiedFile.getParent();
+    }
+    ...
+</pre>
+
+<h3 id="GetDirectory">Get the directory from a content URI</h3>
+<p>
+    If the incoming {@link android.content.Intent} contains a content URI, the URI may point to a
+    directory and file name stored in the {@link android.provider.MediaStore} content provider. You
+    can detect a content URI for {@link android.provider.MediaStore} by testing the URI's
+    authority value. A content URI for {@link android.provider.MediaStore} may come from
+    Android Beam file transfer or from another app, but in both cases you can retrieve a directory
+    and file name for the content URI.
+</p>
+<p>
+    You can also receive an incoming {@link android.content.Intent#ACTION_VIEW ACTION_VIEW}
+    intent containing a content URI for a content provider other than
+    {@link android.provider.MediaStore}. In this case, the content URI doesn't contain the
+    {@link android.provider.MediaStore} authority value, and the content URI usually doesn't point
+    to a directory.
+</p>
+<p class="note">
+    <strong>Note:</strong> For Android Beam file transfer, you receive a content URI in the
+    {@link android.content.Intent#ACTION_VIEW ACTION_VIEW} intent if the first incoming file
+    has a MIME type of "audio/*", "image/*", or "video/*", indicating that the file is media-
+    related. Android Beam file transfer indexes the media files it transfers by running Media
+    Scanner on the directory where it stores transferred files. Media Scanner writes its results
+    to the {@link android.provider.MediaStore} content provider, then it passes a content URI
+    for the first file back to Android Beam file transfer. This content URI is the one you
+    receive in the notification {@link android.content.Intent}. To get the directory
+    of the first file, you retrieve it from {@link android.provider.MediaStore} using the content
+    URI.
+</p>
+<h3>Determine the content provider</h3>
+<p>
+    To determine if you can retrieve a file directory from the content URI, determine the
+    the content provider associated with the URI by calling
+    {@link android.net.Uri#getAuthority Uri.getAuthority()} to get the URI's authority. The
+    result has two possible values:
+</p>
+<dl>
+    <dt>
+        {@link android.provider.MediaStore#AUTHORITY MediaStore.AUTHORITY}
+    </dt>
+    <dd>
+        The URI is for a file or files tracked by {@link android.provider.MediaStore}. Retrieve the
+        full file name from {@link android.provider.MediaStore}, and get directory from the file
+        name.
+    </dd>
+    <dt>
+        Any other authority value
+    </dt>
+    <dd>
+        A content URI from another content provider. Display the data associated with the content
+        URI, but don't get the file directory.
+    </dd>
+</dl>
+<p>
+    To get the directory for a {@link android.provider.MediaStore} content URI,
+    run a query that specifies the incoming content URI for the {@link android.net.Uri} argument and
+    the column {@link android.provider.MediaStore.MediaColumns#DATA MediaColumns.DATA} for the
+    projection. The returned {@link android.database.Cursor} contains the full path and name for
+    the file represented by the URI. This path also contains all the other files that Android Beam
+    file transfer just copied to the device.
+</p>
+<p>
+    The following snippet shows you how to test the authority of the content URI and retrieve the
+    the path and file name for the transferred file:
+</p>
+<pre>
+    ...
+    public String handleContentUri(Uri beamUri) {
+        // Position of the filename in the query Cursor
+        int filenameIndex;
+        // File object for the filename
+        File copiedFile;
+        // The filename stored in MediaStore
+        String fileName;
+        // Test the authority of the URI
+        if (!TextUtils.equals(beamUri.getAuthority(), MediaStore.AUTHORITY)) {
+            /*
+             * Handle content URIs for other content providers
+             */
+        // For a MediaStore content URI
+        } else {
+            // Get the column that contains the file name
+            String[] projection = { MediaStore.MediaColumns.DATA };
+            Cursor pathCursor =
+                    getContentResolver().query(beamUri, projection,
+                    null, null, null);
+            // Check for a valid cursor
+            if (pathCursor != null &amp;&amp;
+                    pathCursor.moveToFirst()) {
+                // Get the column index in the Cursor
+                filenameIndex = pathCursor.getColumnIndex(
+                        MediaStore.MediaColumns.DATA);
+                // Get the full file name including path
+                fileName = pathCursor.getString(filenameIndex);
+                // Create a File object for the filename
+                copiedFile = new File(fileName);
+                // Return the parent directory of the file
+                return new File(copiedFile.getParent());
+             } else {
+                // The query didn't work; return null
+                return null;
+             }
+        }
+    }
+    ...
+</pre>
+<p>
+    To learn more about retrieving data from a content provider, see the section
+    <a href="{@docRoot}guide/topics/providers/content-provider-basics.html#SimpleQuery"
+    >Retrieving Data from the Provider</a>.
+</p>
diff --git a/docs/html/training/beam-files/send-files.jd b/docs/html/training/beam-files/send-files.jd
new file mode 100644
index 0000000..917b87f
--- /dev/null
+++ b/docs/html/training/beam-files/send-files.jd
@@ -0,0 +1,294 @@
+page.title=Sending Files to Another Device
+
+trainingnavtop=true
+@jd:body
+
+
+<div id="tb-wrapper">
+<div id="tb">
+
+<!-- table of contents -->
+<h2>This lesson teaches you to</h2>
+<ol>
+  <li><a href="#DeclareFeatures">Declare Features in the Manifest</a>
+  <li><a href="#TestAndroidBeam">Test for Android Beam File Transfer Support</a></li>
+  <li>
+    <a href="#CreateCallback"
+    >Create a Callback Method That Provides Files</a>
+  </li>
+  <li><a href="#ProvideUri">Specify the Files to Send</a>
+</ol>
+
+<h2>You should also read</h2>
+<ul>
+    <li><a href="{@docRoot}guide/topics/data/data-storage.html">Storage Options</a></li>
+</ul>
+
+</div>
+</div>
+<p>
+    This lesson shows you how to design your app to send large files to another device using
+    Android Beam file transfer. To send files, you request permission to use NFC and external
+    storage, test to ensure your device supports NFC, and provide URIs to Android Beam file
+    transfer.
+</p>
+<p>
+    The Android Beam file transfer feature has the following requirements:
+</p>
+<ol>
+    <li>
+        Android Beam file transfer for large files is only available in Android 4.1 (API level 16)
+        and higher.
+    </li>
+    <li>
+        Files you want to transfer must reside in external storage. To learn more about using
+        external storage, read <a href="{@docRoot}guide/topics/data/data-storage.html#filesExternal"
+        >Using the External Storage</a>.
+    </li>
+    <li>
+        Each file you want to transfer must be world-readable. You can set this permission by
+        calling the method {@link java.io.File#setReadable File.setReadable(true,false)}.
+    </li>
+    <li>
+        You must provide a file URI for the files you want to transfer. Android Beam file transfer
+        is unable to handle content URIs generated by
+        {@link android.support.v4.content.FileProvider#getUriForFile FileProvider.getUriForFile}.
+    </li>
+</ol>
+
+<h2 id="DeclareFeatures">Declare Features in the Manifest</h2>
+<p>
+    First, edit your app manifest to declare the permissions and features your app needs.
+</p>
+<h3>Request Permissions</h3>
+<p>
+    To allow your app to use Android Beam file transfer to send files from external storage using
+    NFC, you must request the following permissions in your app manifest:
+</p>
+<dl>
+    <dt>
+        {@link android.Manifest.permission#NFC NFC}
+    </dt>
+    <dd>
+        Allows your app to send data over NFC. To specify this permission, add the following element
+        as a child of the <code><a href="{@docRoot}guide/topics/manifest/manifest-element.html"
+        >&lt;manifest&gt;</a></code> element:
+<pre>
+    &lt;uses-permission android:name="android.permission.NFC" /&gt;
+</pre>
+    </dd>
+    <dt>
+        {@link android.Manifest.permission#READ_EXTERNAL_STORAGE READ_EXTERNAL_STORAGE}
+    </dt>
+    <dd>
+        Allows your app to read from external storage. To specify this permission, add the following
+        element as a child of the
+        <code><a href="{@docRoot}guide/topics/manifest/manifest-element.html"
+        >&lt;manifest&gt;</a></code> element:
+<pre>
+    &lt;uses-permission
+            android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt;
+</pre>
+    <p class="note">
+        <strong>Note:</strong> As of Android 4.2.2 (API level 17), this permission is not
+        enforced. Future versions of the platform may require it for apps that want to read from
+        external storage. To ensure forward compatibility, request the permission now, before it
+        becomes required.
+    </p>
+    </dd>
+</dl>
+<h3>Specify the NFC feature</h3>
+<p>
+    Specify that your app uses NFC, by adding a
+    <code><a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"
+    >&lt;uses-feature&gt;</a></code> element as a child
+    of the <code><a href="{@docRoot}guide/topics/manifest/manifest-element.html"
+    >&lt;manifest&gt;</a></code> element. Set the <code>android:required</code> attribute to
+    <code>true</code> to indicate that your app won't function unless NFC is present.
+</p>
+<p>
+    The following snippet shows you how to specify the
+    <code><a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"
+    >&lt;uses-feature&gt;</a></code> element:
+</p>
+<pre>
+&lt;uses-feature
+    android:name="android.hardware.nfc"
+    android:required="true" /&gt;</pre>
+<p>
+    Note that if your app only uses NFC as an option, but still functions if NFC isn't present, you
+    should set <code>android:required</code> to <code>false</code>, and test for NFC in code.
+</p>
+<h3>Specify Android Beam file transfer</h3>
+<p>
+    Since Android Beam file transfer is only available in Android 4.1 (API level 16) and later,
+    if your app depends on Android Beam file transfer for a key part of its functionality you must
+    specify the <code><a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"
+    >&lt;uses-sdk&gt;</a></code> element with the
+    <code><a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min"
+    >android:minSdkVersion</a>="16"</code> attribute. Otherwise, you can set
+    <code><a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min"
+    >android:minSdkVersion</a></code> to another value as necessary, and test for the platform
+    version in code, as described in the following section.
+</p>
+<h2 id="TestAndroidBeam">Test for Android Beam File Transfer Support</h2>
+<p>
+    To specify in your app manifest that NFC is optional, you use the following element:
+</p>
+<pre>
+&lt;uses-feature android:name="android.hardware.nfc" android:required="false" /&gt;</pre>
+<p>
+    If you set the attribute
+    <code><a href="guide/topics/manifest/uses-feature-element.html#required"
+    >android:required</a>="false"</code>, you must test for NFC support and Android Beam file
+    transfer support in code.
+</p>
+<p>
+    To test for Android Beam file transfer support in code, start by testing that the device
+    supports NFC by calling {@link android.content.pm.PackageManager#hasSystemFeature
+    PackageManager.hasSystemFeature()} with the argument
+    {@link android.content.pm.PackageManager#FEATURE_NFC FEATURE_NFC}. Next, check that the Android
+    version supports Android Beam file transfer by testing the value of
+    {@link android.os.Build.VERSION#SDK_INT}. If Android Beam file transfer is supported, get an
+    instance of the NFC controller, which allows you to communicate with the NFC hardware.
+    For example:
+</p>
+<pre>
+public class MainActivity extends Activity {
+    ...
+    NfcAdapter mNfcAdapter;
+    // Flag to indicate that Android Beam is available
+    boolean mAndroidBeamAvailable  = false;
+    ...
+    &#64;Override
+    protected void onCreate(Bundle savedInstanceState) {
+        ...
+        // NFC isn't available on the device
+        if (!PackageManager.hasSystemFeature(PackageManager.FEATURE_NFC)) {
+            /*
+             * Disable NFC features here.
+             * For example, disable menu items or buttons that activate
+             * NFC-related features
+             */
+            ...
+        // Android Beam file transfer isn't supported
+        } else if (Build.VERSION.SDK_INT &lt;
+                Build.VERSION_CODES.JELLY_BEAN_MR1) {
+            // If Android Beam isn't available, don't continue.
+            mAndroidBeamAvailable = false;
+            /*
+             * Disable Android Beam file transfer features here.
+             */
+            ...
+        // Android Beam file transfer is available, continue
+        } else {
+        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
+        ...
+        }
+    }
+    ...
+}</pre>
+
+<h2 id="CreateCallback">
+    Create a Callback Method that Provides Files
+</h2>
+<p>
+    Once you've verified that the device supports Android Beam file transfer, add a callback
+    method that the system invokes when Android Beam file transfer detects that the user wants
+    to send files to another NFC-enabled device. In this callback method, return an array of
+    {@link android.net.Uri} objects. Android Beam file transfer copies the files represented by
+    these URIs to the receiving device.
+</p>
+<p>
+    To add the callback method, implement the
+    {@link android.nfc.NfcAdapter.CreateBeamUrisCallback} interface and its method
+    {@link android.nfc.NfcAdapter.CreateBeamUrisCallback#createBeamUris createBeamUris()}. The
+    following snippet shows you how to do this:
+</p>
+<pre>
+public class MainActivity extends Activity {
+    ...
+    // List of URIs to provide to Android Beam
+    private Uri[] mFileUris = new Uri[10];
+    ...
+    /**
+     * Callback that Android Beam file transfer calls to get
+     * files to share
+     */
+    private class FileUriCallback implements
+            NfcAdapter.CreateBeamUrisCallback {
+        public FileUriCallback() {
+        }
+        /**
+         * Create content URIs as needed to share with another device
+         */
+        &#64;Override
+        public Uri[] createBeamUris(NfcEvent event) {
+            return mFileUris;
+        }
+    }
+    ...
+}
+</pre>
+<p>
+    Once you've implemented the interface, provide the callback to Android Beam file transfer by
+    calling {@link android.nfc.NfcAdapter#setBeamPushUrisCallback setBeamPushUrisCallback()}. The
+    following snippet shows you how to do this:
+</p>
+<pre>
+public class MainActivity extends Activity {
+    ...
+    // Instance that returns available files from this app
+    private FileUriCallback mFileUriCallback;
+    ...
+    &#64;Override
+    protected void onCreate(Bundle savedInstanceState) {
+        ...
+        // Android Beam file transfer is available, continue
+        ...
+        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
+        /*
+         * Instantiate a new FileUriCallback to handle requests for
+         * URIs
+         */
+        mFileUriCallback = new FileUriCallback();
+        // Set the dynamic callback for URI requests.
+        mNfcAdapter.setBeamPushUrisCallback(mFileUriCallback,this);
+        ...
+    }
+    ...
+}
+</pre>
+<p class="note">
+    <strong>Note:</strong> You can also provide the array of {@link android.net.Uri} objects
+    directly to the NFC framework through your app's {@link android.nfc.NfcAdapter} instance. Choose
+    this approach if you can define the URIs to transfer before the NFC touch event occurs.
+    To learn more about this approach, see {@link android.nfc.NfcAdapter#setBeamPushUris
+    NfcAdapter.setBeamPushUris()}.
+</p>
+<h2 id="ProvideUri">Specify the Files to Send</h2>
+<p>
+    To transfer one or more files to another NFC-enabled device, get a file URI (a URI with a
+    <code>file</code> scheme) for each file and then add the URI to an array of
+    {@link android.net.Uri} objects. To transfer a file, you must also have permanent read access
+    for the file. For example, the following snippet shows you how to get a file URI from a file
+    name and then add the URI to the array:
+</p>
+<pre>
+        /*
+         * Create a list of URIs, get a File,
+         * and set its permissions
+         */
+        private Uri[] mFileUris = new Uri[10];
+        String transferFile = "transferimage.jpg";
+        File extDir = getExternalFilesDir(null);
+        File requestFile = new File(extDir, transferFile);
+        requestFile.setReadable(true, false);
+        // Get a URI for the File and add it to the list of URIs
+        fileUri = Uri.fromFile(requestFile);
+        if (fileUri != null) {
+            mFileUris[0] = fileUri;
+        } else {
+            Log.e("My Activity", "No File URI available for file.");
+        }
+</pre>
diff --git a/docs/html/training/training_toc.cs b/docs/html/training/training_toc.cs
index 77ac235..27e7004 100644
--- a/docs/html/training/training_toc.cs
+++ b/docs/html/training/training_toc.cs
@@ -423,7 +423,22 @@
           </li>
         </ul>
       </li>
-
+      <li class="nav-section">
+        <div class="nav-section-header">
+          <a href="<?cs var:toroot ?>training/beam-files/index.html"
+             description=
+             "How to transfer files between devices using the NFC Android Beam feature."
+             >Sharing Files with NFC</a>
+        </div>
+        <ul>
+            <li>
+                <a href="<?cs var:toroot ?>training/beam-files/send-files.html"
+                >Sending Files to Another Device</a>
+            </li>
+            <li><a href="<?cs var:toroot ?>training/beam-files/receive-files.html"
+            >Receiving Files from Another Device</a></li>
+        </ul>
+       </li>
        <li class="nav-section">
         <div class="nav-section-header">
           <a href="<?cs var:toroot ?>training/basics/network-ops/index.html"
@@ -498,7 +513,7 @@
            "How to design a robust conflict resolution strategy for apps that save data to the cloud."
            >Resolving Cloud Save Conflicts
           </a>
-          </li>
+        </li>
       </li>
       <li class="nav-section">
         <div class="nav-section-header">
@@ -1181,7 +1196,6 @@
       </a>
     </div>
     <ul>
-
       <li>
         <a href="<?cs var:toroot ?>training/articles/security-tips.html"
            description=
diff --git a/packages/DocumentsUI/src/com/android/documentsui/DocumentsActivity.java b/packages/DocumentsUI/src/com/android/documentsui/DocumentsActivity.java
index 7660779..d675e8d 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/DocumentsActivity.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/DocumentsActivity.java
@@ -292,7 +292,7 @@
         @Override
         protected Void doInBackground(Void... params) {
             // Restore last stack for calling package
-            final String packageName = getCallingPackage();
+            final String packageName = getCallingPackageMaybeExtra();
             final Cursor cursor = getContentResolver()
                     .query(RecentsProvider.buildResume(packageName), null, null, null, null);
             try {
@@ -783,6 +783,11 @@
         return mState.stack.peek();
     }
 
+    private String getCallingPackageMaybeExtra() {
+        final String extra = getIntent().getStringExtra(DocumentsContract.EXTRA_PACKAGE_NAME);
+        return (extra != null) ? extra : getCallingPackage();
+    }
+
     public Executor getCurrentExecutor() {
         final DocumentInfo cwd = getCurrentDirectory();
         if (cwd != null && cwd.authority != null) {
@@ -921,7 +926,7 @@
         if (requestCode == CODE_FORWARD && resultCode != RESULT_CANCELED) {
 
             // Remember that we last picked via external app
-            final String packageName = getCallingPackage();
+            final String packageName = getCallingPackageMaybeExtra();
             final ContentValues values = new ContentValues();
             values.put(ResumeColumns.EXTERNAL, 1);
             getContentResolver().insert(RecentsProvider.buildResume(packageName), values);
@@ -1002,7 +1007,7 @@
         }
 
         // Remember location for next app launch
-        final String packageName = getCallingPackage();
+        final String packageName = getCallingPackageMaybeExtra();
         values.clear();
         values.put(ResumeColumns.STACK, rawStack);
         values.put(ResumeColumns.EXTERNAL, 0);
diff --git a/packages/DocumentsUI/src/com/android/documentsui/RootsCache.java b/packages/DocumentsUI/src/com/android/documentsui/RootsCache.java
index eb56765..b98e1ee 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/RootsCache.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/RootsCache.java
@@ -194,16 +194,6 @@
                 handleDocumentsProvider(info.providerInfo);
             }
 
-            // Pick up legacy providers
-            final List<ProviderInfo> legacyProviders = pm.queryContentProviders(
-                    null, -1, PackageManager.GET_META_DATA);
-            for (ProviderInfo info : legacyProviders) {
-                if (info.metaData != null && info.metaData.containsKey(
-                        DocumentsContract.META_DATA_DOCUMENT_PROVIDER)) {
-                    handleDocumentsProvider(info);
-                }
-            }
-
             final long delta = SystemClock.elapsedRealtime() - start;
             Log.d(TAG, "Update found " + mTaskRoots.size() + " roots in " + delta + "ms");
             synchronized (mLock) {
diff --git a/packages/Keyguard/src/com/android/keyguard/KeyguardViewManager.java b/packages/Keyguard/src/com/android/keyguard/KeyguardViewManager.java
index 65841805..58ca0b0 100644
--- a/packages/Keyguard/src/com/android/keyguard/KeyguardViewManager.java
+++ b/packages/Keyguard/src/com/android/keyguard/KeyguardViewManager.java
@@ -420,6 +420,7 @@
     public synchronized void onScreenTurnedOn(final IKeyguardShowCallback callback) {
         if (DEBUG) Log.d(TAG, "onScreenTurnedOn()");
         mScreenOn = true;
+        final IBinder token = mKeyguardHost == null ? null : mKeyguardHost.getWindowToken();
         if (mKeyguardView != null) {
             mKeyguardView.onScreenTurnedOn();
 
@@ -432,10 +433,6 @@
                     mKeyguardHost.post(new Runnable() {
                         @Override
                         public void run() {
-                            IBinder token = null;
-                            if (mKeyguardHost.getVisibility() == View.VISIBLE) {
-                                token = mKeyguardHost.getWindowToken();
-                            }
                             try {
                                 callback.onShown(token);
                             } catch (RemoteException e) {
@@ -445,7 +442,7 @@
                     });
                 } else {
                     try {
-                        callback.onShown(null);
+                        callback.onShown(token);
                     } catch (RemoteException e) {
                         Slog.w(TAG, "Exception calling onShown():", e);
                     }
@@ -453,7 +450,7 @@
             }
         } else if (callback != null) {
             try {
-                callback.onShown(null);
+                callback.onShown(token);
             } catch (RemoteException e) {
                 Slog.w(TAG, "Exception calling onShown():", e);
             }
diff --git a/packages/SystemUI/res/drawable-hdpi/bottom_divider_glow.png b/packages/SystemUI/res/drawable-hdpi/bottom_divider_glow.png
index e8cfc0f..d1948d6 100644
--- a/packages/SystemUI/res/drawable-hdpi/bottom_divider_glow.png
+++ b/packages/SystemUI/res/drawable-hdpi/bottom_divider_glow.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-hdpi/top_divider_glow.png b/packages/SystemUI/res/drawable-hdpi/top_divider_glow.png
index 89cd10e..a540efb1 100644
--- a/packages/SystemUI/res/drawable-hdpi/top_divider_glow.png
+++ b/packages/SystemUI/res/drawable-hdpi/top_divider_glow.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/bottom_divider_glow.png b/packages/SystemUI/res/drawable-mdpi/bottom_divider_glow.png
index 7d7868d..ba25f65 100644
--- a/packages/SystemUI/res/drawable-mdpi/bottom_divider_glow.png
+++ b/packages/SystemUI/res/drawable-mdpi/bottom_divider_glow.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/top_divider_glow.png b/packages/SystemUI/res/drawable-mdpi/top_divider_glow.png
index f93da09..53d85de 100644
--- a/packages/SystemUI/res/drawable-mdpi/top_divider_glow.png
+++ b/packages/SystemUI/res/drawable-mdpi/top_divider_glow.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xhdpi/bottom_divider_glow.png b/packages/SystemUI/res/drawable-xhdpi/bottom_divider_glow.png
index bbcea9e..0b012b4 100644
--- a/packages/SystemUI/res/drawable-xhdpi/bottom_divider_glow.png
+++ b/packages/SystemUI/res/drawable-xhdpi/bottom_divider_glow.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xhdpi/top_divider_glow.png b/packages/SystemUI/res/drawable-xhdpi/top_divider_glow.png
index 56b63d0..d4526c0 100644
--- a/packages/SystemUI/res/drawable-xhdpi/top_divider_glow.png
+++ b/packages/SystemUI/res/drawable-xhdpi/top_divider_glow.png
Binary files differ
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
index 932fe20..6a2bc5f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/BaseStatusBar.java
@@ -570,12 +570,14 @@
                  if (DEBUG) Log.d(TAG, "opening search panel");
                  if (mSearchPanelView != null && mSearchPanelView.isAssistantAvailable()) {
                      mSearchPanelView.show(true, true);
+                     onShowSearchPanel();
                  }
                  break;
              case MSG_CLOSE_SEARCH_PANEL:
                  if (DEBUG) Log.d(TAG, "closing search panel");
                  if (mSearchPanelView != null && mSearchPanelView.isShowing()) {
                      mSearchPanelView.show(false, true);
+                     onHideSearchPanel();
                  }
                  break;
             }
@@ -607,6 +609,12 @@
     protected void workAroundBadLayerDrawableOpacity(View v) {
     }
 
+    protected void onHideSearchPanel() {
+    }
+
+    protected void onShowSearchPanel() {
+    }
+
     public boolean inflateViews(NotificationData.Entry entry, ViewGroup parent) {
         int minHeight =
                 mContext.getResources().getDimensionPixelSize(R.dimen.notification_min_height);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
index 6e53363..d1c4109 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
@@ -37,10 +37,10 @@
 import android.view.MotionEvent;
 import android.view.Surface;
 import android.view.View;
-import android.view.View.OnClickListener;
 import android.view.ViewGroup;
 import android.view.WindowManager;
 import android.view.accessibility.AccessibilityManager;
+import android.view.accessibility.AccessibilityManager.TouchExplorationStateChangeListener;
 import android.widget.ImageView;
 import android.widget.LinearLayout;
 
@@ -89,26 +89,31 @@
     // used to disable the camera icon in navbar when disabled by DPM
     private boolean mCameraDisabledByDpm;
 
+    // simplified click handler to be used when device is in accessibility mode
+    private final OnClickListener mAccessibilityClickListener = new OnClickListener() {
+        @Override
+        public void onClick(View v) {
+            if (v.getId() == R.id.camera_button) {
+                KeyguardTouchDelegate.getInstance(getContext()).launchCamera();
+            } else if (v.getId() == R.id.search_light) {
+                KeyguardTouchDelegate.getInstance(getContext()).showAssistant();
+            }
+        }
+    };
+
     private final OnTouchListener mCameraTouchListener = new OnTouchListener() {
         @Override
         public boolean onTouch(View cameraButtonView, MotionEvent event) {
-            View searchLight = getSearchLight();
             switch (event.getAction()) {
                 case MotionEvent.ACTION_DOWN:
                     // disable search gesture while interacting with camera
                     mDelegateHelper.setDisabled(true);
-                    cameraButtonView.animate().alpha(0.0f).setDuration(CAMERA_BUTTON_FADE_DURATION);
-                    if (searchLight != null) {
-                        searchLight.animate().alpha(0.0f).setDuration(CAMERA_BUTTON_FADE_DURATION);
-                    }
+                    transitionCameraAndSearchButtonAlpha(0.0f);
                     break;
                 case MotionEvent.ACTION_UP:
                 case MotionEvent.ACTION_CANCEL:
                     mDelegateHelper.setDisabled(false);
-                    cameraButtonView.animate().alpha(1.0f).setDuration(CAMERA_BUTTON_FADE_DURATION);
-                    if (searchLight != null) {
-                        searchLight.animate().alpha(1.0f).setDuration(CAMERA_BUTTON_FADE_DURATION);
-                    }
+                    transitionCameraAndSearchButtonAlpha(1.0f);
                     break;
             }
             return KeyguardTouchDelegate.getInstance(getContext()).dispatch(event);
@@ -158,6 +163,17 @@
         watchForDevicePolicyChanges();
     }
 
+    protected void transitionCameraAndSearchButtonAlpha(float alpha) {
+        View cameraButtonView = getCameraButton();
+        if (cameraButtonView != null) {
+            cameraButtonView.animate().alpha(alpha).setDuration(CAMERA_BUTTON_FADE_DURATION);
+        }
+        View searchLight = getSearchLight();
+        if (searchLight != null) {
+            searchLight.animate().alpha(alpha).setDuration(CAMERA_BUTTON_FADE_DURATION);
+        }
+    }
+
     private void watchForDevicePolicyChanges() {
         final IntentFilter filter = new IntentFilter();
         filter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
@@ -388,44 +404,49 @@
 
         mCurrentView = mRotatedViews[Surface.ROTATION_0];
 
-
-        final AccessibilityManager accessibilityManager =
-                (AccessibilityManager) mContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
-        if (accessibilityManager.isEnabled() && accessibilityManager.isTouchExplorationEnabled()) {
-            // In accessibility mode, we add a simple click handler since swipe is tough to
-            // trigger near screen edges.
-            View camera = getCameraButton();
-            View searchLight = getSearchLight();
-            if (camera != null || searchLight != null) {
-                OnClickListener listener = new OnClickListener() {
-                    @Override
-                    public void onClick(View v) {
-                        launchForAccessibilityClick(v);
-                    }
-                };
-                if (camera != null) {
-                    camera.setOnClickListener(listener);
-                }
-                if (searchLight != null) {
-                    searchLight.setOnClickListener(listener);
-                }
-            }
-        } else {
-            // Add a touch handler for camera icon for all view orientations.
-            for (int i = 0; i < mRotatedViews.length; i++) {
-                View cameraButton = mRotatedViews[i].findViewById(R.id.camera_button);
-                if (cameraButton != null) {
-                    cameraButton.setOnTouchListener(mCameraTouchListener);
-                }
-            }
-        }
+        watchForAccessibilityChanges();
     }
 
-    protected void launchForAccessibilityClick(View v) {
-        if (v == getCameraButton()) {
-            KeyguardTouchDelegate.getInstance(getContext()).launchCamera();
-        } else if (v == getSearchLight()) {
-            KeyguardTouchDelegate.getInstance(getContext()).showAssistant();
+    private void watchForAccessibilityChanges() {
+        final AccessibilityManager am =
+                (AccessibilityManager) mContext.getSystemService(Context.ACCESSIBILITY_SERVICE);
+
+        // Set the initial state
+        enableAccessibility(am.isTouchExplorationEnabled());
+
+        // Watch for changes
+        am.addTouchExplorationStateChangeListener(new TouchExplorationStateChangeListener() {
+            @Override
+            public void onTouchExplorationStateChanged(boolean enabled) {
+                enableAccessibility(enabled);
+            }
+        });
+    }
+
+    private void enableAccessibility(boolean touchEnabled) {
+        Log.v(TAG, "touchEnabled:"  + touchEnabled);
+
+        // Add a touch handler or accessibility click listener for camera and search buttons
+        // for all view orientations.
+        final OnClickListener onClickListener = touchEnabled ? mAccessibilityClickListener : null;
+        final OnTouchListener onTouchListener = touchEnabled ? null : mCameraTouchListener;
+        boolean hasCamera = false;
+        for (int i = 0; i < mRotatedViews.length; i++) {
+            final View cameraButton = mRotatedViews[i].findViewById(R.id.camera_button);
+            final View searchLight = mRotatedViews[i].findViewById(R.id.search_light);
+            if (cameraButton != null) {
+                hasCamera = true;
+                cameraButton.setOnTouchListener(onTouchListener);
+                cameraButton.setOnClickListener(onClickListener);
+            }
+            if (searchLight != null) {
+                searchLight.setOnClickListener(onClickListener);
+            }
+        }
+        if (hasCamera) {
+            // Warm up KeyguardTouchDelegate so it's ready by the time the camera button is touched.
+            // This will connect to KeyguardService so that touch events are processed.
+            KeyguardTouchDelegate.getInstance(mContext);
         }
     }
 
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 c02a99b..3ddcb1b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
@@ -647,6 +647,20 @@
     }
 
     @Override
+    protected void onShowSearchPanel() {
+        if (mNavigationBarView != null) {
+            mNavigationBarView.transitionCameraAndSearchButtonAlpha(0.0f);
+        }
+    }
+
+    @Override
+    protected void onHideSearchPanel() {
+        if (mNavigationBarView != null) {
+            mNavigationBarView.transitionCameraAndSearchButtonAlpha(1.0f);
+        }
+    }
+
+    @Override
     protected View getStatusBarView() {
         return mStatusBarView;
     }
@@ -1923,10 +1937,8 @@
     }
 
     private void checkBarMode(int mode, int windowState, BarTransitions transitions) {
-        final boolean imeVisible = (mNavigationIconHints & NAVIGATION_HINT_BACK_ALT) != 0;
-        final int finalMode = imeVisible ? MODE_OPAQUE : mode;
         final boolean anim = (mScreenOn == null || mScreenOn) && windowState != WINDOW_STATE_HIDDEN;
-        transitions.transitionTo(finalMode, anim);
+        transitions.transitionTo(mode, anim);
     }
 
     private final Runnable mCheckBarModes = new Runnable() {
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
index adbada7..e9e3b27 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -2991,8 +2991,10 @@
             pf.left = df.left = of.left = cf.left = vf.left = mDockLeft;
             pf.top = df.top = of.top = cf.top = vf.top = mDockTop;
             pf.right = df.right = of.right = cf.right = vf.right = mDockRight;
-            // IM dock windows always go above the nav bar.
-            pf.bottom = df.bottom = of.bottom = cf.bottom = vf.bottom = mStableBottom;
+            // IM dock windows layout below the nav bar...
+            pf.bottom = df.bottom = of.bottom = mRestrictedScreenTop + mRestrictedScreenHeight;
+            // ...with content insets above the nav bar
+            cf.bottom = vf.bottom = mStableBottom;
             // IM dock windows always go to the bottom of the screen.
             attrs.gravity = Gravity.BOTTOM;
             mDockLayer = win.getSurfaceLayer();
@@ -4282,12 +4284,14 @@
                 })) {
                     return;
                 }
+                Slog.i(TAG, "No lock screen! waitForWindowDrawn false");
+
             } catch (RemoteException ex) {
                 // Can't happen in system process.
             }
         }
 
-        Slog.i(TAG, "No lock screen!");
+        Slog.i(TAG, "No lock screen! windowToken=" + windowToken);
         finishScreenTurningOn(screenOnListener);
     }
 
diff --git a/services/java/com/android/server/NotificationManagerService.java b/services/java/com/android/server/NotificationManagerService.java
index b881934..7431f1d 100644
--- a/services/java/com/android/server/NotificationManagerService.java
+++ b/services/java/com/android/server/NotificationManagerService.java
@@ -1167,11 +1167,19 @@
                     }
                     if (packageChanged) {
                         // We cancel notifications for packages which have just been disabled
-                        final int enabled = mContext.getPackageManager()
-                                .getApplicationEnabledSetting(pkgName);
-                        if (enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
-                                || enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
-                            cancelNotifications = false;
+                        try {
+                            final int enabled = mContext.getPackageManager()
+                                    .getApplicationEnabledSetting(pkgName);
+                            if (enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
+                                    || enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
+                                cancelNotifications = false;
+                            }
+                        } catch (IllegalArgumentException e) {
+                            // Package doesn't exist; probably racing with uninstall.
+                            // cancelNotifications is already true, so nothing to do here.
+                            if (DBG) {
+                                Slog.i(TAG, "Exception trying to look up app enabled setting", e);
+                            }
                         }
                     }
                     pkgList = new String[]{pkgName};
diff --git a/services/java/com/android/server/accounts/AccountManagerService.java b/services/java/com/android/server/accounts/AccountManagerService.java
index dd9ae4c..cc43a9c 100644
--- a/services/java/com/android/server/accounts/AccountManagerService.java
+++ b/services/java/com/android/server/accounts/AccountManagerService.java
@@ -293,17 +293,16 @@
         return mUserManager;
     }
 
-    private UserAccounts initUser(int userId) {
-        synchronized (mUsers) {
-            UserAccounts accounts = mUsers.get(userId);
-            if (accounts == null) {
-                accounts = new UserAccounts(mContext, userId);
-                mUsers.append(userId, accounts);
-                purgeOldGrants(accounts);
-                validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
-            }
-            return accounts;
+    /* Caller should lock mUsers */
+    private UserAccounts initUserLocked(int userId) {
+        UserAccounts accounts = mUsers.get(userId);
+        if (accounts == null) {
+            accounts = new UserAccounts(mContext, userId);
+            mUsers.append(userId, accounts);
+            purgeOldGrants(accounts);
+            validateAccountsInternal(accounts, true /* invalidateAuthenticatorCache */);
         }
+        return accounts;
     }
 
     private void purgeOldGrantsAll() {
@@ -427,7 +426,7 @@
         synchronized (mUsers) {
             UserAccounts accounts = mUsers.get(userId);
             if (accounts == null) {
-                accounts = initUser(userId);
+                accounts = initUserLocked(userId);
                 mUsers.append(userId, accounts);
             }
             return accounts;
@@ -1798,16 +1797,14 @@
 
     private AccountAndUser[] getAccounts(int[] userIds) {
         final ArrayList<AccountAndUser> runningAccounts = Lists.newArrayList();
-        synchronized (mUsers) {
-            for (int userId : userIds) {
-                UserAccounts userAccounts = getUserAccounts(userId);
-                if (userAccounts == null) continue;
-                synchronized (userAccounts.cacheLock) {
-                    Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
-                            Binder.getCallingUid(), null);
-                    for (int a = 0; a < accounts.length; a++) {
-                        runningAccounts.add(new AccountAndUser(accounts[a], userId));
-                    }
+        for (int userId : userIds) {
+            UserAccounts userAccounts = getUserAccounts(userId);
+            if (userAccounts == null) continue;
+            synchronized (userAccounts.cacheLock) {
+                Account[] accounts = getAccountsFromCacheLocked(userAccounts, null,
+                        Binder.getCallingUid(), null);
+                for (int a = 0; a < accounts.length; a++) {
+                    runningAccounts.add(new AccountAndUser(accounts[a], userId));
                 }
             }
         }
@@ -2858,7 +2855,8 @@
                 || callingUid == Process.myUid()) {
             return unfiltered;
         }
-        if (mUserManager.getUserInfo(userAccounts.userId).isRestricted()) {
+        UserInfo user = mUserManager.getUserInfo(userAccounts.userId);
+        if (user != null && user.isRestricted()) {
             String[] packages = mPackageManager.getPackagesForUid(callingUid);
             // If any of the packages is a white listed package, return the full set,
             // otherwise return non-shared accounts only.
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index 1987d04..6c6cc98 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -6489,26 +6489,53 @@
     }
 
     @Override
-    public ParceledListSlice<android.content.UriPermission> getPersistedUriPermissions() {
+    public ParceledListSlice<android.content.UriPermission> getPersistedUriPermissions(
+            String packageName, boolean incoming) {
         enforceNotIsolatedCaller("getPersistedUriPermissions");
+        Preconditions.checkNotNull(packageName, "packageName");
 
+        final int callingUid = Binder.getCallingUid();
+        final IPackageManager pm = AppGlobals.getPackageManager();
+        try {
+            final int packageUid = pm.getPackageUid(packageName, UserHandle.getUserId(callingUid));
+            if (packageUid != callingUid) {
+                throw new SecurityException(
+                        "Package " + packageName + " does not belong to calling UID " + callingUid);
+            }
+        } catch (RemoteException e) {
+            throw new SecurityException("Failed to verify package name ownership");
+        }
+
+        final ArrayList<android.content.UriPermission> result = Lists.newArrayList();
         synchronized (this) {
-            final int callingUid = Binder.getCallingUid();
-            final ArrayList<android.content.UriPermission> result = Lists.newArrayList();
-            final ArrayMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
-            if (perms == null) {
-                Slog.w(TAG, "No permission grants found for UID " + callingUid);
+            if (incoming) {
+                final ArrayMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
+                if (perms == null) {
+                    Slog.w(TAG, "No permission grants found for " + packageName);
+                } else {
+                    final int size = perms.size();
+                    for (int i = 0; i < size; i++) {
+                        final UriPermission perm = perms.valueAt(i);
+                        if (packageName.equals(perm.targetPkg) && perm.persistedModeFlags != 0) {
+                            result.add(perm.buildPersistedPublicApiObject());
+                        }
+                    }
+                }
             } else {
-                final int size = perms.size();
+                final int size = mGrantedUriPermissions.size();
                 for (int i = 0; i < size; i++) {
-                    final UriPermission perm = perms.valueAt(i);
-                    if (perm.persistedModeFlags != 0) {
-                        result.add(perm.buildPersistedPublicApiObject());
+                    final ArrayMap<Uri, UriPermission> perms = mGrantedUriPermissions.valueAt(i);
+                    final int permsSize = perms.size();
+                    for (int j = 0; j < permsSize; j++) {
+                        final UriPermission perm = perms.valueAt(j);
+                        if (packageName.equals(perm.sourcePkg) && perm.persistedModeFlags != 0) {
+                            result.add(perm.buildPersistedPublicApiObject());
+                        }
                     }
                 }
             }
-            return new ParceledListSlice<android.content.UriPermission>(result);
         }
+        return new ParceledListSlice<android.content.UriPermission>(result);
     }
 
     @Override
@@ -6755,7 +6782,6 @@
     private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
         tr.disposeThumbnail();
         mRecentTasks.remove(tr);
-        mStackSupervisor.removeTask(tr);
         final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
         Intent baseIntent = new Intent(
                 tr.intent != null ? tr.intent : tr.affinityIntent);
@@ -7526,16 +7552,30 @@
                                     + cpr.appInfo.packageName + ": " + e);
                         }
 
-                        ProcessRecord proc = startProcessLocked(cpi.processName,
-                                cpr.appInfo, false, 0, "content provider",
-                                new ComponentName(cpi.applicationInfo.packageName,
-                                        cpi.name), false, false, false);
-                        if (proc == null) {
-                            Slog.w(TAG, "Unable to launch app "
-                                    + cpi.applicationInfo.packageName + "/"
-                                    + cpi.applicationInfo.uid + " for provider "
-                                    + name + ": process is bad");
-                            return null;
+                        // Use existing process if already started
+                        ProcessRecord proc = getProcessRecordLocked(
+                                cpi.processName, cpr.appInfo.uid, false);
+                        if (proc != null) {
+                            if (DEBUG_PROVIDER) {
+                                Slog.d(TAG, "Installing in existing process " + proc);
+                            }
+                            proc.pubProviders.put(cpi.name, cpr);
+                            try {
+                                proc.thread.scheduleInstallProvider(cpi);
+                            } catch (RemoteException e) {
+                            }
+                        } else {
+                            proc = startProcessLocked(cpi.processName,
+                                    cpr.appInfo, false, 0, "content provider",
+                                    new ComponentName(cpi.applicationInfo.packageName,
+                                            cpi.name), false, false, false);
+                            if (proc == null) {
+                                Slog.w(TAG, "Unable to launch app "
+                                        + cpi.applicationInfo.packageName + "/"
+                                        + cpi.applicationInfo.uid + " for provider "
+                                        + name + ": process is bad");
+                                return null;
+                            }
                         }
                         cpr.launchingApp = proc;
                         mLaunchingProviders.add(cpr);
diff --git a/services/java/com/android/server/am/ProcessStatsService.java b/services/java/com/android/server/am/ProcessStatsService.java
index dbc05fa..a6375e1 100644
--- a/services/java/com/android/server/am/ProcessStatsService.java
+++ b/services/java/com/android/server/am/ProcessStatsService.java
@@ -566,6 +566,15 @@
             return;
         }
 
+        long ident = Binder.clearCallingIdentity();
+        try {
+            dumpInner(fd, pw, args);
+        } finally {
+            Binder.restoreCallingIdentity(ident);
+        }
+    }
+
+    private void dumpInner(FileDescriptor fd, PrintWriter pw, String[] args) {
         final long now = SystemClock.uptimeMillis();
 
         boolean isCheckin = false;
diff --git a/services/java/com/android/server/am/UriPermission.java b/services/java/com/android/server/am/UriPermission.java
index 5868c08..684f247 100644
--- a/services/java/com/android/server/am/UriPermission.java
+++ b/services/java/com/android/server/am/UriPermission.java
@@ -20,7 +20,6 @@
 import android.net.Uri;
 import android.os.UserHandle;
 import android.util.Log;
-import android.util.Slog;
 
 import com.android.internal.util.Preconditions;
 import com.google.android.collect.Sets;
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index e089ca6..aa8851c 100644
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -3386,9 +3386,9 @@
             throw new IllegalArgumentException("addAppToken: invalid stackId=" + stackId);
         }
         Task task = new Task(atoken, stack, userId);
+        mTaskIdToTask.put(taskId, task);
         stack.addTask(task, true);
         stack.getDisplayContent().moveStack(stack, true);
-        mTaskIdToTask.put(taskId, task);
         return task;
     }
 
@@ -4724,23 +4724,6 @@
         return index;
     }
 
-    private void moveHomeTasksLocked(boolean toTop) {
-        final DisplayContent displayContent = getDefaultDisplayContentLocked();
-        if (toTop ^ displayContent.homeOnTop()) {
-            final ArrayList<Task> tasks = displayContent.getHomeStack().getTasks();
-            final int numTasks = tasks.size();
-            for (int i = 0; i < numTasks; ++i) {
-                if (toTop) {
-                    // Keep pulling the bottom task off and moving it to the top.
-                    moveTaskToTop(tasks.get(0).taskId);
-                } else {
-                    // Keep pulling the top task off and moving it to the bottom.
-                    moveTaskToBottom(tasks.get(numTasks - 1).taskId);
-                }
-            }
-        }
-    }
-
     void moveStackWindowsLocked(TaskStack stack) {
         DisplayContent displayContent = stack.getDisplayContent();
 
@@ -4797,15 +4780,9 @@
                 final TaskStack stack = task.mStack;
                 final DisplayContent displayContent = task.getDisplayContent();
                 final boolean isHomeStackTask = stack.isHomeStack();
-                final boolean homeIsOnTop = displayContent.homeOnTop();
-                if (!isHomeStackTask && homeIsOnTop) {
-                    // First move move the home tasks all to the bottom to rearrange the windows.
-                    moveHomeTasksLocked(false);
-                    // Now move the stack itself.
-                    displayContent.moveHomeStackBox(false);
-                } else if (isHomeStackTask && !homeIsOnTop) {
-                    // Move the stack to the top.
-                    displayContent.moveHomeStackBox(true);
+                if (isHomeStackTask != displayContent.homeOnTop()) {
+                    // First move the stack itself.
+                    displayContent.moveHomeStackBox(isHomeStackTask);
                 }
                 stack.moveTaskToTop(task);
                 displayContent.moveStack(stack, true);
@@ -9473,9 +9450,8 @@
                 //Slog.i(TAG, "Waiting for drawn " + win + ": removed="
                 //        + win.mRemoved + " visible=" + win.isVisibleLw()
                 //        + " shown=" + win.mSurfaceShown);
-                if (win.mRemoved || !win.isVisibleLw()) {
-                    // Window has been removed or made invisible; no draw
-                    // will now happen, so stop waiting.
+                if (win.mRemoved) {
+                    // Window has been removed; no draw will now happen, so stop waiting.
                     Slog.w(TAG, "Aborted waiting for drawn: " + pair.first);
                     try {
                         pair.second.sendResult(null);
@@ -9510,6 +9486,7 @@
                     checkDrawnWindowsLocked();
                     return true;
                 }
+                Slog.i(TAG, "waitForWindowDrawn: win null");
             }
         }
         return false;
diff --git a/wifi/java/android/net/wifi/WifiStateMachine.java b/wifi/java/android/net/wifi/WifiStateMachine.java
index 349fe24..6b4c580 100644
--- a/wifi/java/android/net/wifi/WifiStateMachine.java
+++ b/wifi/java/android/net/wifi/WifiStateMachine.java
@@ -2958,7 +2958,9 @@
             if (mOperationalMode != CONNECT_MODE) {
                 mWifiNative.disconnect();
                 mWifiConfigStore.disableAllNetworks();
-                setWifiState(WIFI_STATE_DISABLED);
+                if (mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) {
+                    setWifiState(WIFI_STATE_DISABLED);
+                }
                 transitionTo(mScanModeState);
             } else {
                 /* Driver stop may have disabled networks, enable right after start */