Fixes for proximity sensor behavior:

Add optional flag to Wakelock.release() to specify whether we should wait for proximity sensor to go negative before turning on the screen.
Clear the "waiting for proximity sensor to go negative" state when the power key is pressed.

Part of the fix for b/2243198 (Black screen lockup after ending call)

Change-Id: I813fdb7aa4192cd3384a25be9e59d7d4b90da53a
Signed-off-by: Mike Lockwood <lockwood@android.com>
diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java
index 2efc230..4b3b6f6 100644
--- a/core/java/android/os/PowerManager.java
+++ b/core/java/android/os/PowerManager.java
@@ -159,6 +159,15 @@
     public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = WAKE_BIT_PROXIMITY_SCREEN_OFF;
 
     /**
+     * Flag for {@link WakeLock#release release(int)} to defer releasing a
+     * {@link #WAKE_BIT_PROXIMITY_SCREEN_OFF} wakelock until the proximity sensor returns
+     * a negative value.
+     *
+     * {@hide}
+     */
+    public static final int WAIT_FOR_PROXIMITY_NEGATIVE = 1;
+
+    /**
      * Normally wake locks don't actually wake the device, they just cause
      * it to remain on once it's already on.  Think of the video player
      * app as the normal behavior.  Notifications that pop up and want
@@ -267,10 +276,26 @@
          */
         public void release()
         {
+            release(0);
+        }
+
+        /**
+         * Release your claim to the CPU or screen being on.
+         * @param flags Combination of flag values to modify the release behavior.
+         *              Currently only {@link #WAIT_FOR_PROXIMITY_NEGATIVE} is supported.
+         *
+         * <p>
+         * It may turn off shortly after you release it, or it may not if there
+         * are other wake locks held.
+         *
+         * {@hide}
+         */
+        public void release(int flags)
+        {
             synchronized (mToken) {
                 if (!mRefCounted || --mCount == 0) {
                     try {
-                        mService.releaseWakeLock(mToken);
+                        mService.releaseWakeLock(mToken, flags);
                     } catch (RemoteException e) {
                     }
                     mHeld = false;
@@ -302,7 +327,7 @@
             synchronized (mToken) {
                 if (mHeld) {
                     try {
-                        mService.releaseWakeLock(mToken);
+                        mService.releaseWakeLock(mToken, 0);
                     } catch (RemoteException e) {
                     }
                     RuntimeInit.crash(TAG, new Exception(