Merge "Cleanup of docs for ViewPropertyAnimator class"
diff --git a/api/current.xml b/api/current.xml
index 83055bf..2663c53 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -149702,6 +149702,17 @@
  visibility="public"
 >
 </method>
+<method name="detachFd"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="fromSocket"
  return="android.os.ParcelFileDescriptor"
  abstract="false"
@@ -149715,6 +149726,17 @@
 <parameter name="socket" type="java.net.Socket">
 </parameter>
 </method>
+<method name="getFd"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
 <method name="getFileDescriptor"
  return="java.io.FileDescriptor"
  abstract="false"
diff --git a/core/java/android/accounts/AccountManagerService.java b/core/java/android/accounts/AccountManagerService.java
index c91cdca..a1c2867 100644
--- a/core/java/android/accounts/AccountManagerService.java
+++ b/core/java/android/accounts/AccountManagerService.java
@@ -209,9 +209,44 @@
 
         sThis.set(this);
 
+        IntentFilter intentFilter = new IntentFilter();
+        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+        intentFilter.addDataScheme("package");
+        mContext.registerReceiver(new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context1, Intent intent) {
+                purgeOldGrants();
+            }
+        }, intentFilter);
+        purgeOldGrants();
+
         validateAccountsAndPopulateCache();
     }
 
+    private void purgeOldGrants() {
+        synchronized (mCacheLock) {
+            final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+            final Cursor cursor = db.query(TABLE_GRANTS,
+                    new String[]{GRANTS_GRANTEE_UID},
+                    null, null, GRANTS_GRANTEE_UID, null, null);
+            try {
+                while (cursor.moveToNext()) {
+                    final int uid = cursor.getInt(0);
+                    final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
+                    if (packageExists) {
+                        continue;
+                    }
+                    Log.d(TAG, "deleting grants for UID " + uid
+                            + " because its package is no longer installed");
+                    db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
+                            new String[]{Integer.toString(uid)});
+                }
+            } finally {
+                cursor.close();
+            }
+        }
+    }
+
     private void validateAccountsAndPopulateCache() {
         boolean accountDeleted = false;
         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
diff --git a/core/java/android/app/backup/WallpaperBackupHelper.java b/core/java/android/app/backup/WallpaperBackupHelper.java
index d70b3d3..6539711 100644
--- a/core/java/android/app/backup/WallpaperBackupHelper.java
+++ b/core/java/android/app/backup/WallpaperBackupHelper.java
@@ -21,6 +21,8 @@
 import android.graphics.BitmapFactory;
 import android.os.ParcelFileDescriptor;
 import android.util.Slog;
+import android.view.Display;
+import android.view.WindowManager;
 
 import java.io.File;
 
@@ -65,6 +67,13 @@
         mDesiredMinWidth = (double) wpm.getDesiredMinimumWidth();
         mDesiredMinHeight = (double) wpm.getDesiredMinimumHeight();
 
+        if (mDesiredMinWidth <= 0 || mDesiredMinHeight <= 0) {
+            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
+            Display d = wm.getDefaultDisplay();
+            mDesiredMinWidth = d.getWidth();
+            mDesiredMinHeight = d.getHeight();
+        }
+
         if (DEBUG) {
             Slog.d(TAG, "dmW=" + mDesiredMinWidth + " dmH=" + mDesiredMinHeight);
         }
diff --git a/core/java/android/os/Parcel.java b/core/java/android/os/Parcel.java
index 8944f12..eca34848 100644
--- a/core/java/android/os/Parcel.java
+++ b/core/java/android/os/Parcel.java
@@ -1385,6 +1385,7 @@
             int mode) throws FileNotFoundException;
     /*package*/ static native void closeFileDescriptor(FileDescriptor desc)
             throws IOException;
+    /*package*/ static native void clearFileDescriptor(FileDescriptor desc);
 
     /**
      * Read a byte value from the parcel at the current dataPosition().
diff --git a/core/java/android/os/ParcelFileDescriptor.java b/core/java/android/os/ParcelFileDescriptor.java
index 3a5d26b..5bd129f 100644
--- a/core/java/android/os/ParcelFileDescriptor.java
+++ b/core/java/android/os/ParcelFileDescriptor.java
@@ -197,6 +197,40 @@
     public native long seekTo(long pos);
     
     /**
+     * Return the native fd int for this ParcelFileDescriptor.  The
+     * ParcelFileDescriptor still owns the fd, and it still must be closed
+     * through this API.
+     */
+    public int getFd() {
+        if (mClosed) {
+            throw new IllegalStateException("Already closed");
+        }
+        return getFdNative();
+    }
+    
+    private native int getFdNative();
+    
+    /**
+     * Return the native fd int for this ParcelFileDescriptor and detach it
+     * from the object here.  You are now responsible for closing the fd in
+     * native code.
+     */
+    public int detachFd() {
+        if (mClosed) {
+            throw new IllegalStateException("Already closed");
+        }
+        if (mParcelDescriptor != null) {
+            int fd = mParcelDescriptor.detachFd();
+            mClosed = true;
+            return fd;
+        }
+        int fd = getFd();
+        mClosed = true;
+        Parcel.clearFileDescriptor(mFileDescriptor);
+        return fd;
+    }
+    
+    /**
      * Close the ParcelFileDescriptor. This implementation closes the underlying
      * OS resources allocated to represent this stream.
      * 
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index 1d05d0b..47bf57f 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -3241,6 +3241,27 @@
             mLastY = y;
             break;
         }
+
+        case MotionEvent.ACTION_POINTER_DOWN: {
+            // New pointers take over dragging duties
+            final int index = ev.getActionIndex();
+            final int id = ev.getPointerId(index);
+            final int x = (int) ev.getX(index);
+            final int y = (int) ev.getY(index);
+            mMotionCorrection = 0;
+            mActivePointerId = id;
+            mMotionX = x;
+            mMotionY = y;
+            final int motionPosition = pointToPosition(x, y);
+            if (motionPosition >= 0) {
+                // Remember where the motion event started
+                v = getChildAt(motionPosition - mFirstPosition);
+                mMotionViewOriginalTop = v.getTop();
+                mMotionPosition = motionPosition;
+            }
+            mLastY = y;
+            break;
+        }
         }
 
         return true;
@@ -3270,7 +3291,7 @@
                         final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
                         if (vscroll != 0) {
                             final int delta = (int) (vscroll * getVerticalScrollFactor());
-                            if (trackMotionScroll(delta, delta)) {
+                            if (!trackMotionScroll(delta, delta)) {
                                 return true;
                             }
                         }
@@ -3412,9 +3433,6 @@
             mMotionY = (int) ev.getY(newPointerIndex);
             mMotionCorrection = 0;
             mActivePointerId = ev.getPointerId(newPointerIndex);
-            if (mVelocityTracker != null) {
-                mVelocityTracker.clear();
-            }
         }
     }
 
diff --git a/core/java/android/widget/ExpandableListView.java b/core/java/android/widget/ExpandableListView.java
index 8279ee5..f862368 100644
--- a/core/java/android/widget/ExpandableListView.java
+++ b/core/java/android/widget/ExpandableListView.java
@@ -299,6 +299,9 @@
                     indicatorRect.right = mIndicatorRight;
                 }
                 
+                indicatorRect.left += mPaddingLeft;
+                indicatorRect.right += mPaddingLeft;
+
                 lastItemType = pos.position.type; 
             }
 
diff --git a/core/java/android/widget/HorizontalScrollView.java b/core/java/android/widget/HorizontalScrollView.java
index 3255f6f..d92588cb 100644
--- a/core/java/android/widget/HorizontalScrollView.java
+++ b/core/java/android/widget/HorizontalScrollView.java
@@ -475,8 +475,16 @@
                     invalidate();
                 }
                 break;
+            case MotionEvent.ACTION_POINTER_DOWN: {
+                final int index = ev.getActionIndex();
+                final float x = ev.getX(index);
+                mLastMotionX = x;
+                mActivePointerId = ev.getPointerId(index);
+                break;
+            }
             case MotionEvent.ACTION_POINTER_UP:
                 onSecondaryPointerUp(ev);
+                mLastMotionX = ev.getX(ev.findPointerIndex(mActivePointerId));
                 break;
         }
 
diff --git a/core/java/android/widget/ScrollView.java b/core/java/android/widget/ScrollView.java
index 7aca0db..4b4f5f2 100644
--- a/core/java/android/widget/ScrollView.java
+++ b/core/java/android/widget/ScrollView.java
@@ -607,8 +607,16 @@
                     endDrag();
                 }
                 break;
+            case MotionEvent.ACTION_POINTER_DOWN: {
+                final int index = ev.getActionIndex();
+                final float y = ev.getY(index);
+                mLastMotionY = y;
+                mActivePointerId = ev.getPointerId(index);
+                break;
+            }
             case MotionEvent.ACTION_POINTER_UP:
                 onSecondaryPointerUp(ev);
+                mLastMotionY = ev.getY(ev.findPointerIndex(mActivePointerId));
                 break;
         }
         return true;
diff --git a/core/jni/android_os_ParcelFileDescriptor.cpp b/core/jni/android_os_ParcelFileDescriptor.cpp
index eceef1c..1f737f9 100644
--- a/core/jni/android_os_ParcelFileDescriptor.cpp
+++ b/core/jni/android_os_ParcelFileDescriptor.cpp
@@ -126,6 +126,17 @@
     return lseek(fd, pos, SEEK_SET);
 }
 
+static jlong android_os_ParcelFileDescriptor_getFdNative(JNIEnv* env, jobject clazz)
+{
+    jint fd = getFd(env, clazz);
+    if (fd < 0) {
+        jniThrowException(env, "java/lang/IllegalArgumentException", "bad file descriptor");
+        return -1;
+    }
+
+    return fd;
+}
+
 static const JNINativeMethod gParcelFileDescriptorMethods[] = {
     {"getFileDescriptorFromSocket", "(Ljava/net/Socket;)Ljava/io/FileDescriptor;",
         (void*)android_os_ParcelFileDescriptor_getFileDescriptorFromSocket},
@@ -134,7 +145,9 @@
     {"getStatSize", "()J",
         (void*)android_os_ParcelFileDescriptor_getStatSize},
     {"seekTo", "(J)J",
-        (void*)android_os_ParcelFileDescriptor_seekTo}
+        (void*)android_os_ParcelFileDescriptor_seekTo},
+    {"getFdNative", "()I",
+        (void*)android_os_ParcelFileDescriptor_getFdNative}
 };
 
 const char* const kParcelFileDescriptorPathName = "android/os/ParcelFileDescriptor";
diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp
index 7226e31..15362eb 100644
--- a/core/jni/android_util_Binder.cpp
+++ b/core/jni/android_util_Binder.cpp
@@ -1520,6 +1520,14 @@
     }
 }
 
+static void android_os_Parcel_clearFileDescriptor(JNIEnv* env, jobject clazz, jobject object)
+{
+    int fd = env->GetIntField(object, gFileDescriptorOffsets.mDescriptor);
+    if (fd >= 0) {
+        env->SetIntField(object, gFileDescriptorOffsets.mDescriptor, -1);
+    }
+}
+
 static void android_os_Parcel_freeBuffer(JNIEnv* env, jobject clazz)
 {
     int32_t own = env->GetIntField(clazz, gParcelOffsets.mOwnObject);
@@ -1719,6 +1727,7 @@
     {"internalReadFileDescriptor",  "()Ljava/io/FileDescriptor;", (void*)android_os_Parcel_readFileDescriptor},
     {"openFileDescriptor",  "(Ljava/lang/String;I)Ljava/io/FileDescriptor;", (void*)android_os_Parcel_openFileDescriptor},
     {"closeFileDescriptor", "(Ljava/io/FileDescriptor;)V", (void*)android_os_Parcel_closeFileDescriptor},
+    {"clearFileDescriptor", "(Ljava/io/FileDescriptor;)V", (void*)android_os_Parcel_clearFileDescriptor},
     {"freeBuffer",          "()V", (void*)android_os_Parcel_freeBuffer},
     {"init",                "(I)V", (void*)android_os_Parcel_init},
     {"destroy",             "()V", (void*)android_os_Parcel_destroy},
diff --git a/data/etc/com.google.android.usb.xml b/data/etc/com.google.android.usb.xml
new file mode 100644
index 0000000..fae3d23
--- /dev/null
+++ b/data/etc/com.google.android.usb.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+  
+          http://www.apache.org/licenses/LICENSE-2.0
+  
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<permissions>
+    <library name="com.google.android.usb"
+            file="/system/framework/com.google.android.usb.jar" />
+</permissions>
diff --git a/libs/usb/Android.mk b/libs/usb/Android.mk
new file mode 100644
index 0000000..d0ef6f0
--- /dev/null
+++ b/libs/usb/Android.mk
@@ -0,0 +1,27 @@
+#
+# Copyright (C) 2008 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(call all-java-files-under,src)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE:= com.google.android.usb
+
+include $(BUILD_JAVA_LIBRARY)
diff --git a/libs/usb/src/com/google/android/usb/UsbAccessory.java b/libs/usb/src/com/google/android/usb/UsbAccessory.java
new file mode 100644
index 0000000..91095f3
--- /dev/null
+++ b/libs/usb/src/com/google/android/usb/UsbAccessory.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.android.usb;
+
+/**
+ * A class representing a USB accessory.
+ */
+public final class UsbAccessory {
+
+    private final String mManufacturer;
+    private final String mModel;
+    private final String mType;
+    private final String mVersion;
+
+    /* package */ UsbAccessory(android.hardware.UsbAccessory accessory) {
+        mManufacturer = accessory.getManufacturer();
+        mModel = accessory.getModel();
+        mType = accessory.getType();
+        mVersion = accessory.getVersion();
+    }
+
+    /**
+     * Returns the manufacturer of the accessory.
+     *
+     * @return the accessory manufacturer
+     */
+    public String getManufacturer() {
+        return mManufacturer;
+    }
+
+    /**
+     * Returns the model name of the accessory.
+     *
+     * @return the accessory model
+     */
+    public String getModel() {
+        return mModel;
+    }
+
+    /**
+     * Returns the type of the accessory.
+     *
+     * @return the accessory type
+     */
+    public String getType() {
+        return mType;
+    }
+
+    /**
+     * Returns the version of the accessory.
+     *
+     * @return the accessory version
+     */
+    public String getVersion() {
+        return mVersion;
+    }
+
+    private static boolean compare(String s1, String s2) {
+        if (s1 == null) return (s2 == null);
+        return s1.equals(s2);
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj instanceof UsbAccessory) {
+            UsbAccessory accessory = (UsbAccessory)obj;
+            return (compare(mManufacturer, accessory.getManufacturer()) &&
+                    compare(mModel, accessory.getModel()) &&
+                    compare(mType, accessory.getType()) &&
+                    compare(mVersion, accessory.getVersion()));
+        }
+        return false;
+    }
+
+    @Override
+    public String toString() {
+        return "UsbAccessory[mManufacturer=" + mManufacturer +
+                            ", mModel=" + mModel +
+                            ", mType=" + mType +
+                            ", mVersion=" + mVersion + "]";
+    }
+}
diff --git a/libs/usb/src/com/google/android/usb/UsbManager.java b/libs/usb/src/com/google/android/usb/UsbManager.java
new file mode 100644
index 0000000..1b9bff9
--- /dev/null
+++ b/libs/usb/src/com/google/android/usb/UsbManager.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package com.google.android.usb;
+
+import android.content.Context;
+import android.content.Intent;
+import android.hardware.IUsbManager;
+import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.util.Log;
+
+/**
+ * This class allows you to access the state of USB, both in host and device mode.
+ *
+ * <p>You can obtain an instance of this class by calling {@link #getInstance}
+ *
+ */
+public class UsbManager {
+    private static final String TAG = "UsbManager";
+
+   /**
+     * Broadcast Action:  A broadcast for USB accessory attached event.
+     *
+     * This intent is sent when a USB accessory is attached.
+     * Call {@link #getAccessory(android.content.Intent)} to retrieve the
+     * {@link com.google.android.usb.UsbAccessory} for the attached accessory.
+     */
+    public static final String ACTION_USB_ACCESSORY_ATTACHED =
+            "android.hardware.action.USB_ACCESSORY_ATTACHED";
+
+   /**
+     * Broadcast Action:  A broadcast for USB accessory detached event.
+     *
+     * This intent is sent when a USB accessory is detached.
+     * Call {@link #getAccessory(android.content.Intent)} to retrieve the
+     * {@link com.google.android.usb.UsbAccessory} for the attached accessory that was detached.
+     */
+    public static final String ACTION_USB_ACCESSORY_DETACHED =
+            "android.hardware.action.USB_ACCESSORY_DETACHED";
+
+    private final IUsbManager mService;
+
+    private UsbManager(IUsbManager service) {
+        mService = service;
+    }
+
+    /**
+     * Returns a new instance of this class.
+     *
+     * @return UsbManager instance.
+     */
+    public static UsbManager getInstance() {
+        IBinder b = ServiceManager.getService(Context.USB_SERVICE);
+        return new UsbManager(IUsbManager.Stub.asInterface(b));
+    }
+
+    /**
+     * Returns the {@link com.google.android.usb.UsbAccessory} for
+     * a {@link #ACTION_USB_ACCESSORY_ATTACHED} or {@link #ACTION_USB_ACCESSORY_ATTACHED}
+     * broadcast Intent
+     *
+     * @return UsbAccessory for the broadcast.
+     */
+    public static UsbAccessory getAccessory(Intent intent) {
+        android.hardware.UsbAccessory accessory =
+            intent.getParcelableExtra(android.hardware.UsbManager.EXTRA_ACCESSORY);
+        if (accessory == null) {
+            return null;
+        } else {
+            return new UsbAccessory(accessory);
+        }
+    }
+
+    /**
+     * Returns a list of currently attached USB accessories.
+     * (in the current implementation there can be at most one)
+     *
+     * @return list of USB accessories, or null if none are attached.
+     */
+    public UsbAccessory[] getAccessoryList() {
+        try {
+            android.hardware.UsbAccessory accessory = mService.getCurrentAccessory();
+            if (accessory == null) {
+                return null;
+            } else {
+                return new UsbAccessory[] { new UsbAccessory(accessory) };
+            }
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException in getAccessoryList" , e);
+            return null;
+        }
+    }
+
+    /**
+     * Opens a file descriptor for reading and writing data to the USB accessory.
+     *
+     * @param accessory the USB accessory to open
+     * @return file descriptor, or null if the accessor could not be opened.
+     */
+    public ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
+        try {
+            return mService.openAccessory(new android.hardware.UsbAccessory(
+                    accessory.getManufacturer(),accessory.getModel(),
+                    accessory.getType(), accessory.getVersion()));
+        } catch (RemoteException e) {
+            Log.e(TAG, "RemoteException in openAccessory" , e);
+            return null;
+        }
+    }
+}
diff --git a/libs/usb/tests/AccessoryChat/Android.mk b/libs/usb/tests/AccessoryChat/Android.mk
new file mode 100644
index 0000000..b854569
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/Android.mk
@@ -0,0 +1,15 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_PACKAGE_NAME := AccessoryChatGB
+
+LOCAL_JAVA_LIBRARIES := com.google.android.usb
+
+# Force an old SDK version to make sure we aren't using newer UsbManager APIs
+LOCAL_SDK_VERSION := 8
+
+include $(BUILD_PACKAGE)
diff --git a/libs/usb/tests/AccessoryChat/AndroidManifest.xml b/libs/usb/tests/AccessoryChat/AndroidManifest.xml
new file mode 100644
index 0000000..b63999c
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/AndroidManifest.xml
@@ -0,0 +1,23 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+        package="com.google.android.accessorychat">
+
+    <application>
+        <uses-library android:name="com.google.android.usb" />
+
+        <activity android:name="AccessoryChat" android:label="Accessory Chat GB">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+
+            <intent-filter>
+                <action android:name="android.hardware.action.USB_ACCESSORY_ATTACHED" />
+            </intent-filter>
+
+            <meta-data android:name="android.hardware.action.USB_ACCESSORY_ATTACHED"
+                android:resource="@xml/accessory_filter" />
+        </activity>
+    </application>
+    <uses-sdk android:minSdkVersion="8" />
+</manifest>
diff --git a/libs/usb/tests/AccessoryChat/README.txt b/libs/usb/tests/AccessoryChat/README.txt
new file mode 100644
index 0000000..d2ce11e
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/README.txt
@@ -0,0 +1,10 @@
+This is a test app for the USB accessory APIs.  It consists of two parts:
+
+AccessoryChat - A Java app with a chat-like UI that sends and receives strings
+                via the UsbAccessory class.
+
+accessorychat - A C command-line program that communicates with AccessoryChat.
+                This program behaves as if it were a USB accessory.
+                It builds both for the host (Linux PC) and as an android
+                command line program, which will work if run as root on an
+                android device with USB host support
diff --git a/libs/usb/tests/AccessoryChat/accessorychat/Android.mk b/libs/usb/tests/AccessoryChat/accessorychat/Android.mk
new file mode 100644
index 0000000..300224a
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/accessorychat/Android.mk
@@ -0,0 +1,34 @@
+LOCAL_PATH:= $(call my-dir)
+
+# Build for Linux (desktop) host
+ifeq ($(HOST_OS),linux)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := accessorychat.c
+
+LOCAL_MODULE := accessorychat
+
+LOCAL_C_INCLUDES += bionic/libc/kernel/common
+LOCAL_STATIC_LIBRARIES := libusbhost libcutils
+LOCAL_LDLIBS += -lpthread
+LOCAL_CFLAGS := -g -O0
+
+include $(BUILD_HOST_EXECUTABLE)
+
+endif
+
+# Build for device
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := accessorychat.c
+
+LOCAL_MODULE := accessorychat
+
+LOCAL_SHARED_LIBRARIES := libusbhost libcutils
+
+include $(BUILD_EXECUTABLE)
diff --git a/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c b/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c
new file mode 100644
index 0000000..94cc0ce
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <pthread.h>
+
+#include <usbhost/usbhost.h>
+#include <linux/usb/f_accessory.h>
+
+struct usb_device *sDevice = NULL;
+
+static void* read_thread(void* arg) {
+    int endpoint = (int)arg;
+    int ret = 0;
+
+    while (sDevice && ret >= 0) {
+        char    buffer[16384];
+
+        ret = usb_device_bulk_transfer(sDevice, endpoint, buffer, sizeof(buffer), 1000);
+        if (ret < 0 && errno == ETIMEDOUT)
+            ret = 0;
+        if (ret > 0) {
+            fwrite(buffer, 1, ret, stdout);
+            printf("\n");
+            fflush(stdout);
+        }
+    }
+
+    return NULL;
+}
+
+static void* write_thread(void* arg) {
+    int endpoint = (int)arg;
+    int ret = 0;
+
+    while (ret >= 0) {
+        char    buffer[16384];
+        char *line = fgets(buffer, sizeof(buffer), stdin);
+        if (!line || !sDevice)
+            break;
+        ret = usb_device_bulk_transfer(sDevice, endpoint, line, strlen(line), 1000);
+    }
+
+    return NULL;
+}
+
+static void send_string(struct usb_device *device, int index, const char* string) {
+    int ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
+            ACCESSORY_SEND_STRING, 0, index, (void *)string, strlen(string) + 1, 0);
+}
+
+static int usb_device_added(const char *devname, void* client_data) {
+    struct usb_descriptor_header* desc;
+    struct usb_descriptor_iter iter;
+    uint16_t vendorId, productId;
+    int ret;
+    pthread_t th;
+
+    struct usb_device *device = usb_device_open(devname);
+    if (!device) {
+        fprintf(stderr, "usb_device_open failed\n");
+        return 0;
+    }
+
+    vendorId = usb_device_get_vendor_id(device);
+    productId = usb_device_get_product_id(device);
+
+    if (vendorId == 0x18D1 || vendorId == 0x22B8) {
+        if (!sDevice && (productId == 0x2D00 || productId == 0x2D01)) {
+            struct usb_descriptor_header* desc;
+            struct usb_descriptor_iter iter;
+            struct usb_interface_descriptor *intf = NULL;
+            struct usb_endpoint_descriptor *ep1 = NULL;
+            struct usb_endpoint_descriptor *ep2 = NULL;
+
+            printf("Found android device in accessory mode\n");
+            sDevice = device;
+
+            usb_descriptor_iter_init(device, &iter);
+            while ((desc = usb_descriptor_iter_next(&iter)) != NULL && (!intf || !ep1 || !ep2)) {
+                if (desc->bDescriptorType == USB_DT_INTERFACE) {
+                    intf = (struct usb_interface_descriptor *)desc;
+                } else if (desc->bDescriptorType == USB_DT_ENDPOINT) {
+                    if (ep1)
+                        ep2 = (struct usb_endpoint_descriptor *)desc;
+                    else
+                        ep1 = (struct usb_endpoint_descriptor *)desc;
+                }
+            }
+
+            if (!intf) {
+                fprintf(stderr, "interface not found\n");
+                exit(1);
+            }
+            if (!ep1 || !ep2) {
+                fprintf(stderr, "endpoints not found\n");
+                exit(1);
+            }
+
+            if (usb_device_claim_interface(device, intf->bInterfaceNumber)) {
+                fprintf(stderr, "usb_device_claim_interface failed errno: %d\n", errno);
+                exit(1);
+            }
+
+            if ((ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) {
+                pthread_create(&th, NULL, read_thread, (void *)ep1->bEndpointAddress);
+                pthread_create(&th, NULL, write_thread, (void *)ep2->bEndpointAddress);
+            } else {
+                pthread_create(&th, NULL, read_thread, (void *)ep2->bEndpointAddress);
+                pthread_create(&th, NULL, write_thread, (void *)ep1->bEndpointAddress);
+            }
+        } else {
+            printf("Found possible android device - attempting to switch to accessory mode\n");
+
+            send_string(device, ACCESSORY_STRING_MANUFACTURER, "Google, Inc.");
+            send_string(device, ACCESSORY_STRING_MODEL, "AccessoryChat");
+            send_string(device, ACCESSORY_STRING_TYPE, "Sample Program");
+            send_string(device, ACCESSORY_STRING_VERSION, "1.0");
+
+            ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
+                    ACCESSORY_START, 0, 0, 0, 0, 0);
+            return 0;
+        }
+    }
+
+    if (device != sDevice)
+        usb_device_close(device);
+
+    return 0;
+}
+
+static int usb_device_removed(const char *devname, void* client_data) {
+    if (sDevice && !strcmp(usb_device_get_name(sDevice), devname)) {
+        usb_device_close(sDevice);
+        sDevice = NULL;
+        // exit when we are disconnected
+        return 1;
+    }
+    return 0;
+}
+
+
+int main(int argc, char* argv[]) {
+    struct usb_host_context* context = usb_host_init();
+    if (!context) {
+        fprintf(stderr, "usb_host_init failed");
+        return 1;
+    }
+
+    // this will never return so it is safe to pass thiz directly
+    usb_host_run(context, usb_device_added, usb_device_removed, NULL, NULL);
+    return 0;
+}
diff --git a/libs/usb/tests/AccessoryChat/res/layout/accessory_chat.xml b/libs/usb/tests/AccessoryChat/res/layout/accessory_chat.xml
new file mode 100644
index 0000000..596ecbf
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/res/layout/accessory_chat.xml
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical"
+    >
+
+    <ScrollView android:id="@+id/scroll"
+        android:layout_width="match_parent"
+        android:layout_height="0px"
+        android:layout_weight="1"
+        >
+        <TextView android:id="@+id/log"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_marginTop="25dp"
+            android:textSize="12sp"
+            android:textColor="#ffffffff"
+            />
+    </ScrollView>
+
+    <EditText android:id="@+id/message"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:capitalize="sentences"
+        android:autoText="true"
+        android:singleLine="true"
+        />
+
+</LinearLayout>
+
+
diff --git a/libs/usb/tests/AccessoryChat/res/xml/accessory_filter.xml b/libs/usb/tests/AccessoryChat/res/xml/accessory_filter.xml
new file mode 100644
index 0000000..588946f
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/res/xml/accessory_filter.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<resources>
+    <usb-accessory manufacturer="Google, Inc." model="AccessoryChat" type="Sample Program" version="1.0" />
+</resources>
diff --git a/libs/usb/tests/AccessoryChat/src/com/google/android/accessorychat/AccessoryChat.java b/libs/usb/tests/AccessoryChat/src/com/google/android/accessorychat/AccessoryChat.java
new file mode 100644
index 0000000..0a5701c
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/src/com/google/android/accessorychat/AccessoryChat.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.android.accessorychat;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.ParcelFileDescriptor;
+import android.view.KeyEvent;
+import android.view.View;
+import android.view.inputmethod.EditorInfo;
+import android.util.Log;
+import android.widget.EditText;
+import android.widget.TextView;
+
+import com.google.android.usb.UsbAccessory;
+import com.google.android.usb.UsbManager;
+
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+public class AccessoryChat extends Activity implements Runnable, TextView.OnEditorActionListener {
+
+    private static final String TAG = "AccessoryChat";
+    TextView mLog;
+    EditText mEditText;
+    ParcelFileDescriptor mFileDescriptor;
+    FileInputStream mInputStream;
+    FileOutputStream mOutputStream;
+
+    private static final int MESSAGE_LOG = 1;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        setContentView(R.layout.accessory_chat);
+        mLog = (TextView)findViewById(R.id.log);
+        mEditText = (EditText)findViewById(R.id.message);
+        mEditText.setOnEditorActionListener(this);
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+
+        Intent intent = getIntent();
+        Log.d(TAG, "intent: " + intent);
+        UsbManager manager = UsbManager.getInstance();
+        UsbAccessory[] accessories = manager.getAccessoryList();
+        UsbAccessory accessory = (accessories == null ? null : accessories[0]);
+        if (accessory != null) {
+            mFileDescriptor = manager.openAccessory(accessory);
+            if (mFileDescriptor != null) {
+                FileDescriptor fd = mFileDescriptor.getFileDescriptor();
+                mInputStream = new FileInputStream(fd);
+                mOutputStream = new FileOutputStream(fd);
+                Thread thread = new Thread(null, this, "AccessoryChat");
+                thread.start();
+            } else {
+                Log.d(TAG, "openAccessory fail");
+            }
+        } else {
+            Log.d(TAG, "mAccessory is null");
+        }
+    }
+
+    @Override
+    public void onPause() {
+        super.onPause();
+        if (mFileDescriptor != null) {
+            try {
+                mFileDescriptor.close();
+            } catch (IOException e) {
+            } finally {
+                mFileDescriptor = null;
+            }
+        }
+    }
+
+    @Override
+    public void onDestroy() {
+       super.onDestroy();
+    }
+
+    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
+        if (actionId == EditorInfo.IME_ACTION_DONE && mOutputStream != null) {
+            try {
+                mOutputStream.write(v.getText().toString().getBytes());
+            } catch (IOException e) {
+                Log.e(TAG, "write failed", e);
+            }
+            v.setText("");
+            return true;
+        }
+        Log.d(TAG, "onEditorAction " + actionId + " event: " + event);
+        return false;
+    }
+
+    public void run() {
+        int ret = 0;
+        byte[] buffer = new byte[16384];
+        while (ret >= 0) {
+            try {
+                ret = mInputStream.read(buffer);
+            } catch (IOException e) {
+                break;
+            }
+
+            if (ret > 0) {
+                Message m = Message.obtain(mHandler, MESSAGE_LOG);
+                String text = new String(buffer, 0, ret);
+                Log.d(TAG, "chat: " + text);
+                m.obj = text;
+                mHandler.sendMessage(m);
+            }
+        }
+        Log.d(TAG, "thread out");
+    }
+
+   Handler mHandler = new Handler() {
+        @Override
+        public void handleMessage(Message msg) {
+            switch (msg.what) {
+                case MESSAGE_LOG:
+                    mLog.setText(mLog.getText() + "\n" + (String)msg.obj);
+                    break;
+             }
+        }
+    };
+}
+
+
diff --git a/media/tests/CameraBrowser/AndroidManifest.xml b/media/tests/CameraBrowser/AndroidManifest.xml
index f167f4b..fccb3ca 100644
--- a/media/tests/CameraBrowser/AndroidManifest.xml
+++ b/media/tests/CameraBrowser/AndroidManifest.xml
@@ -2,7 +2,6 @@
     package="com.android.camerabrowser">
 
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-    <uses-permission android:name="android.permission.ACCESS_USB" />
 
     <application android:label="@string/app_label"
             android:name="com.android.camerabrowser.CameraBrowserApplication">
@@ -12,20 +11,15 @@
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
+            <intent-filter>
+                <action android:name="android.hardware.action.USB_DEVICE_ATTACHED" />
+            </intent-filter>
+            <meta-data android:name="android.hardware.action.USB_DEVICE_ATTACHED"
+                android:resource="@xml/device_filter" />
         </activity>
 
         <activity android:name="StorageBrowser" />
         <activity android:name="ObjectBrowser" />
         <activity android:name="ObjectViewer" />
-
-<!--
-        <receiver android:name="UsbReceiver">
-            <intent-filter>
-                <action android:name="android.hardware.action.USB_DEVICE_ATTACHED" />
-            </intent-filter>
-        </receiver>
--->
     </application>
-
-
 </manifest>
diff --git a/media/tests/CameraBrowser/res/xml/device_filter.xml b/media/tests/CameraBrowser/res/xml/device_filter.xml
new file mode 100644
index 0000000..36cd13d
--- /dev/null
+++ b/media/tests/CameraBrowser/res/xml/device_filter.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<resources>
+    <!-- filter for PTP devices -->
+    <usb-device class="6" subclass="1" protocol="1" />
+</resources>
diff --git a/media/tests/CameraBrowser/src/com/android/camerabrowser/UsbReceiver.java b/media/tests/CameraBrowser/src/com/android/camerabrowser/UsbReceiver.java
deleted file mode 100644
index 22d9443..0000000
--- a/media/tests/CameraBrowser/src/com/android/camerabrowser/UsbReceiver.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.camerabrowser;
-
-import android.content.Context;
-import android.content.Intent;
-import android.content.BroadcastReceiver;
-import android.hardware.UsbDevice;
-import android.hardware.UsbManager;
-import android.mtp.MtpClient;
-import android.os.Bundle;
-import android.os.Parcelable;
-import android.util.Log;
-
-public class UsbReceiver extends BroadcastReceiver
-{
-    private static final String TAG = "UsbReceiver";
-
-    @Override
-    public void onReceive(Context context, Intent intent) {
-        Log.d(TAG, "onReceive " + intent);
-        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(intent.getAction())) {
-            UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
-            if (MtpClient.isCamera(device)) {
-                String deviceName = device.getDeviceName();
-                Log.d(TAG, "Got camera: " + deviceName);
-                intent = new Intent(context, StorageBrowser.class);
-                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-                intent.putExtra("device", deviceName);
-                context.startActivity(intent);
-            }
-        }
-    }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
index ad57b39..35ae118 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
@@ -39,6 +39,7 @@
 import android.os.Message;
 import android.os.Messenger;
 import android.os.RemoteException;
+import android.os.SystemProperties;
 import android.provider.Settings;
 import android.provider.Telephony;
 import android.telephony.PhoneStateListener;
@@ -92,7 +93,7 @@
     boolean mWifiEnabled, mWifiConnected;
     int mWifiLevel;
     String mWifiSsid;
-    int mWifiIconId;
+    int mWifiIconId = 0;
 
     // bluetooth
     private boolean mBluetoothTethered = false;
@@ -130,6 +131,9 @@
     public NetworkController(Context context) {
         mContext = context;
 
+        // set up the default wifi icon, used when no radios have ever appeared
+        updateWifiIcons();
+
         // telephony
         mPhone = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
         mPhone.listen(mPhoneStateListener,
@@ -272,6 +276,10 @@
             }
             mDataState = state;
             mDataNetType = networkType;
+            if (state < 0) {
+                // device without a data connection
+                mSignalStrength = null;
+            }
             updateDataNetType();
             updateDataIcon();
             refreshViews();
@@ -330,6 +338,11 @@
         }
     }
 
+    private boolean hasMobileDataFeature() {
+        // XXX: HAX: replace when a more reliable method is available
+        return (! "wifi-only".equals(SystemProperties.get("ro.carrier")));
+    }
+
     private final void updateTelephonySignalStrength() {
         // Display signal strength while in "emergency calls only" mode
         if (mServiceState == null || (!hasService() && !mServiceState.isEmergencyOnly())) {
@@ -708,11 +721,13 @@
             dataTypeIconId = 0;
         } else {
             label = context.getString(R.string.status_bar_settings_signal_meter_disconnected);
-            combinedSignalIconId = mDataSignalIconId;
+            // On devices without mobile radios, we want to show the wifi icon
+            combinedSignalIconId =
+                hasMobileDataFeature() ? mDataSignalIconId : mWifiIconId;
             dataTypeIconId = 0;
         }
 
-        if (false) {
+        if (DEBUG) {
             Slog.d(TAG, "refreshViews combinedSignalIconId=0x"
                     + Integer.toHexString(combinedSignalIconId)
                     + "/" + getResourceName(combinedSignalIconId)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/WifiIcons.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/WifiIcons.java
index 0787289..8d72eba 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/WifiIcons.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/WifiIcons.java
@@ -20,11 +20,13 @@
 
 class WifiIcons {
     static final int[][] WIFI_SIGNAL_STRENGTH = {
-            { R.drawable.stat_sys_wifi_signal_1,
+            { R.drawable.stat_sys_wifi_signal_0,
+              R.drawable.stat_sys_wifi_signal_1,
               R.drawable.stat_sys_wifi_signal_2,
               R.drawable.stat_sys_wifi_signal_3,
               R.drawable.stat_sys_wifi_signal_4 },
-            { R.drawable.stat_sys_wifi_signal_1_fully,
+            { R.drawable.stat_sys_wifi_signal_0,
+              R.drawable.stat_sys_wifi_signal_1_fully,
               R.drawable.stat_sys_wifi_signal_2_fully,
               R.drawable.stat_sys_wifi_signal_3_fully,
               R.drawable.stat_sys_wifi_signal_4_fully }
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindow.java b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
index b746c37..d342d669 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindow.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
@@ -1601,6 +1601,7 @@
         private ActionMode mActionMode;
         private ActionBarContextView mActionModeView;
         private PopupWindow mActionModePopup;
+        private Runnable mShowActionModePopup;
 
         public DecorView(Context context, int featureId) {
             super(context);
@@ -1976,6 +1977,12 @@
                         final int height = TypedValue.complexToDimensionPixelSize(heightValue.data,
                                 mContext.getResources().getDisplayMetrics());
                         mActionModePopup.setHeight(height);
+                        mShowActionModePopup = new Runnable() {
+                            public void run() {
+                                mActionModePopup.showAtLocation(PhoneWindow.DecorView.this,
+                                        Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
+                            }
+                        };
                     } else {
                         ViewStub stub = (ViewStub) findViewById(
                                 com.android.internal.R.id.action_mode_bar_stub);
@@ -1994,8 +2001,7 @@
                         mActionModeView.setVisibility(View.VISIBLE);
                         mActionMode = mode;
                         if (mActionModePopup != null) {
-                            mActionModePopup.showAtLocation(this,
-                                    Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
+                            post(mShowActionModePopup);
                         }
                     } else {
                         mActionMode = null;
@@ -2183,6 +2189,14 @@
                 }
                 mActionButtonPopup = null;
             }
+
+            if (mActionModePopup != null) {
+                removeCallbacks(mShowActionModePopup);
+                if (mActionModePopup.isShowing()) {
+                    mActionModePopup.dismiss();
+                }
+                mActionModePopup = null;
+            }
         }
 
         @Override
@@ -2246,6 +2260,7 @@
             public void onDestroyActionMode(ActionMode mode) {
                 mWrapped.onDestroyActionMode(mode);
                 if (mActionModePopup != null) {
+                    removeCallbacks(mShowActionModePopup);
                     mActionModePopup.dismiss();
                 } else if (mActionModeView != null) {
                     mActionModeView.setVisibility(GONE);
diff --git a/tools/aapt/NOTICE b/tools/aapt/NOTICE
new file mode 100644
index 0000000..c5b1efa
--- /dev/null
+++ b/tools/aapt/NOTICE
@@ -0,0 +1,190 @@
+
+   Copyright (c) 2005-2008, The Android Open Source Project
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+
+   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.
+
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
diff --git a/tools/aidl/NOTICE b/tools/aidl/NOTICE
new file mode 100644
index 0000000..c5b1efa
--- /dev/null
+++ b/tools/aidl/NOTICE
@@ -0,0 +1,190 @@
+
+   Copyright (c) 2005-2008, The Android Open Source Project
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+
+   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.
+
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
diff --git a/wifi/java/android/net/wifi/WifiStateMachine.java b/wifi/java/android/net/wifi/WifiStateMachine.java
index 676218e..f9d2772 100644
--- a/wifi/java/android/net/wifi/WifiStateMachine.java
+++ b/wifi/java/android/net/wifi/WifiStateMachine.java
@@ -2785,11 +2785,30 @@
 
     class DisconnectedState extends HierarchicalState {
         private boolean mAlarmEnabled = false;
+        private long mScanIntervalMs;
+
+        private void setScanAlarm(boolean enabled) {
+            if (enabled == mAlarmEnabled) return;
+            if (enabled) {
+                mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
+                        System.currentTimeMillis() + mScanIntervalMs,
+                        mScanIntervalMs,
+                        mScanIntent);
+
+                mAlarmEnabled = true;
+            } else {
+                mAlarmManager.cancel(mScanIntent);
+                mAlarmEnabled = false;
+            }
+        }
+
         @Override
         public void enter() {
             if (DBG) Log.d(TAG, getName() + "\n");
             EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
 
+            mScanIntervalMs = Settings.Secure.getLong(mContext.getContentResolver(),
+                    Settings.Secure.WIFI_SCAN_INTERVAL_MS, DEFAULT_SCAN_INTERVAL_MS);
             /*
              * We initiate background scanning if it is enabled, otherwise we
              * initiate an infrequent scan that wakes up the device to ensure
@@ -2806,12 +2825,7 @@
                     WifiNative.enableBackgroundScan(true);
                 }
             } else {
-                long scanMs = Settings.Secure.getLong(mContext.getContentResolver(),
-                    Settings.Secure.WIFI_SCAN_INTERVAL_MS, DEFAULT_SCAN_INTERVAL_MS);
-
-                mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
-                    System.currentTimeMillis() + scanMs, scanMs, mScanIntent);
-                mAlarmEnabled = true;
+                setScanAlarm(true);
             }
         }
         @Override
@@ -2829,7 +2843,13 @@
                     break;
                 case CMD_ENABLE_BACKGROUND_SCAN:
                     mEnableBackgroundScan = (message.arg1 == 1);
-                    WifiNative.enableBackgroundScan(mEnableBackgroundScan);
+                    if (mEnableBackgroundScan) {
+                        WifiNative.enableBackgroundScan(true);
+                        setScanAlarm(false);
+                    } else {
+                        WifiNative.enableBackgroundScan(false);
+                        setScanAlarm(true);
+                    }
                     break;
                     /* Ignore network disconnect */
                 case NETWORK_DISCONNECTION_EVENT:
@@ -2866,10 +2886,7 @@
             if (mEnableBackgroundScan) {
                 WifiNative.enableBackgroundScan(false);
             }
-            if (mAlarmEnabled) {
-                mAlarmManager.cancel(mScanIntent);
-                mAlarmEnabled = false;
-            }
+            setScanAlarm(false);
         }
     }