Merge "Refine random stats generation."
diff --git a/Android.mk b/Android.mk
index 2311f3c..5a40318 100644
--- a/Android.mk
+++ b/Android.mk
@@ -400,6 +400,8 @@
 		            resources/samples/AccessibilityService "Accessibility Service" \
 		-samplecode $(sample_dir)/AccelerometerPlay \
 		            resources/samples/AccelerometerPlay "Accelerometer Play" \
+		-samplecode $(sample_dir)/ActionBarCompat \
+		            resources/samples/ActionBarCompat "Action Bar Compatibility" \
                 -samplecode $(sample_dir)/AndroidBeam \
 		            resources/samples/AndroidBeam "Android Beam" \
 		-samplecode $(sample_dir)/ApiDemos \
@@ -416,12 +418,12 @@
 		            resources/samples/BusinessCard "Business Card" \
 		-samplecode $(sample_dir)/ContactManager \
 		            resources/samples/ContactManager "Contact Manager" \
-    -samplecode $(sample_dir)/CubeLiveWallpaper \
-                resources/samples/CubeLiveWallpaper "Cube Live Wallpaper" \
+		-samplecode $(sample_dir)/CubeLiveWallpaper \
+		            resources/samples/CubeLiveWallpaper "Cube Live Wallpaper" \
 		-samplecode $(sample_dir)/Home \
 		            resources/samples/Home "Home" \
-                -samplecode $(sample_dir)/HoneycombGallery \
-                            resources/samples/HoneycombGallery "Honeycomb Gallery" \
+		-samplecode $(sample_dir)/HoneycombGallery \
+		            resources/samples/HoneycombGallery "Honeycomb Gallery" \
 		-samplecode $(sample_dir)/JetBoy \
 		            resources/samples/JetBoy "JetBoy" \
 		-samplecode $(sample_dir)/LunarLander \
diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl
index 45f9da2..fe32a5f 100644
--- a/core/java/android/view/IWindowManager.aidl
+++ b/core/java/android/view/IWindowManager.aidl
@@ -192,11 +192,12 @@
     int getPreferredOptionsPanelGravity();
 
 	/**
-	 * Lock the device orientation to the current rotation. Sensor input will
-	 * be ignored until thawRotation() is called.
+	 * Lock the device orientation to the specified rotation, or to the
+	 * current rotation if -1.  Sensor input will be ignored until
+	 * thawRotation() is called.
 	 * @hide
 	 */
-	void freezeRotation();
+	void freezeRotation(int rotation);
 
 	/**
 	 * Release the orientation lock imposed by freezeRotation().
diff --git a/core/java/android/webkit/WebTextView.java b/core/java/android/webkit/WebTextView.java
index 092e2b5..33f84a5 100644
--- a/core/java/android/webkit/WebTextView.java
+++ b/core/java/android/webkit/WebTextView.java
@@ -768,9 +768,13 @@
             imm.hideSoftInputFromWindow(getWindowToken(), 0);
         }
         mInsideRemove = true;
+        boolean isFocused = hasFocus();
         mWebView.removeView(this);
-        mWebView.requestFocus();
+        if (isFocused) {
+            mWebView.requestFocus();
+        }
         mInsideRemove = false;
+        mHandler.removeCallbacksAndMessages(null);
     }
 
     @Override
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index eaed9fe..89f21d7 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -1581,6 +1581,11 @@
             mListBoxDialog.dismiss();
             mListBoxDialog = null;
         }
+        // remove so that it doesn't cause events
+        if (mWebTextView != null) {
+            mWebTextView.remove();
+            mWebTextView = null;
+        }
         if (mNativeClass != 0) nativeStopGL();
         if (mWebViewCore != null) {
             // Set the handlers to null before destroying WebViewCore so no
@@ -7636,6 +7641,10 @@
     }
 
     /* package */ void passToJavaScript(String currentText, KeyEvent event) {
+        // check if mWebViewCore has been destroyed
+        if (mWebViewCore == null) {
+            return;
+        }
         WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
         arg.mEvent = event;
         arg.mCurrentText = currentText;
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index f7a9dc1..68de2e9 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -11605,7 +11605,7 @@
     private static final RectF      sTempRect = new RectF();
 
     // XXX should be much larger
-    private static final int        VERY_WIDE = 16384;
+    private static final int        VERY_WIDE = 1024*1024;
 
     private static final int        BLINK = 500;
 
diff --git a/core/res/res/layout/keyguard_screen_tab_unlock.xml b/core/res/res/layout/keyguard_screen_tab_unlock.xml
index 4349c5b..0ec8f75 100644
--- a/core/res/res/layout/keyguard_screen_tab_unlock.xml
+++ b/core/res/res/layout/keyguard_screen_tab_unlock.xml
@@ -121,7 +121,7 @@
 
     <RelativeLayout
         android:layout_width="match_parent"
-        android:layout_height="292dip">
+        android:layout_height="302dip">
 
         <com.android.internal.widget.multiwaveview.MultiWaveView
             android:id="@+id/unlock_widget"
diff --git a/core/res/res/values/styles.xml b/core/res/res/values/styles.xml
index 13de1c9..1f1dc26 100644
--- a/core/res/res/values/styles.xml
+++ b/core/res/res/values/styles.xml
@@ -1513,8 +1513,8 @@
     </style>
 
     <style name="Widget.Holo.StackView">
-        <item name="android:resOutColor">#ff6699ff</item>
-        <item name="android:clickColor">#886699ff</item>
+        <item name="android:resOutColor">@android:color/holo_blue_light</item>
+        <item name="android:clickColor">@android:color/holo_blue_light</item>
     </style>
 
     <style name="Widget.Holo.Button.Borderless">
diff --git a/docs/html/resources/resources-data.js b/docs/html/resources/resources-data.js
index 796b30a..9267373 100644
--- a/docs/html/resources/resources-data.js
+++ b/docs/html/resources/resources-data.js
@@ -408,6 +408,16 @@
     }
   },
   {
+    tags: ['sample', 'new', 'ui', 'compatibility', 'newfeature'],
+    path: 'samples/ActionBarCompat/index.html',
+    title: {
+      en: 'Action Bar Compatibility'
+    },
+    description: {
+      en: 'Shows how to use the action bar on both pre-API 11 and API 11+ devices, maximizing code re-use.'
+    }
+  },
+  {
     tags: ['sample', 'new'],
     path: 'samples/AndroidBeam/index.html',
     title: {
diff --git a/docs/html/resources/samples/images/ActionBarCompat1.png b/docs/html/resources/samples/images/ActionBarCompat1.png
new file mode 100644
index 0000000..64d3e66
--- /dev/null
+++ b/docs/html/resources/samples/images/ActionBarCompat1.png
Binary files differ
diff --git a/docs/html/resources/samples/images/ActionBarCompat2.png b/docs/html/resources/samples/images/ActionBarCompat2.png
new file mode 100644
index 0000000..04a7e6c
--- /dev/null
+++ b/docs/html/resources/samples/images/ActionBarCompat2.png
Binary files differ
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/AutoRotateController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/AutoRotateController.java
index 5ac5ad0..a31e2a4 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/AutoRotateController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/AutoRotateController.java
@@ -22,6 +22,7 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.provider.Settings;
+import android.util.Log;
 import android.util.Slog;
 import android.view.IWindowManager;
 import android.widget.CompoundButton;
@@ -63,13 +64,13 @@
                     try {
                         IWindowManager wm = IWindowManager.Stub.asInterface(
                                 ServiceManager.getService(Context.WINDOW_SERVICE));
-                        ContentResolver cr = mContext.getContentResolver();
                         if (autorotate) {
                             wm.thawRotation();
                         } else {
-                            wm.freezeRotation();
+                            wm.freezeRotation(-1);
                         }
                     } catch (RemoteException exc) {
+                        Log.w(TAG, "Unable to save auto-rotate setting");
                     }
                 }
             });
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
index ed67707..989ccf7 100755
--- a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -2947,10 +2947,7 @@
                 // enable 180 degree rotation while docked.
                 preferredRotation = mDeskDockEnablesAccelerometer
                         ? sensorRotation : mDeskDockRotation;
-            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
-                // Ignore sensor when user locked rotation.
-                preferredRotation = mUserRotation;
-            } else if ((mAccelerometerDefault != 0
+            } else if ((mAccelerometerDefault != 0 /* implies not rotation locked */
                             && (orientation == ActivityInfo.SCREEN_ORIENTATION_USER
                                     || orientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED))
                     || orientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
@@ -2973,6 +2970,9 @@
                 } else {
                     preferredRotation = lastRotation;
                 }
+            } else if (mUserRotationMode == WindowManagerPolicy.USER_ROTATION_LOCKED) {
+                // Apply rotation lock.
+                preferredRotation = mUserRotation;
             }
 
             // TODO: Sometimes, we might want to override the application-requested
@@ -3018,8 +3018,8 @@
                     return mPortraitRotation;
 
                 default:
-                    // For USER, UNSPECIFIED and NOSENSOR, just return the preferred
-                    // orientation we already calculated.
+                    // For USER, UNSPECIFIED, NOSENSOR, SENSOR and FULL_SENSOR,
+                    // just return the preferred orientation we already calculated.
                     if (preferredRotation >= 0) {
                         return preferredRotation;
                     }
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index 01f5a6f..ab49f93 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -5550,7 +5550,7 @@
 
     // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
     // so that a new chain is created with correct parameters when first effect is added. This is
-    // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
+    // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
     // removed.
     srcThread->removeEffectChain_l(chain);
 
@@ -5563,6 +5563,11 @@
     while (effect != 0) {
         srcThread->removeEffect_l(effect);
         dstThread->addEffect_l(effect);
+        // removeEffect_l() has stopped the effect if it was active so it must be restarted
+        if (effect->state() == EffectModule::ACTIVE ||
+                effect->state() == EffectModule::STOPPING) {
+            effect->start();
+        }
         // if the move request is not received from audio policy manager, the effect must be
         // re-registered with the new strategy and output
         if (dstChain == 0) {
@@ -6350,6 +6355,12 @@
     return status;
 }
 
+status_t AudioFlinger::EffectModule::start()
+{
+    Mutex::Autolock _l(mLock);
+    return start_l();
+}
+
 status_t AudioFlinger::EffectModule::start_l()
 {
     if (mEffectInterface == NULL) {
@@ -7214,7 +7225,10 @@
             // calling stop here will remove pre-processing effect from the audio HAL.
             // This is safe as we hold the EffectChain mutex which guarantees that we are not in
             // the middle of a read from audio HAL
-            mEffects[i]->stop();
+            if (mEffects[i]->state() == EffectModule::ACTIVE ||
+                    mEffects[i]->state() == EffectModule::STOPPING) {
+                mEffects[i]->stop();
+            }
             if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
                 delete[] effect->inBuffer();
             } else {
diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h
index 2e05593..ed9d81e 100644
--- a/services/audioflinger/AudioFlinger.h
+++ b/services/audioflinger/AudioFlinger.h
@@ -1117,6 +1117,7 @@
         status_t         setDevice(uint32_t device);
         status_t         setVolume(uint32_t *left, uint32_t *right, bool controller);
         status_t         setMode(uint32_t mode);
+        status_t         start();
         status_t         stop();
         void             setSuspended(bool suspended);
         bool             suspended();
diff --git a/services/java/com/android/server/AppWidgetService.java b/services/java/com/android/server/AppWidgetService.java
index 9f4936df..dd649e7 100644
--- a/services/java/com/android/server/AppWidgetService.java
+++ b/services/java/com/android/server/AppWidgetService.java
@@ -172,6 +172,10 @@
     boolean mSafeMode;
     boolean mStateLoaded;
 
+    // These are for debugging only -- widgets are going missing in some rare instances
+    ArrayList<Provider> mDeletedProviders = new ArrayList<Provider>();
+    ArrayList<Host> mDeletedHosts = new ArrayList<Host>();
+
     AppWidgetService(Context context) {
         mContext = context;
         mPackageManager = context.getPackageManager();
@@ -219,6 +223,55 @@
         }
     }
 
+    private void dumpProvider(Provider p, int index, PrintWriter pw) {
+        AppWidgetProviderInfo info = p.info;
+        pw.print("  ["); pw.print(index); pw.print("] provider ");
+                pw.print(info.provider.flattenToShortString());
+                pw.println(':');
+        pw.print("    min=("); pw.print(info.minWidth);
+                pw.print("x"); pw.print(info.minHeight);
+        pw.print(")   minResize=("); pw.print(info.minResizeWidth);
+                pw.print("x"); pw.print(info.minResizeHeight);
+                pw.print(") updatePeriodMillis=");
+                pw.print(info.updatePeriodMillis);
+                pw.print(" resizeMode=");
+                pw.print(info.resizeMode);
+                pw.print(" autoAdvanceViewId=");
+                pw.print(info.autoAdvanceViewId);
+                pw.print(" initialLayout=#");
+                pw.print(Integer.toHexString(info.initialLayout));
+                pw.print(" zombie="); pw.println(p.zombie);
+    }
+
+    private void dumpHost(Host host, int index, PrintWriter pw) {
+        pw.print("  ["); pw.print(index); pw.print("] hostId=");
+                pw.print(host.hostId); pw.print(' ');
+                pw.print(host.packageName); pw.print('/');
+        pw.print(host.uid); pw.println(':');
+        pw.print("    callbacks="); pw.println(host.callbacks);
+        pw.print("    instances.size="); pw.print(host.instances.size());
+                pw.print(" zombie="); pw.println(host.zombie);
+    }
+
+    private void dumpAppWidgetId(AppWidgetId id, int index, PrintWriter pw) {
+        pw.print("  ["); pw.print(index); pw.print("] id=");
+                pw.println(id.appWidgetId);
+        pw.print("    hostId=");
+                pw.print(id.host.hostId); pw.print(' ');
+                pw.print(id.host.packageName); pw.print('/');
+                pw.println(id.host.uid);
+        if (id.provider != null) {
+            pw.print("    provider=");
+                    pw.println(id.provider.info.provider.flattenToShortString());
+        }
+        if (id.host != null) {
+            pw.print("    host.callbacks="); pw.println(id.host.callbacks);
+        }
+        if (id.views != null) {
+            pw.print("    views="); pw.println(id.views);
+        }
+    }
+
     @Override
     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
@@ -233,61 +286,35 @@
             int N = mInstalledProviders.size();
             pw.println("Providers:");
             for (int i=0; i<N; i++) {
-                Provider p = mInstalledProviders.get(i);
-                AppWidgetProviderInfo info = p.info;
-                pw.print("  ["); pw.print(i); pw.print("] provider ");
-                        pw.print(info.provider.flattenToShortString());
-                        pw.println(':');
-                pw.print("    min=("); pw.print(info.minWidth);
-                        pw.print("x"); pw.print(info.minHeight);
-                pw.print(")   minResize=("); pw.print(info.minResizeWidth);
-                        pw.print("x"); pw.print(info.minResizeHeight);
-                        pw.print(") updatePeriodMillis=");
-                        pw.print(info.updatePeriodMillis);
-                        pw.print(" resizeMode=");
-                        pw.print(info.resizeMode);
-                        pw.print(" autoAdvanceViewId=");
-                        pw.print(info.autoAdvanceViewId);
-                        pw.print(" initialLayout=#");
-                        pw.print(Integer.toHexString(info.initialLayout));
-                        pw.print(" zombie="); pw.println(p.zombie);
+                dumpProvider(mInstalledProviders.get(i), i, pw);
             }
 
             N = mAppWidgetIds.size();
             pw.println(" ");
             pw.println("AppWidgetIds:");
             for (int i=0; i<N; i++) {
-                AppWidgetId id = mAppWidgetIds.get(i);
-                pw.print("  ["); pw.print(i); pw.print("] id=");
-                        pw.println(id.appWidgetId);
-                pw.print("    hostId=");
-                        pw.print(id.host.hostId); pw.print(' ');
-                        pw.print(id.host.packageName); pw.print('/');
-                        pw.println(id.host.uid);
-                if (id.provider != null) {
-                    pw.print("    provider=");
-                            pw.println(id.provider.info.provider.flattenToShortString());
-                }
-                if (id.host != null) {
-                    pw.print("    host.callbacks="); pw.println(id.host.callbacks);
-                }
-                if (id.views != null) {
-                    pw.print("    views="); pw.println(id.views);
-                }
+                dumpAppWidgetId(mAppWidgetIds.get(i), i, pw);
             }
 
             N = mHosts.size();
             pw.println(" ");
             pw.println("Hosts:");
             for (int i=0; i<N; i++) {
-                Host host = mHosts.get(i);
-                pw.print("  ["); pw.print(i); pw.print("] hostId=");
-                        pw.print(host.hostId); pw.print(' ');
-                        pw.print(host.packageName); pw.print('/');
-                        pw.print(host.uid); pw.println(':');
-                pw.print("    callbacks="); pw.println(host.callbacks);
-                pw.print("    instances.size="); pw.print(host.instances.size());
-                        pw.print(" zombie="); pw.println(host.zombie);
+                dumpHost(mHosts.get(i), i, pw);
+            }
+
+            N = mDeletedProviders.size();
+            pw.println(" ");
+            pw.println("Deleted Providers:");
+            for (int i=0; i<N; i++) {
+                dumpProvider(mDeletedProviders.get(i), i, pw);
+            }
+
+            N = mDeletedHosts.size();
+            pw.println(" ");
+            pw.println("Deleted Hosts:");
+            for (int i=0; i<N; i++) {
+                dumpHost(mDeletedHosts.get(i), i, pw);
             }
         }
     }
@@ -363,6 +390,7 @@
         }
         host.instances.clear();
         mHosts.remove(host);
+        mDeletedHosts.add(host);
         // it's gone or going away, abruptly drop the callback connection
         host.callbacks = null;
     }
@@ -934,6 +962,7 @@
         }
         p.instances.clear();
         mInstalledProviders.remove(index);
+        mDeletedProviders.add(p);
         // no need to send the DISABLE broadcast, since the receiver is gone anyway
         cancelBroadcasts(p);
     }
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index 8e98ec4..f1994d1 100644
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -5050,16 +5050,23 @@
     /**
      * Freeze rotation changes.  (Enable "rotation lock".)
      * Persists across reboots.
+     * @param rotation The desired rotation to freeze to, or -1 to use the
+     * current rotation.
      */
-    public void freezeRotation() {
+    public void freezeRotation(int rotation) {
         if (!checkCallingPermission(android.Manifest.permission.SET_ORIENTATION,
                 "freezeRotation()")) {
             throw new SecurityException("Requires SET_ORIENTATION permission");
         }
+        if (rotation < -1 || rotation > Surface.ROTATION_270) {
+            throw new IllegalArgumentException("Rotation argument must be -1 or a valid "
+                    + "rotation constant.");
+        }
 
         if (DEBUG_ORIENTATION) Slog.v(TAG, "freezeRotation: mRotation=" + mRotation);
 
-        mPolicy.setUserRotationMode(WindowManagerPolicy.USER_ROTATION_LOCKED, mRotation);
+        mPolicy.setUserRotationMode(WindowManagerPolicy.USER_ROTATION_LOCKED,
+                rotation == -1 ? mRotation : rotation);
         updateRotationUnchecked(false);
     }
 
diff --git a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
index 5df018e..c3ac22c 100644
--- a/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
+++ b/tests/permission/src/com/android/framework/permission/tests/WindowManagerPermissionTests.java
@@ -423,7 +423,7 @@
         }
 
         try {
-            mWm.freezeRotation();
+            mWm.freezeRotation(-1);
             mWm.getSwitchState(0);
             fail("IWindowManager.freezeRotation did not throw SecurityException as"
                     + " expected");
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowManager.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowManager.java
index 5b57266..44bdff3 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowManager.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowManager.java
@@ -124,7 +124,7 @@
 
     }
 
-    public void freezeRotation() throws RemoteException {
+    public void freezeRotation(int arg0) throws RemoteException {
         // TODO Auto-generated method stub
 
     }
diff --git a/wifi/java/android/net/wifi/WifiStateMachine.java b/wifi/java/android/net/wifi/WifiStateMachine.java
index 1e45f68..55e9587 100644
--- a/wifi/java/android/net/wifi/WifiStateMachine.java
+++ b/wifi/java/android/net/wifi/WifiStateMachine.java
@@ -381,6 +381,14 @@
      */
     private final int mDefaultSupplicantScanIntervalMs;
 
+    /**
+     * Minimum time interval between enabling all networks.
+     * A device can end up repeatedly connecting to a bad network on screen on/off toggle
+     * due to enabling every time. We add a threshold to avoid this.
+     */
+    private static final int MIN_INTERVAL_ENABLE_ALL_NETWORKS_MS = 10 * 60 * 1000; /* 10 minutes */
+    private long mLastEnableAllNetworksTime;
+
 
     private static final int MIN_RSSI = -200;
     private static final int MAX_RSSI = 256;
@@ -2248,7 +2256,11 @@
                     mReplyChannel.replyToMessage(message, message.what, ok ? SUCCESS : FAILURE);
                     break;
                 case CMD_ENABLE_ALL_NETWORKS:
-                    WifiConfigStore.enableAllNetworks();
+                    long time =  android.os.SystemClock.elapsedRealtime();
+                    if (time - mLastEnableAllNetworksTime > MIN_INTERVAL_ENABLE_ALL_NETWORKS_MS) {
+                        WifiConfigStore.enableAllNetworks();
+                        mLastEnableAllNetworksTime = time;
+                    }
                     break;
                 case CMD_DISABLE_NETWORK:
                     ok = WifiConfigStore.disableNetwork(message.arg1, message.arg2);