Merge "Use CONNECTIVITY_INTERNAL for global proxy" into jb-mr2-dev
diff --git a/Android.mk b/Android.mk
index e70f9f3..8115472 100644
--- a/Android.mk
+++ b/Android.mk
@@ -124,6 +124,8 @@
 	core/java/android/hardware/display/IDisplayManagerCallback.aidl \
 	core/java/android/hardware/input/IInputManager.aidl \
 	core/java/android/hardware/input/IInputDevicesChangedListener.aidl \
+	core/java/android/hardware/location/IGeofenceHardware.aidl \
+	core/java/android/hardware/location/IGeofenceHardwareCallback.aidl \
 	core/java/android/hardware/usb/IUsbManager.aidl \
 	core/java/android/net/IConnectivityManager.aidl \
 	core/java/android/net/INetworkManagementEventObserver.aidl \
@@ -207,10 +209,12 @@
 	location/java/android/location/ICountryDetector.aidl \
 	location/java/android/location/ICountryListener.aidl \
 	location/java/android/location/IGeocodeProvider.aidl \
+	location/java/android/location/IGeofenceProvider.aidl \
 	location/java/android/location/IGpsStatusListener.aidl \
 	location/java/android/location/IGpsStatusProvider.aidl \
 	location/java/android/location/ILocationListener.aidl \
 	location/java/android/location/ILocationManager.aidl \
+	location/java/android/location/IGpsGeofenceHardware.aidl \
 	location/java/android/location/INetInitiatedListener.aidl \
 	location/java/com/android/internal/location/ILocationProvider.aidl \
 	media/java/android/media/IAudioService.aidl \
@@ -438,6 +442,7 @@
     -since $(SRC_API_DIR)/15.txt 15 \
     -since $(SRC_API_DIR)/16.txt 16 \
     -since $(SRC_API_DIR)/17.txt 17 \
+    -since $(SRC_API_DIR)/18.txt 18 \
 		-werror -hide 113 \
 		-overview $(LOCAL_PATH)/core/java/overview.html
 
diff --git a/api/current.txt b/api/current.txt
index 5ac9a65..9ed1b3c 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -69,6 +69,7 @@
     field public static final java.lang.String INTERNAL_SYSTEM_WINDOW = "android.permission.INTERNAL_SYSTEM_WINDOW";
     field public static final java.lang.String INTERNET = "android.permission.INTERNET";
     field public static final java.lang.String KILL_BACKGROUND_PROCESSES = "android.permission.KILL_BACKGROUND_PROCESSES";
+    field public static final java.lang.String LOCATION_HARDWARE = "android.permission.LOCATION_HARDWARE";
     field public static final java.lang.String MANAGE_ACCOUNTS = "android.permission.MANAGE_ACCOUNTS";
     field public static final java.lang.String MANAGE_APP_TOKENS = "android.permission.MANAGE_APP_TOKENS";
     field public static final java.lang.String MASTER_CLEAR = "android.permission.MASTER_CLEAR";
@@ -5017,6 +5018,7 @@
     method public boolean addService(android.bluetooth.BluetoothGattService);
     method public void cancelConnection(android.bluetooth.BluetoothDevice);
     method public void clearServices();
+    method public void close();
     method public boolean connect(android.bluetooth.BluetoothDevice, boolean);
     method public java.util.List<android.bluetooth.BluetoothDevice> getConnectedDevices();
     method public int getConnectionState(android.bluetooth.BluetoothDevice);
@@ -6863,7 +6865,6 @@
     method public abstract boolean addPermission(android.content.pm.PermissionInfo);
     method public abstract boolean addPermissionAsync(android.content.pm.PermissionInfo);
     method public abstract deprecated void addPreferredActivity(android.content.IntentFilter, int, android.content.ComponentName[], android.content.ComponentName);
-    method public android.content.Intent buildPermissionRequestIntent(java.lang.String...);
     method public abstract java.lang.String[] canonicalToCurrentPackageNames(java.lang.String[]);
     method public abstract int checkPermission(java.lang.String, java.lang.String);
     method public abstract int checkSignatures(java.lang.String, java.lang.String);
@@ -10294,16 +10295,20 @@
     field public static final int TYPE_ACCELEROMETER = 1; // 0x1
     field public static final int TYPE_ALL = -1; // 0xffffffff
     field public static final int TYPE_AMBIENT_TEMPERATURE = 13; // 0xd
+    field public static final int TYPE_GAME_ROTATION_VECTOR = 15; // 0xf
     field public static final int TYPE_GRAVITY = 9; // 0x9
     field public static final int TYPE_GYROSCOPE = 4; // 0x4
+    field public static final int TYPE_GYROSCOPE_UNCALIBRATED = 16; // 0x10
     field public static final int TYPE_LIGHT = 5; // 0x5
     field public static final int TYPE_LINEAR_ACCELERATION = 10; // 0xa
     field public static final int TYPE_MAGNETIC_FIELD = 2; // 0x2
+    field public static final int TYPE_MAGNETIC_FIELD_UNCALIBRATED = 14; // 0xe
     field public static final deprecated int TYPE_ORIENTATION = 3; // 0x3
     field public static final int TYPE_PRESSURE = 6; // 0x6
     field public static final int TYPE_PROXIMITY = 8; // 0x8
     field public static final int TYPE_RELATIVE_HUMIDITY = 12; // 0xc
     field public static final int TYPE_ROTATION_VECTOR = 11; // 0xb
+    field public static final int TYPE_SIGNIFICANT_MOTION = 17; // 0x11
     field public static final deprecated int TYPE_TEMPERATURE = 7; // 0x7
   }
 
@@ -10325,6 +10330,7 @@
   }
 
   public abstract class SensorManager {
+    method public boolean cancelTriggerSensor(android.hardware.TriggerEventListener, android.hardware.Sensor);
     method public static float getAltitude(float, float);
     method public static void getAngleChange(float[], float[], float[]);
     method public android.hardware.Sensor getDefaultSensor(int);
@@ -10340,6 +10346,7 @@
     method public boolean registerListener(android.hardware.SensorEventListener, android.hardware.Sensor, int);
     method public boolean registerListener(android.hardware.SensorEventListener, android.hardware.Sensor, int, android.os.Handler);
     method public static boolean remapCoordinateSystem(float[], int, int, float[]);
+    method public boolean requestTriggerSensor(android.hardware.TriggerEventListener, android.hardware.Sensor);
     method public deprecated void unregisterListener(android.hardware.SensorListener);
     method public deprecated void unregisterListener(android.hardware.SensorListener, int);
     method public void unregisterListener(android.hardware.SensorEventListener, android.hardware.Sensor);
@@ -10403,6 +10410,17 @@
     field public static final float STANDARD_GRAVITY = 9.80665f;
   }
 
+  public final class TriggerEvent {
+    field public android.hardware.Sensor sensor;
+    field public long timestamp;
+    field public final float[] values;
+  }
+
+  public abstract class TriggerEventListener {
+    ctor public TriggerEventListener();
+    method public abstract void onTrigger(android.hardware.TriggerEvent);
+  }
+
 }
 
 package android.hardware.display {
@@ -10443,6 +10461,43 @@
 
 }
 
+package android.hardware.location {
+
+  public final class GeofenceHardware {
+    method public boolean addCircularFence(int, double, double, double, int, int, int, int, int, android.hardware.location.GeofenceHardwareCallback);
+    method public int[] getMonitoringTypesAndStatus();
+    method public boolean pauseGeofence(int, int);
+    method public boolean registerForMonitorStateChangeCallback(int, android.hardware.location.GeofenceHardwareCallback);
+    method public boolean removeGeofence(int, int);
+    method public boolean resumeGeofence(int, int, int);
+    method public boolean unregisterForMonitorStateChangeCallback(int, android.hardware.location.GeofenceHardwareCallback);
+    field public static final int GEOFENCE_ENTERED = 1; // 0x1
+    field public static final int GEOFENCE_ERROR_ID_EXISTS = 2; // 0x2
+    field public static final int GEOFENCE_ERROR_ID_UNKNOWN = 3; // 0x3
+    field public static final int GEOFENCE_ERROR_INVALID_TRANSITION = 4; // 0x4
+    field public static final int GEOFENCE_ERROR_TOO_MANY_GEOFENCES = 1; // 0x1
+    field public static final int GEOFENCE_EXITED = 2; // 0x2
+    field public static final int GEOFENCE_FAILURE = 5; // 0x5
+    field public static final int GEOFENCE_SUCCESS = 0; // 0x0
+    field public static final int GEOFENCE_UNCERTAIN = 4; // 0x4
+    field public static final int MONITORING_TYPE_GPS_HARDWARE = 0; // 0x0
+    field public static final int MONITOR_CURRENTLY_AVAILABLE = 0; // 0x0
+    field public static final int MONITOR_CURRENTLY_UNAVAILABLE = 1; // 0x1
+    field public static final int MONITOR_UNSUPPORTED = 2; // 0x2
+  }
+
+  public abstract class GeofenceHardwareCallback {
+    ctor public GeofenceHardwareCallback();
+    method public void onGeofenceAdd(int, int);
+    method public void onGeofenceChange(int, int, android.location.Location, long, int);
+    method public void onGeofencePause(int, int);
+    method public void onGeofenceRemove(int, int);
+    method public void onGeofenceResume(int, int);
+    method public void onMonitoringSystemChange(int, boolean, android.location.Location);
+  }
+
+}
+
 package android.hardware.usb {
 
   public class UsbAccessory implements android.os.Parcelable {
@@ -16988,6 +17043,11 @@
     method public abstract void released();
   }
 
+  public final class Trace {
+    method public static void beginSection(java.lang.String);
+    method public static void endSection();
+  }
+
   public class TransactionTooLargeException extends android.os.RemoteException {
     ctor public TransactionTooLargeException();
   }
diff --git a/core/java/android/accounts/CantAddAccountActivity.java b/core/java/android/accounts/CantAddAccountActivity.java
new file mode 100644
index 0000000..e1717a6
--- /dev/null
+++ b/core/java/android/accounts/CantAddAccountActivity.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.accounts;
+
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.view.View;
+
+import com.android.internal.R;
+
+/**
+ * @hide
+ * Just shows an error message about the account restrictions for the limited user.
+ */
+public class CantAddAccountActivity extends Activity {
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.app_not_authorized);
+    }
+
+    public void onCancelButtonClicked(View view) {
+        onBackPressed();
+    }
+}
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index 19d495b..3fc82fa 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -449,7 +449,8 @@
 
         registerService(SENSOR_SERVICE, new ServiceFetcher() {
                 public Object createService(ContextImpl ctx) {
-                    return new SystemSensorManager(ctx.mMainThread.getHandler().getLooper());
+                    return new SystemSensorManager(ctx.getOuterContext(),
+                      ctx.mMainThread.getHandler().getLooper());
                 }});
 
         registerService(STATUS_BAR_SERVICE, new ServiceFetcher() {
diff --git a/core/java/android/bluetooth/BluetoothGattServer.java b/core/java/android/bluetooth/BluetoothGattServer.java
index 644c619b..d7f150b 100644
--- a/core/java/android/bluetooth/BluetoothGattServer.java
+++ b/core/java/android/bluetooth/BluetoothGattServer.java
@@ -288,9 +288,9 @@
     }
 
     /**
-     * Close the connection to the gatt service.
+     * Close this GATT server instance.
      */
-    /*package*/ void close() {
+    public void close() {
         if (DBG) Log.d(TAG, "close()");
         unregisterCallback();
     }
diff --git a/core/java/android/content/pm/PackageInfo.java b/core/java/android/content/pm/PackageInfo.java
index fb539c5..33a6757 100644
--- a/core/java/android/content/pm/PackageInfo.java
+++ b/core/java/android/content/pm/PackageInfo.java
@@ -154,7 +154,7 @@
     /**
      * Flag for {@link #requestedPermissionsFlags}: the requested permission
      * is required for the application to run; the user can not optionally
-     * disable it.
+     * disable it.  Currently all permissions are required.
      */
     public static final int REQUESTED_PERMISSION_REQUIRED = 1<<0;
 
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index da15e3b..30bdfef 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -1754,6 +1754,7 @@
     /**
      * Returns an {@link Intent} suitable for passing to {@code startActivityForResult}
      * which prompts the user to grant {@code permissions} to this application.
+     * @hide
      *
      * @throws NullPointerException if {@code permissions} is {@code null}.
      * @throws IllegalArgumentException if {@code permissions} contains {@code null}.
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index 384aed8..5a50ec2 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -1407,8 +1407,11 @@
         // that may change.
         String name = sa.getNonResourceString(
                 com.android.internal.R.styleable.AndroidManifestUsesPermission_name);
+/*
         boolean required = sa.getBoolean(
                 com.android.internal.R.styleable.AndroidManifestUsesPermission_required, true);
+*/
+        boolean required = true; // Optional <uses-permission> not supported
 
         sa.recycle();
 
diff --git a/core/java/android/hardware/Sensor.java b/core/java/android/hardware/Sensor.java
index 41384d2..074f8fe 100644
--- a/core/java/android/hardware/Sensor.java
+++ b/core/java/android/hardware/Sensor.java
@@ -17,6 +17,8 @@
 
 package android.hardware;
 
+import android.os.Build;
+
 /**
  * Class representing a sensor. Use {@link SensorManager#getSensorList} to get
  * the list of available Sensors.
@@ -114,11 +116,112 @@
     /** A constant describing an ambient temperature sensor type */
     public static final int TYPE_AMBIENT_TEMPERATURE = 13;
 
-    /** 
+    /**
+     * A constant describing a magnetic field uncalibrated sensor type. See
+     * {@link android.hardware.SensorEvent#values SensorEvent.values} for more
+     * details.
+     * <p>
+     * Similar to {@link #TYPE_MAGNETIC_FIELD} but the hard iron calibration (calibration
+     * due to distortions that arise from magnetized iron, steel or permanenet magnets
+     * on the device) is reported separately. No periodic calibration is performed
+     * (i.e. there are no discontinuities in the data stream while using this sensor).
+     * Assumptions that the magnetic field is due to the Earth's poles is avoided.
+     * Factory calibration and temperature compensation are still performed.
+     * </p>
+     */
+    public static final int TYPE_MAGNETIC_FIELD_UNCALIBRATED = 14;
+
+    /**
+     * Identical to {@link #TYPE_ROTATION_VECTOR} except that it doesn't
+     * use the geomagnetic field. Therefore the Y axis doesn't
+     * point north, but instead to some other reference, that reference is
+     * allowed to drift by the same order of magnitude as the gyroscope
+     * drift around the Z axis.
+     * <p>
+     * In the ideal case, a phone rotated and returning to the same real-world
+     * orientation should report the same game rotation vector
+     * (without using the earth's geomagnetic field). However, the orientation
+     * may drift somewhat over time.
+     * </p>
+     */
+
+    public static final int TYPE_GAME_ROTATION_VECTOR = 15;
+
+    /**
+     * A constant describing a gyroscope uncalibrated sensor type. See
+     * {@link android.hardware.SensorEvent#values SensorEvent.values} for more
+     * details.
+     * <p>
+     * No gyro-drift compensation is performed.
+     * Factory calibration and temperature compensation is still applied
+     * to the rate of rotation (angular speeds).
+     * </p>
+     */
+    public static final int TYPE_GYROSCOPE_UNCALIBRATED = 16;
+
+    /**
+     * A constant describing the significant motion trigger sensor.
+     * See {@link android.hardware.SensorEvent#values} for more details.
+     * <p>
+     * It triggers when an event occurs and then automatically disables
+     * itself. The sensor continues to operate while the device is asleep
+     * and will automatically wake the device to notify when significant
+     * motion is detected. The application does not need to hold any wake
+     * locks for this sensor to trigger.
+     * </p>
+     */
+    public static final int TYPE_SIGNIFICANT_MOTION = 17;
+
+    /**
      * A constant describing all sensor types.
      */
     public static final int TYPE_ALL = -1;
 
+    /* Reporting mode constants for sensors. Each sensor will have exactly one
+       reporting mode associated with it. */
+    // Events are reported at a constant rate.
+    static int REPORTING_MODE_CONTINUOUS = 1;
+
+    // Events are reported only when the value changes.
+    static int REPORTING_MODE_ON_CHANGE = 2;
+
+    // Upon detection of an event, the sensor deactivates itself and then sends a single event.
+    static int REPORTING_MODE_ONE_SHOT = 3;
+
+    // Note: This needs to be updated, whenever a new sensor is added.
+    private static int[] sSensorReportingModes = {
+            REPORTING_MODE_CONTINUOUS, REPORTING_MODE_CONTINUOUS, REPORTING_MODE_CONTINUOUS,
+            REPORTING_MODE_CONTINUOUS, REPORTING_MODE_ON_CHANGE, REPORTING_MODE_CONTINUOUS,
+            REPORTING_MODE_ON_CHANGE, REPORTING_MODE_ON_CHANGE, REPORTING_MODE_CONTINUOUS,
+            REPORTING_MODE_CONTINUOUS, REPORTING_MODE_CONTINUOUS, REPORTING_MODE_ON_CHANGE,
+            REPORTING_MODE_ON_CHANGE, REPORTING_MODE_CONTINUOUS, REPORTING_MODE_CONTINUOUS,
+            REPORTING_MODE_CONTINUOUS, REPORTING_MODE_ONE_SHOT };
+
+    // Note: This needs to be updated, whenever a new sensor is added.
+    // Holds the maximum length of the values array associated with {@link SensorEvent} or
+    // {@link TriggerEvent} for the Sensor
+    private static int[] sMaxLengthValuesArray = {
+            3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 3, 3, 3,
+            6, 4, 6, 1 };
+
+    static int getReportingMode(Sensor sensor) {
+        // mType starts from offset 1.
+        return sSensorReportingModes[sensor.mType - 1];
+    }
+
+    static int getMaxLengthValuesArray(Sensor sensor, int sdkLevel) {
+        // mType starts from offset 1.
+        int len = sMaxLengthValuesArray[sensor.mType - 1];
+
+        // RotationVector length has changed to 3 to 5 for API level 18
+        // Set it to 3 for backward compatibility.
+        if (sensor.getType() == Sensor.TYPE_ROTATION_VECTOR &&
+                sdkLevel <= Build.VERSION_CODES.JELLY_BEAN_MR1) {
+            len = 3;
+        }
+        return len;
+    }
+
     /* Some of these fields are set only by the native bindings in
      * SensorManager.
      */
@@ -132,7 +235,6 @@
     private float   mPower;
     private int     mMinDelay;
 
-
     Sensor() {
     }
 
diff --git a/core/java/android/hardware/SensorEvent.java b/core/java/android/hardware/SensorEvent.java
index 51a17c1..012ae7e 100644
--- a/core/java/android/hardware/SensorEvent.java
+++ b/core/java/android/hardware/SensorEvent.java
@@ -17,11 +17,9 @@
 package android.hardware;
 
 /**
- * <p>
  * This class represents a {@link android.hardware.Sensor Sensor} event and
  * holds informations such as the sensor's type, the time-stamp, accuracy and of
  * course the sensor's {@link SensorEvent#values data}.
- * </p>
  *
  * <p>
  * <u>Definition of the coordinate system used by the SensorEvent API.</u>
@@ -67,15 +65,9 @@
      * Sensor.TYPE_ACCELEROMETER}:</h4> All values are in SI units (m/s^2)
      * 
      * <ul>
-     * <p>
-     * values[0]: Acceleration minus Gx on the x-axis
-     * </p>
-     * <p>
-     * values[1]: Acceleration minus Gy on the y-axis
-     * </p>
-     * <p>
-     * values[2]: Acceleration minus Gz on the z-axis
-     * </p>
+     * <li> values[0]: Acceleration minus Gx on the x-axis </li>
+     * <li> values[1]: Acceleration minus Gy on the y-axis </li>
+     * <li> values[2]: Acceleration minus Gz on the z-axis </li>
      * </ul>
      * 
      * <p>
@@ -165,15 +157,9 @@
      * definition of positive rotation and does not agree with the definition of
      * roll given earlier.
      * <ul>
-     * <p>
-     * values[0]: Angular speed around the x-axis
-     * </p>
-     * <p>
-     * values[1]: Angular speed around the y-axis
-     * </p>
-     * <p>
-     * values[2]: Angular speed around the z-axis
-     * </p>
+     * <li> values[0]: Angular speed around the x-axis </li>
+     * <li> values[1]: Angular speed around the y-axis </li>
+     * <li> values[2]: Angular speed around the z-axis </li>
      * </ul>
      * <p>
      * Typically the output of the gyroscope is integrated over time to
@@ -233,22 +219,19 @@
      * </p>
      * <h4>{@link android.hardware.Sensor#TYPE_LIGHT Sensor.TYPE_LIGHT}:</h4>
      * <ul>
-     * <p>
-     * values[0]: Ambient light level in SI lux units
+     * <li>values[0]: Ambient light level in SI lux units </li>
      * </ul>
      * 
      * <h4>{@link android.hardware.Sensor#TYPE_PRESSURE Sensor.TYPE_PRESSURE}:</h4>
      * <ul>
-     * <p>
-     * values[0]: Atmospheric pressure in hPa (millibar)
+     * <li>values[0]: Atmospheric pressure in hPa (millibar) </li>
      * </ul>
      *
      * <h4>{@link android.hardware.Sensor#TYPE_PROXIMITY Sensor.TYPE_PROXIMITY}:
      * </h4>
      * 
      * <ul>
-     * <p>
-     * values[0]: Proximity sensor distance measured in centimeters
+     * <li>values[0]: Proximity sensor distance measured in centimeters </li>
      * </ul>
      * 
      * <p>
@@ -304,39 +287,27 @@
      * </p>
      *
      * <ul>
-     * <p>
-     * values[0]: x*sin(&#952/2)
-     * </p>
-     * <p>
-     * values[1]: y*sin(&#952/2)
-     * </p>
-     * <p>
-     * values[2]: z*sin(&#952/2)
-     * </p>
-     * <p>
-     * values[3]: cos(&#952/2) <i>(optional: only if value.length = 4)</i>
-     * </p>
+     * <li> values[0]: x*sin(&#952/2) </li>
+     * <li> values[1]: y*sin(&#952/2) </li>
+     * <li> values[2]: z*sin(&#952/2) </li>
+     * <li> values[3]: cos(&#952/2) </li>
+     * <li> values[4]: estimated heading Accuracy (in radians) (-1 if unavailable)</li>
      * </ul>
+     * <p> values[3], originally optional, will always be present from SDK Level 18 onwards.
+     * values[4] is a new value that has been added in SDK Level 18.
+     * </p>
      *
      * <h4>{@link android.hardware.Sensor#TYPE_ORIENTATION
      * Sensor.TYPE_ORIENTATION}:</h4> All values are angles in degrees.
      * 
      * <ul>
-     * <p>
-     * values[0]: Azimuth, angle between the magnetic north direction and the
+     * <li> values[0]: Azimuth, angle between the magnetic north direction and the
      * y-axis, around the z-axis (0 to 359). 0=North, 90=East, 180=South,
-     * 270=West
-     * </p>
-     * 
-     * <p>
-     * values[1]: Pitch, rotation around x-axis (-180 to 180), with positive
-     * values when the z-axis moves <b>toward</b> the y-axis.
-     * </p>
-     * 
-     * <p>
-     * values[2]: Roll, rotation around y-axis (-90 to 90), with positive values
-     * when the x-axis moves <b>toward</b> the z-axis.
-     * </p>
+     * 270=West </li>
+     * <li> values[1]: Pitch, rotation around x-axis (-180 to 180), with positive
+     * values when the z-axis moves <b>toward</b> the y-axis. </li>
+     * <li> values[2]: Roll, rotation around y-axis (-90 to 90), with positive values
+     * when the x-axis moves <b>toward</b> the z-axis. </li>
      * </ul>
      * 
      * <p>
@@ -364,9 +335,7 @@
      * <h4>{@link android.hardware.Sensor#TYPE_RELATIVE_HUMIDITY
      * Sensor.TYPE_RELATIVE_HUMIDITY}:</h4>
      * <ul>
-     * <p>
-     * values[0]: Relative ambient air humidity in percent
-     * </p>
+     * <li> values[0]: Relative ambient air humidity in percent </li>
      * </ul>
      * <p>
      * When relative ambient air humidity and ambient temperature are
@@ -423,21 +392,95 @@
      * </h4>
      *
      * <ul>
-     * <p>
-     * values[0]: ambient (room) temperature in degree Celsius.
+     * <li> values[0]: ambient (room) temperature in degree Celsius.</li>
      * </ul>
      *
      * @see SensorEvent
      * @see GeomagneticField
+     *
+     * <h4>{@link android.hardware.Sensor#TYPE_MAGNETIC_FIELD_UNCALIBRATED} </h4>
+     * Similar to {@link android.hardware.Sensor#TYPE_MAGNETIC_FIELD},
+     * but the hard iron calibration is reported separately instead of being included
+     * in the measurement. Factory calibration and temperature compensation will still
+     * be applied to the "uncalibrated" measurement. Assumptions that the magnetic field
+     * is due to the Earth's poles is avoided.
+     * <p>
+     * The values array is shown below:
+     * <ul>
+     * <li> values[0] = x_uncalib </li>
+     * <li> values[1] = y_uncalib </li>
+     * <li> values[2] = z_uncalib </li>
+     * <li> values[3] = x_bias </li>
+     * <li> values[4] = y_bias </li>
+     * <li> values[5] = z_bias </li>
+     * </ul>
+     * </p>
+     * <p>
+     * x_uncalib, y_uncalib, z_uncalib are the measured magnetic field in X, Y, Z axes.
+     * Soft iron and temperature calibrations are applied. But the hard iron
+     * calibration is not applied. The values are in micro-Tesla (uT).
+     * </p>
+     * <p>
+     * x_bias, y_bias, z_bias give the iron bias estimated in X, Y, Z axes.
+     * Each field is a component of the estimated hard iron calibration.
+     * The values are in micro-Tesla (uT).
+     * </p>
+     * <p> Hard iron - These distortions arise due to the magnetized iron, steel or permanenet
+     * magnets on the device.
+     * Soft iron - These distortions arise due to the interaction with the earth's magentic
+     * field.
+     * </p>
+     * <h4> {@link android.hardware.Sensor#TYPE_GAME_ROTATION_VECTOR} </h4>
+     * Identical to {@link android.hardware.Sensor#TYPE_ROTATION_VECTOR} except that it
+     * doesn't use the geomagnetic field. Therefore the Y axis doesn't
+     * point north, but instead to some other reference, that reference is
+     * allowed to drift by the same order of magnitude as the gyroscope
+     * drift around the Z axis.
+     * <p>
+     * In the ideal case, a phone rotated and returning to the same real-world
+     * orientation will report the same game rotation vector
+     * (without using the earth's geomagnetic field). However, the orientation
+     * may drift somewhat over time. See {@link android.hardware.Sensor#TYPE_ROTATION_VECTOR}
+     * for a detailed description of the values. This sensor will not have
+     * the estimated heading accuracy value.
+     * </p>
+     *
+     * <h4> {@link android.hardware.Sensor#TYPE_GYROSCOPE_UNCALIBRATED} </h4>
+     * All values are in radians/second and measure the rate of rotation
+     * around the X, Y and Z axis. An estimation of the drift on each axis is
+     * reported as well.
+     * <p>
+     * No gyro-drift compensation is performed. Factory calibration and temperature
+     * compensation is still applied to the rate of rotation (angular speeds).
+     * </p>
+     * <p>
+     * The coordinate system is the same as is used for the
+     * {@link android.hardware.Sensor#TYPE_ACCELEROMETER}
+     * Rotation is positive in the counter-clockwise direction (right-hand rule).
+     * That is, an observer looking from some positive location on the x, y or z axis
+     * at a device positioned on the origin would report positive rotation if the device
+     * appeared to be rotating counter clockwise.
+     * The range would at least be 17.45 rad/s (ie: ~1000 deg/s).
+     * <ul>
+     * <li> values[0] : angular speed (w/o drift compensation) around the X axis in rad/s </li>
+     * <li> values[1] : angular speed (w/o drift compensation) around the Y axis in rad/s </li>
+     * <li> values[2] : angular speed (w/o drift compensation) around the Z axis in rad/s </li>
+     * <li> values[3] : estimated drift around X axis in rad/s </li>
+     * <li> values[4] : estimated drift around Y axis in rad/s </li>
+     * <li> values[5] : estimated drift around Z axis in rad/s </li>
+     * </ul>
+     * </p>
+     * <h4></h4>
+     * <h4> Pro Tip: Always use the length of the values array while performing operations
+     * on it. In earlier versions, this used to be always 3 which has changed now. </h4>
      */
-
     public final float[] values;
 
     /**
      * The sensor that generated this event. See
      * {@link android.hardware.SensorManager SensorManager} for details.
      */
-   public Sensor sensor;
+    public Sensor sensor;
 
     /**
      * The accuracy of this event. See {@link android.hardware.SensorManager
@@ -445,14 +488,12 @@
      */
     public int accuracy;
 
-
     /**
      * The time in nanosecond at which the event happened
      */
     public long timestamp;
 
-
-    SensorEvent(int size) {
-        values = new float[size];
+    SensorEvent(int valueSize) {
+        values = new float[valueSize];
     }
 }
diff --git a/core/java/android/hardware/SensorManager.java b/core/java/android/hardware/SensorManager.java
index 7f94794..37cbe04 100644
--- a/core/java/android/hardware/SensorManager.java
+++ b/core/java/android/hardware/SensorManager.java
@@ -38,7 +38,11 @@
  * hours. Note that the system will <i>not</i> disable sensors automatically when
  * the screen turns off.
  * </p>
- *
+ * <p class="note">
+ * Note: Don't use this mechanism with a Trigger Sensor, have a look
+ * at {@link TriggerEventListener}. {@link Sensor#TYPE_SIGNIFICANT_MOTION}
+ * is an example of a trigger sensor.
+ * </p>
  * <pre class="prettyprint">
  * public class SensorActivity extends Activity, implements SensorEventListener {
  *     private final SensorManager mSensorManager;
@@ -515,6 +519,12 @@
     /**
      * Unregisters a listener for the sensors with which it is registered.
      *
+     * <p class="note"></p>
+     * Note: Don't use this method with a one shot trigger sensor such as
+     * {@link Sensor#TYPE_SIGNIFICANT_MOTION}.
+     * Use {@link #cancelTriggerSensor(TriggerEventListener, Sensor)} instead.
+     * </p>
+     *
      * @param listener
      *        a SensorEventListener object
      *
@@ -524,6 +534,7 @@
      * @see #unregisterListener(SensorEventListener)
      * @see #registerListener(SensorEventListener, Sensor, int)
      *
+     * @throws IllegalArgumentException when sensor is a trigger sensor.
      */
     public void unregisterListener(SensorEventListener listener, Sensor sensor) {
         if (listener == null || sensor == null) {
@@ -558,6 +569,12 @@
      * Registers a {@link android.hardware.SensorEventListener
      * SensorEventListener} for the given sensor.
      *
+     * <p class="note"></p>
+     * Note: Don't use this method with a one shot trigger sensor such as
+     * {@link Sensor#TYPE_SIGNIFICANT_MOTION}.
+     * Use {@link #requestTriggerSensor(TriggerEventListener, Sensor)} instead.
+     * </p>
+     *
      * @param listener
      *        A {@link android.hardware.SensorEventListener SensorEventListener}
      *        object.
@@ -584,6 +601,7 @@
      * @see #unregisterListener(SensorEventListener)
      * @see #unregisterListener(SensorEventListener, Sensor)
      *
+     * @throws IllegalArgumentException when sensor is null or a trigger sensor
      */
     public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate) {
         return registerListener(listener, sensor, rate, null);
@@ -593,6 +611,12 @@
      * Registers a {@link android.hardware.SensorEventListener
      * SensorEventListener} for the given sensor.
      *
+     * <p class="note"></p>
+     * Note: Don't use this method with a one shot trigger sensor such as
+     * {@link Sensor#TYPE_SIGNIFICANT_MOTION}.
+     * Use {@link #requestTriggerSensor(TriggerEventListener, Sensor)} instead.
+     * </p>
+     *
      * @param listener
      *        A {@link android.hardware.SensorEventListener SensorEventListener}
      *        object.
@@ -623,6 +647,7 @@
      * @see #unregisterListener(SensorEventListener)
      * @see #unregisterListener(SensorEventListener, Sensor)
      *
+     * @throws IllegalArgumentException when sensor is null or a trigger sensor
      */
     public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate,
             Handler handler) {
@@ -1310,6 +1335,68 @@
         Q[3] = rv[2];
     }
 
+    /**
+     * Requests receiving trigger events for a trigger sensor.
+     *
+     * <p>
+     * When the sensor detects a trigger event condition, such as significant motion in
+     * the case of the {@link Sensor#TYPE_SIGNIFICANT_MOTION}, the provided trigger listener
+     * will be invoked once and then its request to receive trigger events will be canceled.
+     * To continue receiving trigger events, the application must request to receive trigger
+     * events again.
+     * </p>
+     *
+     * @param listener The listener on which the
+     *        {@link TriggerEventListener#onTrigger(TriggerEvent)} will be delivered.
+     * @param sensor The sensor to be enabled.
+     *
+     * @return true if the sensor was successfully enabled.
+     *
+     * @throws IllegalArgumentException when sensor is null or not a trigger sensor.
+     */
+    public boolean requestTriggerSensor(TriggerEventListener listener, Sensor sensor) {
+        return requestTriggerSensorImpl(listener, sensor);
+    }
+
+    /**
+     * @hide
+     */
+    protected abstract boolean requestTriggerSensorImpl(TriggerEventListener listener,
+            Sensor sensor);
+
+    /**
+     * Cancels receiving trigger events for a trigger sensor.
+     *
+     * <p>
+     * Note that a Trigger sensor will be auto disabled if
+     * {@link TriggerEventListener#onTrigger(TriggerEvent)} has triggered.
+     * This method is provided in case the user wants to explicitly cancel the request
+     * to receive trigger events.
+     * </p>
+     *
+     * @param listener The listener on which the
+     *        {@link TriggerEventListener#onTrigger(TriggerEvent)}
+     *        is delivered.It should be the same as the one used
+     *        in {@link #requestTriggerSensor(TriggerEventListener, Sensor)}
+     * @param sensor The sensor for which the trigger request should be canceled.
+     *        If null, it cancels receiving trigger for all sensors associated
+     *        with the listener.
+     *
+     * @return true if successfully canceled.
+     *
+     * @throws IllegalArgumentException when sensor is a trigger sensor.
+     */
+    public boolean cancelTriggerSensor(TriggerEventListener listener, Sensor sensor) {
+        return cancelTriggerSensorImpl(listener, sensor);
+    }
+
+    /**
+     * @hide
+     */
+    protected abstract boolean cancelTriggerSensorImpl(TriggerEventListener listener,
+            Sensor sensor);
+
+
     private LegacySensorManager getLegacySensorManager() {
         synchronized (mSensorListByType) {
             if (mLegacySensorManager == null) {
diff --git a/core/java/android/hardware/SystemSensorManager.java b/core/java/android/hardware/SystemSensorManager.java
index 9591631..c6c999b 100644
--- a/core/java/android/hardware/SystemSensorManager.java
+++ b/core/java/android/hardware/SystemSensorManager.java
@@ -1,4 +1,4 @@
-/*
+    /*
  * Copyright (C) 2012 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,18 +16,18 @@
 
 package android.hardware;
 
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-
-import dalvik.system.CloseGuard;
-
+import android.content.Context;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.MessageQueue;
 import android.util.SparseArray;
 import android.util.SparseBooleanArray;
 import android.util.SparseIntArray;
+import dalvik.system.CloseGuard;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
 
 /**
  * Sensor manager implementation that communicates with the built-in
@@ -45,22 +45,19 @@
     private static final SparseArray<Sensor> sHandleToSensor = new SparseArray<Sensor>();
 
     // Listener list
-    private final ArrayList<SensorEventListenerSensorPair> mListenerDelegates = new ArrayList<SensorEventListenerSensorPair>();
-
-    // Common pool of sensor events.
-    private static SensorEventPool sPool;
+    private final HashMap<SensorEventListener, SensorEventQueue> mSensorListeners =
+            new HashMap<SensorEventListener, SensorEventQueue>();
+    private final HashMap<TriggerEventListener, TriggerEventQueue> mTriggerListeners =
+            new HashMap<TriggerEventListener, TriggerEventQueue>();
 
     // Looper associated with the context in which this instance was created.
     private final Looper mMainLooper;
-
-    // maps a SensorEventListener to a SensorEventQueue
-    private final Hashtable<SensorEventListener, SensorEventQueue> mSensorEventQueueMap;
+    private final int mTargetSdkLevel;
 
     /** {@hide} */
-    public SystemSensorManager(Looper mainLooper) {
+    public SystemSensorManager(Context context, Looper mainLooper) {
         mMainLooper = mainLooper;
-        mSensorEventQueueMap = new Hashtable<SensorEventListener, SensorEventQueue>();
-
+        mTargetSdkLevel = context.getApplicationInfo().targetSdkVersion;
         synchronized(sSensorModuleLock) {
             if (!sSensorModuleInitialized) {
                 sSensorModuleInitialized = true;
@@ -80,8 +77,6 @@
                         sHandleToSensor.append(sensor.getHandle(), sensor);
                     }
                 } while (i>0);
-
-                sPool = new SensorEventPool( sFullSensorsList.size()*2 );
             }
         }
     }
@@ -102,136 +97,145 @@
         // Invariants to preserve:
         // - one Looper per SensorEventListener
         // - one Looper per SensorEventQueue
-        // We map SensorEventListeners to a SensorEventQueue, which holds the looper
+        // We map SensorEventListener to a SensorEventQueue, which holds the looper
+        if (sensor == null) throw new IllegalArgumentException("sensor cannot be null");
 
-        if (sensor == null) throw new NullPointerException("sensor cannot be null");
+        // Trigger Sensors should use the requestTriggerSensor call.
+        if (Sensor.getReportingMode(sensor) == Sensor.REPORTING_MODE_ONE_SHOT) return false;
 
-        boolean result;
-        synchronized (mSensorEventQueueMap) {
-            // check if we already have this SensorEventListener, Sensor pair
-            // registered -- if so, we ignore the register. This is not ideal
-            // but this is what the implementation has always been doing.
-            for (SensorEventListenerSensorPair l : mListenerDelegates) {
-                if (l.isSameListenerSensorPair(listener, sensor)) {
-                    // already added, just return silently.
-                    return true;
-                }
-            }
-
-            // now find the SensorEventQueue associated to this listener
-            SensorEventQueue queue = mSensorEventQueueMap.get(listener);
-            if (queue != null) {
-                result = queue.addSensor(sensor, delay);
-                if (result) {
-                    // create a new ListenerDelegate for this pair
-                    mListenerDelegates.add(new SensorEventListenerSensorPair(listener, sensor));
-                }
-            } else {
+        synchronized (mSensorListeners) {
+            SensorEventQueue queue = mSensorListeners.get(listener);
+            if (queue == null) {
                 Looper looper = (handler != null) ? handler.getLooper() : mMainLooper;
-                queue = new SensorEventQueue(listener, looper.getQueue());
-                result = queue.addSensor(sensor, delay);
-                if (result) {
-                    // create a new ListenerDelegate for this pair
-                    mListenerDelegates.add(new SensorEventListenerSensorPair(listener, sensor));
-                    mSensorEventQueueMap.put(listener, queue);
-                } else {
+                queue = new SensorEventQueue(listener, looper, this);
+                if (!queue.addSensor(sensor, delay)) {
                     queue.dispose();
+                    return false;
                 }
+                mSensorListeners.put(listener, queue);
+                return true;
+            } else {
+                return queue.addSensor(sensor, delay);
             }
         }
-        return result;
     }
 
     /** @hide */
     @Override
     protected void unregisterListenerImpl(SensorEventListener listener, Sensor sensor) {
-        synchronized (mSensorEventQueueMap) {
+        // Trigger Sensors should use the cancelTriggerSensor call.
+        if (sensor != null && Sensor.getReportingMode(sensor) == Sensor.REPORTING_MODE_ONE_SHOT) {
+            return;
+        }
 
-            // remove this listener/sensor from our list
-            final ArrayList<SensorEventListenerSensorPair> copy =
-                    new ArrayList<SensorEventListenerSensorPair>(mListenerDelegates);
-            int lastIndex = copy.size()-1;
-            for (int i=lastIndex ; i>= 0 ; i--) {
-                if (copy.get(i).isSameListenerSensorPair(listener, sensor)) {
-                    mListenerDelegates.remove(i);
-                }
-            }
-
-            // find the SensorEventQueue associated to this SensorEventListener
-            SensorEventQueue queue = mSensorEventQueueMap.get(listener);
+        synchronized (mSensorListeners) {
+            SensorEventQueue queue = mSensorListeners.get(listener);
             if (queue != null) {
-                if (sensor != null) {
-                    queue.removeSensor(sensor);
+                boolean result;
+                if (sensor == null) {
+                    result = queue.removeAllSensors();
                 } else {
-                    queue.removeAllSensors();
+                    result = queue.removeSensor(sensor);
                 }
-                if (!queue.hasSensors()) {
-                    mSensorEventQueueMap.remove(listener);
+                if (result && !queue.hasSensors()) {
+                    mSensorListeners.remove(listener);
                     queue.dispose();
                 }
             }
         }
     }
 
+    /** @hide */
+    @Override
+    protected boolean requestTriggerSensorImpl(TriggerEventListener listener, Sensor sensor) {
+        if (sensor == null) throw new IllegalArgumentException("sensor cannot be null");
 
-    /*
-     * ListenerDelegate is essentially a SensorEventListener, Sensor pair
-     * and is associated with a single SensorEventQueue.
-     */
-    private static final class SensorEventListenerSensorPair {
-        private final SensorEventListener mSensorEventListener;
-        private final Sensor mSensor;
-        public SensorEventListenerSensorPair(SensorEventListener listener, Sensor sensor) {
-            mSensorEventListener = listener;
-            mSensor = sensor;
-        }
-        public boolean isSameListenerSensorPair(SensorEventListener listener, Sensor sensor) {
-            // if sensor is null, we match only on the listener
-            if (sensor != null) {
-                return (listener == mSensorEventListener) &&
-                        (sensor.getHandle() == mSensor.getHandle());
+        if (Sensor.getReportingMode(sensor) != Sensor.REPORTING_MODE_ONE_SHOT) return false;
+
+        synchronized (mTriggerListeners) {
+            TriggerEventQueue queue = mTriggerListeners.get(listener);
+            if (queue == null) {
+                queue = new TriggerEventQueue(listener, mMainLooper, this);
+                if (!queue.addSensor(sensor, 0)) {
+                    queue.dispose();
+                    return false;
+                }
+                mTriggerListeners.put(listener, queue);
+                return true;
             } else {
-                return (listener == mSensorEventListener);
+                return queue.addSensor(sensor, 0);
             }
         }
     }
 
+    /** @hide */
+    @Override
+    protected boolean cancelTriggerSensorImpl(TriggerEventListener listener, Sensor sensor) {
+        if (sensor != null && Sensor.getReportingMode(sensor) != Sensor.REPORTING_MODE_ONE_SHOT) {
+            return false;
+        }
+        synchronized (mTriggerListeners) {
+            TriggerEventQueue queue = mTriggerListeners.get(listener);
+            if (queue != null) {
+                boolean result;
+                if (sensor == null) {
+                    result = queue.removeAllSensors();
+                } else {
+                    result = queue.removeSensor(sensor);
+                }
+                if (result && !queue.hasSensors()) {
+                    mTriggerListeners.remove(listener);
+                    queue.dispose();
+                }
+                return result;
+            }
+            return false;
+        }
+    }
+
     /*
-     * SensorEventQueue is the communication channel with the sensor service,
-     * there is a one-to-one mapping between SensorEventQueue and
-     * SensorEventListener.
+     * BaseEventQueue is the communication channel with the sensor service,
+     * SensorEventQueue, TriggerEventQueue are subclases and there is one-to-one mapping between
+     * the queues and the listeners.
      */
-    private static final class SensorEventQueue {
-        private static native int nativeInitSensorEventQueue(SensorEventQueue eventQ, MessageQueue msgQ, float[] scratch);
+    private static abstract class BaseEventQueue {
+        private native int nativeInitBaseEventQueue(BaseEventQueue eventQ, MessageQueue msgQ,
+
+                float[] scratch);
         private static native int nativeEnableSensor(int eventQ, int handle, int us);
         private static native int nativeDisableSensor(int eventQ, int handle);
         private static native void nativeDestroySensorEventQueue(int eventQ);
         private int nSensorEventQueue;
-        private final SensorEventListener mListener;
         private final SparseBooleanArray mActiveSensors = new SparseBooleanArray();
-        private final SparseIntArray mSensorAccuracies = new SparseIntArray();
-        private final SparseBooleanArray mFirstEvent = new SparseBooleanArray();
+        protected final SparseIntArray mSensorAccuracies = new SparseIntArray();
+        protected final SparseBooleanArray mFirstEvent = new SparseBooleanArray();
         private final CloseGuard mCloseGuard = CloseGuard.get();
         private final float[] mScratch = new float[16];
+        protected final SystemSensorManager mManager;
 
-        public SensorEventQueue(SensorEventListener listener, MessageQueue msgQ) {
-            nSensorEventQueue = nativeInitSensorEventQueue(this, msgQ, mScratch);
-            mListener = listener;
+        BaseEventQueue(Looper looper, SystemSensorManager manager) {
+            nSensorEventQueue = nativeInitBaseEventQueue(this, looper.getQueue(), mScratch);
             mCloseGuard.open("dispose");
+            mManager = manager;
         }
+
         public void dispose() {
             dispose(false);
         }
 
         public boolean addSensor(Sensor sensor, int delay) {
+            // Check if already present.
+            if (mActiveSensors.get(sensor.getHandle())) return false;
+
             if (enableSensor(sensor, delay) == 0) {
                 mActiveSensors.put(sensor.getHandle(), true);
+                addSensorEvent(sensor);
                 return true;
             }
             return false;
         }
 
-        public void removeAllSensors() {
+        public boolean removeAllSensors() {
             for (int i=0 ; i<mActiveSensors.size(); i++) {
                 if (mActiveSensors.valueAt(i) == true) {
                     int handle = mActiveSensors.keyAt(i);
@@ -239,26 +243,31 @@
                     if (sensor != null) {
                         disableSensor(sensor);
                         mActiveSensors.put(handle, false);
+                        removeSensorEvent(sensor);
                     } else {
                         // it should never happen -- just ignore.
                     }
                 }
             }
+            return true;
         }
 
-        public void removeSensor(Sensor sensor) {
+        public boolean removeSensor(Sensor sensor) {
             final int handle = sensor.getHandle();
             if (mActiveSensors.get(handle)) {
                 disableSensor(sensor);
                 mActiveSensors.put(sensor.getHandle(), false);
+                removeSensorEvent(sensor);
+                return true;
             }
+            return false;
         }
 
         public boolean hasSensors() {
             // no more sensors are set
             return mActiveSensors.indexOfValue(true) >= 0;
         }
-        
+
         @Override
         protected void finalize() throws Throwable {
             try {
@@ -291,95 +300,106 @@
             if (sensor == null) throw new NullPointerException();
             return nativeDisableSensor(nSensorEventQueue, sensor.getHandle());
         }
+        protected abstract void dispatchSensorEvent(int handle, float[] values, int accuracy,
+                long timestamp);
+
+        protected abstract void addSensorEvent(Sensor sensor);
+        protected abstract void removeSensorEvent(Sensor sensor);
+    }
+
+    static final class SensorEventQueue extends BaseEventQueue {
+        private final SensorEventListener mListener;
+        private final SparseArray<SensorEvent> mSensorsEvents = new SparseArray<SensorEvent>();
+
+        public SensorEventQueue(SensorEventListener listener, Looper looper,
+                SystemSensorManager manager) {
+            super(looper, manager);
+            mListener = listener;
+        }
+
+        public void addSensorEvent(Sensor sensor) {
+            SensorEvent t = new SensorEvent(Sensor.getMaxLengthValuesArray(sensor,
+                    mManager.mTargetSdkLevel));
+            mSensorsEvents.put(sensor.getHandle(), t);
+        }
+
+        public void removeSensorEvent(Sensor sensor) {
+            mSensorsEvents.delete(sensor.getHandle());
+        }
 
         // Called from native code.
         @SuppressWarnings("unused")
-        private void dispatchSensorEvent(int handle, float[] values, int inAccuracy, long timestamp) {
-            // this is always called on the same thread.
-            final SensorEvent t = sPool.getFromPool();
-            try {
-                final Sensor sensor = sHandleToSensor.get(handle);
-                final SensorEventListener listener = mListener;
-                // FIXME: handle more than 3 values
-                System.arraycopy(values, 0, t.values, 0, 3);
-                t.timestamp = timestamp;
-                t.accuracy = inAccuracy;
-                t.sensor = sensor;
-                switch (t.sensor.getType()) {
-                    // Only report accuracy for sensors that support it.
-                    case Sensor.TYPE_MAGNETIC_FIELD:
-                    case Sensor.TYPE_ORIENTATION:
-                        // call onAccuracyChanged() only if the value changes
-                        final int accuracy = mSensorAccuracies.get(handle);
-                        if ((t.accuracy >= 0) && (accuracy != t.accuracy)) {
-                            mSensorAccuracies.put(handle, t.accuracy);
-                            listener.onAccuracyChanged(t.sensor, t.accuracy);
-                        }
-                        break;
-                    default:
-                        // For other sensors, just report the accuracy once
-                        if (mFirstEvent.get(handle) == false) {
-                            mFirstEvent.put(handle, true);
-                            listener.onAccuracyChanged(
-                                    t.sensor, SENSOR_STATUS_ACCURACY_HIGH);
-                        }
-                        break;
-                }
-                listener.onSensorChanged(t);
-            } finally {
-                sPool.returnToPool(t);
+        @Override
+        protected void dispatchSensorEvent(int handle, float[] values, int inAccuracy,
+                long timestamp) {
+            final Sensor sensor = sHandleToSensor.get(handle);
+            SensorEvent t = mSensorsEvents.get(handle);
+            // Copy from the values array.
+            System.arraycopy(values, 0, t.values, 0, t.values.length);
+            t.timestamp = timestamp;
+            t.accuracy = inAccuracy;
+            t.sensor = sensor;
+            switch (t.sensor.getType()) {
+                // Only report accuracy for sensors that support it.
+                case Sensor.TYPE_MAGNETIC_FIELD:
+                case Sensor.TYPE_ORIENTATION:
+                    // call onAccuracyChanged() only if the value changes
+                    final int accuracy = mSensorAccuracies.get(handle);
+                    if ((t.accuracy >= 0) && (accuracy != t.accuracy)) {
+                        mSensorAccuracies.put(handle, t.accuracy);
+                        mListener.onAccuracyChanged(t.sensor, t.accuracy);
+                    }
+                    break;
+                default:
+                    // For other sensors, just report the accuracy once
+                    if (mFirstEvent.get(handle) == false) {
+                        mFirstEvent.put(handle, true);
+                        mListener.onAccuracyChanged(
+                                t.sensor, SENSOR_STATUS_ACCURACY_HIGH);
+                    }
+                    break;
             }
+            mListener.onSensorChanged(t);
         }
     }
 
-    /*
-     * A dumb pool of SensorEvent
-     */
-    private static final class SensorEventPool {
-        private final int mPoolSize;
-        private final SensorEvent mPool[];
-        private int mNumItemsInPool;
+    static final class TriggerEventQueue extends BaseEventQueue {
+        private final TriggerEventListener mListener;
+        private final SparseArray<TriggerEvent> mTriggerEvents = new SparseArray<TriggerEvent>();
 
-        private SensorEvent createSensorEvent() {
-            // maximal size for all legacy events is 3
-            return new SensorEvent(3);
+        public TriggerEventQueue(TriggerEventListener listener, Looper looper,
+                SystemSensorManager manager) {
+            super(looper, manager);
+            mListener = listener;
         }
 
-        SensorEventPool(int poolSize) {
-            mPoolSize = poolSize;
-            mNumItemsInPool = poolSize;
-            mPool = new SensorEvent[poolSize];
+        public void addSensorEvent(Sensor sensor) {
+            TriggerEvent t = new TriggerEvent(Sensor.getMaxLengthValuesArray(sensor,
+                    mManager.mTargetSdkLevel));
+            mTriggerEvents.put(sensor.getHandle(), t);
         }
 
-        SensorEvent getFromPool() {
-            SensorEvent t = null;
-            synchronized (this) {
-                if (mNumItemsInPool > 0) {
-                    // remove the "top" item from the pool
-                    final int index = mPoolSize - mNumItemsInPool;
-                    t = mPool[index];
-                    mPool[index] = null;
-                    mNumItemsInPool--;
-                }
-            }
-            if (t == null) {
-                // the pool was empty or this item was removed from the pool for
-                // the first time. In any case, we need to create a new item.
-                t = createSensorEvent();
-            }
-            return t;
+        public void removeSensorEvent(Sensor sensor) {
+            mTriggerEvents.delete(sensor.getHandle());
         }
 
-        void returnToPool(SensorEvent t) {
-            synchronized (this) {
-                // is there space left in the pool?
-                if (mNumItemsInPool < mPoolSize) {
-                    // if so, return the item to the pool
-                    mNumItemsInPool++;
-                    final int index = mPoolSize - mNumItemsInPool;
-                    mPool[index] = t;
-                }
-            }
+        // Called from native code.
+        @SuppressWarnings("unused")
+        @Override
+        protected void dispatchSensorEvent(int handle, float[] values, int accuracy,
+                long timestamp) {
+            final Sensor sensor = sHandleToSensor.get(handle);
+            TriggerEvent t = mTriggerEvents.get(handle);
+
+            // Copy from the values array.
+            System.arraycopy(values, 0, t.values, 0, t.values.length);
+            t.timestamp = timestamp;
+            t.sensor = sensor;
+
+            // A trigger sensor should be auto disabled.
+            mManager.cancelTriggerSensorImpl(mListener, sensor);
+
+            mListener.onTrigger(t);
         }
     }
 }
diff --git a/core/java/android/hardware/TriggerEvent.java b/core/java/android/hardware/TriggerEvent.java
new file mode 100644
index 0000000..bdd39f3
--- /dev/null
+++ b/core/java/android/hardware/TriggerEvent.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware;
+
+/**
+ * This class represents a Trigger Event - the event
+ * associated with a Trigger Sensor. When the sensor detects a trigger
+ * event condition, such as significant motion in the case of the
+ * {@link Sensor#TYPE_SIGNIFICANT_MOTION}, the {@link TriggerEventListener}
+ * is called with the TriggerEvent. The sensor is automatically canceled
+ * after the trigger.
+ * <p>
+ * This class holds information such as the value of the sensor
+ * when the trigger happened, the timestamp along with detailed
+ * information regarding the Sensor itself.
+ * </p>
+ * @see android.hardware.SensorManager
+ * @see android.hardware.TriggerEvent
+ * @see android.hardware.Sensor
+ */
+public final class TriggerEvent {
+    /**
+     * <p>
+     * The length and contents of the {@link #values values} array depends on
+     * which {@link android.hardware.Sensor sensor} type is being monitored (see
+     * also {@link SensorEvent} for a definition of the coordinate system used).
+     * </p>
+     * <h4> {@link Sensor#TYPE_SIGNIFICANT_MOTION} </h4>
+     * The value field is of length 1. value[0] = 1.0 when the sensor triggers.
+     * 1.0 is the only allowed value.
+     */
+    public final float[] values;
+
+    /**
+     * The sensor that generated this event. See
+     * {@link android.hardware.SensorManager SensorManager} for details.
+     */
+    public Sensor sensor;
+
+    /**
+     * The time in nanosecond at which the event happened
+     */
+    public long timestamp;
+
+    TriggerEvent(int size) {
+        values = new float[size];
+    }
+}
diff --git a/core/java/android/hardware/TriggerEventListener.java b/core/java/android/hardware/TriggerEventListener.java
new file mode 100644
index 0000000..76b2796
--- /dev/null
+++ b/core/java/android/hardware/TriggerEventListener.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware;
+
+/**
+ * This class is the listener used to handle Trigger Sensors.
+ * Trigger Sensors are sensors that trigger an event and are automatically
+ * disabled. {@link Sensor#TYPE_SIGNIFICANT_MOTION} is one such example.
+ * <p>
+ * SensorManager lets you access the device's {@link android.hardware.Sensor
+ * sensors}. Get an instance of this class by calling
+ * {@link android.content.Context#getSystemService(java.lang.String)
+ * Context.getSystemService()} with the argument
+ * {@link android.content.Context#SENSOR_SERVICE}.
+ * Usage details are explained in the example below.
+ * </p>
+ *
+ * <pre class="prettyprint">
+ * class TriggerListener extends TriggerEventListener {
+ *     public void onTrigger(TriggerEvent event) {
+ *          // Do Work.
+ *
+ *     // As it is a one shot sensor, it will be canceled automatically.
+ *     // SensorManager.requestTriggerSensor(this, mSigMotion); needs to
+ *     // be called again, if needed.
+ *     }
+ * }
+ * public class SensorActivity extends Activity {
+ *     private final SensorManager mSensorManager;
+ *     private final Sensor mSigMotion;
+ *     private final TriggerEventListener mListener = new TriggerEventListener();
+ *
+ *     public SensorActivity() {
+ *         mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
+ *         mSigMotion = mSensorManager.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION);
+ *     }
+ *
+ *     protected void onResume() {
+ *         super.onResume();
+ *         mSensorManager.requestTriggerSensor(mListener, mSigMotion);
+ *     }
+ *
+ *     protected void onPause() {
+ *         super.onPause();
+ *         // Call disable to ensure that the trigger request has been canceled.
+ *         mSensorManager.cancelTriggerSensor(mListener, mSigMotion);
+ *     }
+ *
+ * }
+ * </pre>
+ *
+ * @see TriggerEvent
+ * @see Sensor
+ */
+public abstract class TriggerEventListener {
+    /**
+     * The method that will be called when the sensor
+     * is triggered. Override this method in your implementation
+     * of this class.
+     *
+     * @param event The details of the event.
+     */
+    public abstract void onTrigger(TriggerEvent event);
+}
diff --git a/core/java/android/hardware/location/GeofenceHardware.java b/core/java/android/hardware/location/GeofenceHardware.java
new file mode 100644
index 0000000..35bbb9c
--- /dev/null
+++ b/core/java/android/hardware/location/GeofenceHardware.java
@@ -0,0 +1,439 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.hardware.location;
+
+import android.content.Context;
+import android.location.Location;
+import android.os.RemoteException;
+import android.util.Log;
+
+import java.lang.ref.WeakReference;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+
+/**
+ * This class handles geofences managed by various hardware subsystems. It contains
+ * the public APIs that is needed to accomplish the task.
+ *
+ * <p>The APIs should not be called directly by the app developers. A higher level api
+ * which abstracts the hardware should be used instead. All the checks are done by the higher
+ * level public API. Any needed locking should be handled by the higher level API.
+ *
+ * <p> There are 3 states associated with a Geofence: Inside, Outside, Unknown.
+ * There are 3 transitions: {@link #GEOFENCE_ENTERED}, {@link #GEOFENCE_EXITED},
+ * {@link #GEOFENCE_UNCERTAIN}. The APIs only expose the transitions.
+ *
+ * <p> Inside state: The hardware subsystem is reasonably confident that the user is inside
+ * the geofence. Outside state: The hardware subsystem is reasonably confident that the user
+ * is outside the geofence Unknown state: Unknown state can be interpreted as a state in which the
+ * monitoring subsystem isn't confident enough that the user is either inside or
+ * outside the Geofence. If the accuracy does not improve for a sufficient period of time,
+ * the {@link #GEOFENCE_UNCERTAIN} transition would be triggered. If the accuracy improves later,
+ * an appropriate transition would be triggered. The "reasonably confident" parameter
+ * depends on the hardware system and the positioning algorithms used.
+ * For instance, {@link #MONITORING_TYPE_GPS_HARDWARE} uses 95% as a confidence level.
+ */
+public final class GeofenceHardware {
+    private IGeofenceHardware mService;
+
+    // Hardware systems that do geofence monitoring.
+    static final int NUM_MONITORS = 1;
+
+    /**
+     * Constant for geofence monitoring done by the GPS hardware.
+     */
+    public static final int MONITORING_TYPE_GPS_HARDWARE = 0;
+
+    /**
+     * Constant to indiciate that the monitoring system is currently
+     * available for monitoring geofences.
+     */
+    public static final int MONITOR_CURRENTLY_AVAILABLE = 0;
+
+    /**
+     * Constant to indiciate that the monitoring system is currently
+     * unavailable for monitoring geofences.
+     */
+    public static final int MONITOR_CURRENTLY_UNAVAILABLE = 1;
+
+    /**
+     * Constant to indiciate that the monitoring system is unsupported
+     * for hardware geofence monitoring.
+     */
+    public static final int MONITOR_UNSUPPORTED = 2;
+
+    // The following constants need to match geofence flags in gps.h
+    /**
+     * The constant to indicate that the user has entered the geofence.
+     */
+    public static final int GEOFENCE_ENTERED = 1<<0L;
+
+    /**
+     * The constant to indicate that the user has exited the geofence.
+     */
+    public static final int GEOFENCE_EXITED = 1<<1L;
+
+    /**
+     * The constant to indicate that the user is uncertain with respect to a
+     * geofence.                                                  nn
+     */
+    public static final int GEOFENCE_UNCERTAIN = 1<<2L;
+
+    /**
+     * The constant used to indicate success of the particular geofence call
+     */
+    public static final int GEOFENCE_SUCCESS = 0;
+
+    /**
+     * The constant used to indicate that too many geofences have been registered.
+     */
+    public static final int GEOFENCE_ERROR_TOO_MANY_GEOFENCES = 1;
+
+    /**
+     * The constant used to indicate that the geofence id already exists.
+     */
+    public static final int GEOFENCE_ERROR_ID_EXISTS  = 2;
+
+    /**
+     * The constant used to indicate that the geofence id is unknown.
+     */
+    public static final int GEOFENCE_ERROR_ID_UNKNOWN = 3;
+
+    /**
+     * The constant used to indicate that the transition requested for the geofence is invalid.
+     */
+    public static final int GEOFENCE_ERROR_INVALID_TRANSITION = 4;
+
+    /**
+     * The constant used to indicate that the geofence operation has failed.
+     */
+    public static final int GEOFENCE_FAILURE = 5;
+
+    static final int GPS_GEOFENCE_UNAVAILABLE = 1<<0L;
+    static final int GPS_GEOFENCE_AVAILABLE = 1<<1L;
+
+    private HashMap<GeofenceHardwareCallback, GeofenceHardwareCallbackWrapper>
+            mCallbacks = new HashMap<GeofenceHardwareCallback, GeofenceHardwareCallbackWrapper>();
+    /**
+     * @hide
+     */
+    public GeofenceHardware(IGeofenceHardware service) {
+        mService = service;
+    }
+
+    /**
+     * Returns all the hardware geofence monitoring systems and their status.
+     * Status can be one of {@link #MONITOR_CURRENTLY_AVAILABLE},
+     * {@link #MONITOR_CURRENTLY_UNAVAILABLE} or {@link #MONITOR_UNSUPPORTED}
+     *
+     * <p> Some supported hardware monitoring systems might not be available
+     * for monitoring geofences in certain scenarios. For example, when a user
+     * enters a building, the GPS hardware subsystem might not be able monitor
+     * geofences and will change from {@link #MONITOR_CURRENTLY_AVAILABLE} to
+     * {@link #MONITOR_CURRENTLY_UNAVAILABLE}.
+     *
+     * <p> Requires {@link android.Manifest.permission#LOCATION_HARDWARE} permission to access
+     * geofencing in hardware.
+     *
+     * @return An array indexed by the various monitoring types and their status.
+     *         An array of length 0 is returned in case of errors.
+     */
+    public int[] getMonitoringTypesAndStatus() {
+        try {
+            return mService.getMonitoringTypesAndStatus();
+        } catch (RemoteException e) {
+        }
+        return new int[0];
+    }
+
+    /**
+     * Creates a circular geofence which is monitored by subsystems in the hardware.
+     *
+     * <p> When the device detects that is has entered, exited or is uncertain
+     * about the area specified by the geofence, the given callback will be called.
+     *
+     * <p> The {@link GeofenceHardwareCallback#onGeofenceChange} callback will be called,
+     * with the following parameters
+     * <ul>
+     * <li> The geofence Id
+     * <li> The location object indicating the last known location.
+     * <li> The transition associated with the geofence. One of
+     *      {@link #GEOFENCE_ENTERED}, {@link #GEOFENCE_EXITED}, {@link #GEOFENCE_UNCERTAIN}
+     * <li> The timestamp when the geofence transition occured.
+     * <li> The monitoring type ({@link #MONITORING_TYPE_GPS_HARDWARE} is one such example)
+     *      that was used.
+     * </ul>
+     *
+     * <p> The geofence will be monitored by the subsystem specified by monitoring_type parameter.
+     * The application does not need to hold a wakelock when the monitoring
+     * is being done by the underlying hardware subsystem. If the same geofence Id is being
+     * monitored by two different monitoring systems, the same id can be used for both calls, as
+     * long as the same callback object is used.
+     *
+     * <p> Requires {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission when
+     * {@link #MONITORING_TYPE_GPS_HARDWARE} is used.
+     *
+     * <p> Requires {@link android.Manifest.permission#LOCATION_HARDWARE} permission to access
+     * geofencing in hardware.
+     *
+     * <p>This API should not be called directly by the app developers. A higher level api
+     * which abstracts the hardware should be used instead. All the checks are done by the higher
+     * level public API. Any needed locking should be handled by the higher level API.
+     *
+     * @param latitude Latitude of the area to be monitored.
+     * @param longitude Longitude of the area to be monitored.
+     * @param radius Radius (in meters) of the area to be monitored.
+     * @param lastTransition The current state of the geofence. Can be one of
+     *        {@link #GEOFENCE_ENTERED}, {@link #GEOFENCE_EXITED},
+     *        {@link #GEOFENCE_UNCERTAIN}.
+     * @param monitorTransitions Bitwise OR of {@link #GEOFENCE_ENTERED},
+     *        {@link #GEOFENCE_EXITED}, {@link #GEOFENCE_UNCERTAIN}
+     * @param notificationResponsivenes Defines the best-effort description
+     *        of how soon should the callback be called when the transition
+     *        associated with the Geofence is triggered. For instance, if
+     *        set to 1000 millseconds with {@link #GEOFENCE_ENTERED},
+     *        the callback will be called 1000 milliseconds within entering
+     *        the geofence. This parameter is defined in milliseconds.
+     * @param unknownTimer The time limit after which the
+     *        {@link #GEOFENCE_UNCERTAIN} transition
+     *        should be triggered. This paramter is defined in milliseconds.
+     * @param monitoringType The type of the hardware subsystem that should be used
+     *        to monitor the geofence.
+     * @param callback {@link GeofenceHardwareCallback} that will be use to notify the
+     *        transition.
+     * @return true on success.
+     */
+    public boolean addCircularFence(int geofenceId, double latitude, double longitude,
+            double radius, int lastTransition,int monitorTransitions, int notificationResponsivenes,
+            int unknownTimer, int monitoringType, GeofenceHardwareCallback callback) {
+        try {
+            return mService.addCircularFence(geofenceId, latitude, longitude, radius,
+                    lastTransition, monitorTransitions, notificationResponsivenes, unknownTimer,
+                    monitoringType, getCallbackWrapper(callback));
+        } catch (RemoteException e) {
+        }
+        return false;
+    }
+
+    /**
+     * Removes a geofence added by {@link #addCircularFence} call.
+     *
+     * <p> Requires {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission when
+     * {@link #MONITORING_TYPE_GPS_HARDWARE} is used.
+     *
+     * <p> Requires {@link android.Manifest.permission#LOCATION_HARDWARE} permission to access
+     * geofencing in hardware.
+     *
+     * <p>This API should not be called directly by the app developers. A higher level api
+     * which abstracts the hardware should be used instead. All the checks are done by the higher
+     * level public API. Any needed locking should be handled by the higher level API.
+     *
+     * @param geofenceId The id of the geofence.
+     * @param monitoringType The type of the hardware subsystem that should be used
+     *        to monitor the geofence.
+     * @return true on success.
+     */
+   public boolean removeGeofence(int geofenceId, int monitoringType) {
+       try {
+           return mService.removeGeofence(geofenceId, monitoringType);
+       } catch (RemoteException e) {
+       }
+       return false;
+   }
+
+    /**
+     * Pauses the monitoring of a geofence added by {@link #addCircularFence} call.
+     *
+     * <p> Requires {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission when
+     * {@link #MONITORING_TYPE_GPS_HARDWARE} is used.
+     *
+     * <p> Requires {@link android.Manifest.permission#LOCATION_HARDWARE} permission to access
+     * geofencing in hardware.
+     *
+     * <p>This API should not be called directly by the app developers. A higher level api
+     * which abstracts the hardware should be used instead. All the checks are done by the higher
+     * level public API. Any needed locking should be handled by the higher level API.
+     *
+     * @param geofenceId The id of the geofence.
+     * @param monitoringType The type of the hardware subsystem that should be used
+     *        to monitor the geofence.
+     * @return true on success.
+     */
+    public boolean pauseGeofence(int geofenceId, int monitoringType) {
+        try {
+            return mService.pauseGeofence(geofenceId, monitoringType);
+        } catch (RemoteException e) {
+        }
+        return false;
+    }
+
+    /**
+     * Resumes the monitoring of a geofence added by {@link #pauseGeofence} call.
+     *
+     * <p> Requires {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission when
+     * {@link #MONITORING_TYPE_GPS_HARDWARE} is used.
+     *
+     * <p> Requires {@link android.Manifest.permission#LOCATION_HARDWARE} permission to access
+     * geofencing in hardware.
+     *
+     * <p>This API should not be called directly by the app developers. A higher level api
+     * which abstracts the hardware should be used instead. All the checks are done by the higher
+     * level public API. Any needed locking should be handled by the higher level API.
+     *
+     * @param geofenceId The id of the geofence.
+     * @param monitorTransition Bitwise OR of {@link #GEOFENCE_ENTERED},
+     *        {@link #GEOFENCE_EXITED}, {@link #GEOFENCE_UNCERTAIN}
+     * @param monitoringType The type of the hardware subsystem that should be used
+     *        to monitor the geofence.
+     * @return true on success.
+     */
+    public boolean resumeGeofence(int geofenceId, int monitorTransition, int monitoringType) {
+        try {
+            return mService.resumeGeofence(geofenceId, monitorTransition, monitoringType);
+        } catch (RemoteException e) {
+        }
+        return false;
+    }
+
+    /**
+     * Register the callback to be notified when the state of a hardware geofence
+     * monitoring system changes. For instance, it can change from
+     * {@link #MONITOR_CURRENTLY_AVAILABLE} to {@link #MONITOR_CURRENTLY_UNAVAILABLE}
+     *
+     * <p> Requires {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission when
+     * {@link #MONITORING_TYPE_GPS_HARDWARE} is used.
+     *
+     * <p> Requires {@link android.Manifest.permission#LOCATION_HARDWARE} permission to access
+     * geofencing in hardware.
+     *
+     * <p>This API should not be called directly by the app developers. A higher level api
+     * which abstracts the hardware should be used instead. All the checks are done by the higher
+     * level public API. Any needed locking should be handled by the higher level API.
+     *
+     * <p> The same callback object can be used to be informed of geofence transitions
+     * and state changes of the underlying hardware subsystem.
+     *
+     * @param monitoringType Type of the monitor
+     * @param callback Callback that will be called.
+     * @return true on success
+     */
+    public boolean registerForMonitorStateChangeCallback(int monitoringType,
+            GeofenceHardwareCallback callback) {
+        try {
+            return mService.registerForMonitorStateChangeCallback(monitoringType,
+                    getCallbackWrapper(callback));
+        } catch (RemoteException e) {
+        }
+        return false;
+    }
+
+    /**
+     * Unregister the callback that was used with {@link #registerForMonitorStateChangeCallback}
+     * to notify when the state of the hardware geofence monitoring system changes.
+     *
+     * <p> Requires {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission when
+     * {@link #MONITORING_TYPE_GPS_HARDWARE} is used.
+     *
+     * <p> Requires {@link android.Manifest.permission#LOCATION_HARDWARE} permission to access
+     * geofencing in hardware.
+     *
+     * <p>This API should not be called directly by the app developers. A higher level api
+     * which abstracts the hardware should be used instead. All the checks are done by the higher
+     * level public API. Any needed locking should be handled by the higher level API.
+     *
+     * @param monitoringType Type of the monitor
+     * @param callback Callback that will be called.
+     * @return true on success
+     */
+    public boolean unregisterForMonitorStateChangeCallback(int monitoringType,
+            GeofenceHardwareCallback callback) {
+        boolean  result = false;
+        try {
+            result = mService.unregisterForMonitorStateChangeCallback(monitoringType,
+                    getCallbackWrapper(callback));
+            if (result) removeCallback(callback);
+
+        } catch (RemoteException e) {
+        }
+        return result;
+    }
+
+
+    private void removeCallback(GeofenceHardwareCallback callback) {
+        synchronized (mCallbacks) {
+            mCallbacks.remove(callback);
+        }
+    }
+
+    private GeofenceHardwareCallbackWrapper getCallbackWrapper(GeofenceHardwareCallback callback) {
+        synchronized (mCallbacks) {
+            GeofenceHardwareCallbackWrapper wrapper = mCallbacks.get(callback);
+            if (wrapper == null) {
+                wrapper = new GeofenceHardwareCallbackWrapper(callback);
+                mCallbacks.put(callback, wrapper);
+            }
+            return wrapper;
+        }
+    }
+
+    class GeofenceHardwareCallbackWrapper extends IGeofenceHardwareCallback.Stub {
+        private WeakReference<GeofenceHardwareCallback> mCallback;
+
+        GeofenceHardwareCallbackWrapper(GeofenceHardwareCallback c) {
+            mCallback = new WeakReference<GeofenceHardwareCallback>(c);
+        }
+
+        public void onMonitoringSystemChange(int monitoringType, boolean available,
+                Location location) {
+            GeofenceHardwareCallback c = mCallback.get();
+            if (c != null) c.onMonitoringSystemChange(monitoringType, available, location);
+        }
+
+        public void onGeofenceChange(int geofenceId, int transition, Location location,
+                long timestamp, int monitoringType) {
+            GeofenceHardwareCallback c = mCallback.get();
+            if (c != null) {
+                c.onGeofenceChange(geofenceId, transition, location, timestamp,
+                        monitoringType);
+            }
+        }
+
+        public void onGeofenceAdd(int geofenceId, int status) {
+            GeofenceHardwareCallback c = mCallback.get();
+            if (c != null) c.onGeofenceAdd(geofenceId, status);
+        }
+
+        public void onGeofenceRemove(int geofenceId, int status) {
+            GeofenceHardwareCallback c = mCallback.get();
+            if (c != null) {
+                c.onGeofenceRemove(geofenceId, status);
+                removeCallback(c);
+            }
+        }
+
+        public void onGeofencePause(int geofenceId, int status) {
+            GeofenceHardwareCallback c = mCallback.get();
+            if (c != null) c.onGeofencePause(geofenceId, status);
+        }
+
+        public void onGeofenceResume(int geofenceId, int status) {
+            GeofenceHardwareCallback c = mCallback.get();
+            if (c != null) c.onGeofenceResume(geofenceId, status);
+        }
+    }
+}
diff --git a/core/java/android/hardware/location/GeofenceHardwareCallback.java b/core/java/android/hardware/location/GeofenceHardwareCallback.java
new file mode 100644
index 0000000..8ab582a
--- /dev/null
+++ b/core/java/android/hardware/location/GeofenceHardwareCallback.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.location;
+
+import android.location.Location;
+
+/**
+ * The callback class associated with the APIs in {@link GeofenceHardware}
+ */
+public abstract class GeofenceHardwareCallback {
+
+    /**
+     * The callback called when the state of a monitoring system changes.
+     * {@link GeofenceHardware#MONITORING_TYPE_GPS_HARDWARE} is an example of a
+     * monitoring system.
+     *
+     * @param monitoringType The type of the monitoring system.
+     * @param available Indicates whether the system is currently available or not.
+     * @param location The last known location according to the monitoring system.
+     */
+    public void onMonitoringSystemChange(int monitoringType, boolean available, Location location) {
+    }
+
+    /**
+     * The callback called when there is a transition to report for the specific
+     * geofence.
+     *
+     * @param geofenceId The geofence ID of the geofence
+     * @param transition One of {@link GeofenceHardware#GEOFENCE_ENTERED},
+     *        {@link GeofenceHardware#GEOFENCE_EXITED}, {@link GeofenceHardware#GEOFENCE_UNCERTAIN}
+     * @param location The last known location according to the monitoring system.
+     * @param timestamp The timestamp (elapsed real time in milliseconds) when the transition was
+     *        detected
+     * @param monitoringType Type of the monitoring system.
+     */
+    public void onGeofenceChange(int geofenceId, int transition, Location location,
+            long timestamp, int monitoringType) {
+    }
+
+    /**
+     * The callback called to notify the success or failure of the add call.
+     *
+     * @param geofenceId The ID of the geofence.
+     * @param status One of {@link GeofenceHardware#GEOFENCE_SUCCESS},
+     *        {@link GeofenceHardware#GEOFENCE_ERROR_ID_EXISTS},
+     *        {@link GeofenceHardware#GEOFENCE_ERROR_INVALID_TRANSITION},
+     *        {@link GeofenceHardware#GEOFENCE_ERROR_TOO_MANY_GEOFENCES},
+     *        {@link GeofenceHardware#GEOFENCE_FAILURE}
+     */
+    public void onGeofenceAdd(int geofenceId, int status) {
+    }
+
+    /**
+     * The callback called to notify the success or failure of the remove call.
+     *
+     * @param geofenceId The ID of the geofence.
+     * @param status  One of {@link GeofenceHardware#GEOFENCE_SUCCESS},
+     *        {@link GeofenceHardware#GEOFENCE_ERROR_ID_UNKNOWN},
+     *        {@link GeofenceHardware#GEOFENCE_FAILURE}
+     */
+    public void onGeofenceRemove(int geofenceId, int status) {
+    }
+
+    /**
+     * The callback called to notify the success or failure of the pause call.
+     *
+     * @param geofenceId The ID of the geofence.
+     * @param status One of {@link GeofenceHardware#GEOFENCE_SUCCESS},
+     *        {@link GeofenceHardware#GEOFENCE_ERROR_ID_UNKNOWN},
+     *        {@link GeofenceHardware#GEOFENCE_FAILURE}
+     */
+    public void onGeofencePause(int geofenceId, int status) {
+    }
+
+    /**
+     * The callback called to notify the success or failure of the resume call.
+     *
+     * @param geofenceId The ID of the geofence.
+     * @param status One of {@link GeofenceHardware#GEOFENCE_SUCCESS},
+     *        {@link GeofenceHardware#GEOFENCE_ERROR_ID_UNKNOWN},
+     *        {@link GeofenceHardware#GEOFENCE_ERROR_INVALID_TRANSITION},
+     *        {@link GeofenceHardware#GEOFENCE_FAILURE}
+     */
+    public void onGeofenceResume(int geofenceId, int status) {
+    }
+}
diff --git a/core/java/android/hardware/location/GeofenceHardwareImpl.java b/core/java/android/hardware/location/GeofenceHardwareImpl.java
new file mode 100644
index 0000000..21f1ea6
--- /dev/null
+++ b/core/java/android/hardware/location/GeofenceHardwareImpl.java
@@ -0,0 +1,599 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.location;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.location.IGpsGeofenceHardware;
+import android.location.Location;
+import android.location.LocationManager;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.PowerManager;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.SystemClock;
+import android.util.Log;
+import android.util.SparseArray;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+/**
+ * This class manages the geofences which are handled by hardware.
+ *
+ * @hide
+ */
+public final class GeofenceHardwareImpl {
+    private static final String TAG = "GeofenceHardwareImpl";
+    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+
+    private final Context mContext;
+    private static GeofenceHardwareImpl sInstance;
+    private PowerManager.WakeLock mWakeLock;
+    private SparseArray<IGeofenceHardwareCallback> mGeofences =
+            new SparseArray<IGeofenceHardwareCallback>();
+    private ArrayList<IGeofenceHardwareCallback>[] mCallbacks =
+            new ArrayList[GeofenceHardware.NUM_MONITORS];
+
+    private IGpsGeofenceHardware mGpsService;
+
+    private int[] mSupportedMonitorTypes = new int[GeofenceHardware.NUM_MONITORS];
+
+    // mGeofenceHandler message types
+    private static final int GEOFENCE_TRANSITION_CALLBACK = 1;
+    private static final int ADD_GEOFENCE_CALLBACK = 2;
+    private static final int REMOVE_GEOFENCE_CALLBACK = 3;
+    private static final int PAUSE_GEOFENCE_CALLBACK = 4;
+    private static final int RESUME_GEOFENCE_CALLBACK = 5;
+    private static final int ADD_GEOFENCE = 6;
+    private static final int REMOVE_GEOFENCE = 7;
+
+    // mCallbacksHandler message types
+    private static final int GPS_GEOFENCE_STATUS = 1;
+    private static final int CALLBACK_ADD = 2;
+    private static final int CALLBACK_REMOVE = 3;
+
+    // The following constants need to match GpsLocationFlags enum in gps.h
+    private static final int LOCATION_INVALID = 0;
+    private static final int LOCATION_HAS_LAT_LONG = 1;
+    private static final int LOCATION_HAS_ALTITUDE = 2;
+    private static final int LOCATION_HAS_SPEED = 4;
+    private static final int LOCATION_HAS_BEARING = 8;
+    private static final int LOCATION_HAS_ACCURACY = 16;
+
+    // Resolution level constants used for permission checks.
+    // These constants must be in increasing order of finer resolution.
+    private static final int RESOLUTION_LEVEL_NONE = 1;
+    private static final int RESOLUTION_LEVEL_COARSE = 2;
+    private static final int RESOLUTION_LEVEL_FINE = 3;
+
+    // GPS Geofence errors. Should match gps.h constants.
+    private static final int GPS_GEOFENCE_OPERATION_SUCCESS = 0;
+    private static final int GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES = 100;
+    private static final int GPS_GEOFENCE_ERROR_ID_EXISTS  = -101;
+    private static final int GPS_GEOFENCE_ERROR_ID_UNKNOWN = -102;
+    private static final int GPS_GEOFENCE_ERROR_INVALID_TRANSITION = -103;
+    private static final int GPS_GEOFENCE_ERROR_GENERIC = -149;
+
+
+
+    public synchronized static GeofenceHardwareImpl getInstance(Context context) {
+        if (sInstance == null) {
+            sInstance = new GeofenceHardwareImpl(context);
+        }
+        return sInstance;
+    }
+
+    private GeofenceHardwareImpl(Context context) {
+        mContext = context;
+        // Init everything to unsupported.
+        setMonitorAvailability(GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
+                GeofenceHardware.MONITOR_UNSUPPORTED);
+
+    }
+
+    private void acquireWakeLock() {
+        if (mWakeLock == null) {
+            PowerManager powerManager =
+                    (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
+            mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
+        }
+        mWakeLock.acquire();
+    }
+
+    private void releaseWakeLock() {
+        if (mWakeLock.isHeld()) mWakeLock.release();
+    }
+
+    private void updateGpsHardwareAvailability() {
+        //Check which monitors are available.
+        boolean gpsSupported;
+        try {
+            gpsSupported = mGpsService.isHardwareGeofenceSupported();
+        } catch (RemoteException e) {
+            Log.e(TAG, "Remote Exception calling LocationManagerService");
+            gpsSupported = false;
+        }
+
+        if (gpsSupported) {
+            // Its assumed currently available at startup.
+            // native layer will update later.
+            setMonitorAvailability(GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
+                    GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE);
+        }
+    }
+
+    public void setGpsHardwareGeofence(IGpsGeofenceHardware service) {
+        if (mGpsService == null) {
+            mGpsService = service;
+            updateGpsHardwareAvailability();
+        } else if (service == null) {
+            mGpsService = null;
+            Log.w(TAG, "GPS Geofence Hardware service seems to have crashed");
+        } else {
+            Log.e(TAG, "Error: GpsService being set again.");
+        }
+    }
+
+    public int[] getMonitoringTypesAndStatus() {
+        synchronized (mSupportedMonitorTypes) {
+            return mSupportedMonitorTypes;
+        }
+    }
+
+    public boolean addCircularFence(int geofenceId, double latitude, double longitude,
+            double radius, int lastTransition,int monitorTransitions, int notificationResponsivenes,
+            int unknownTimer, int monitoringType, IGeofenceHardwareCallback callback) {
+        // This API is not thread safe. Operations on the same geofence need to be serialized
+        // by upper layers
+        if (DEBUG) {
+            Log.d(TAG, "addCircularFence: GeofenceId: " + geofenceId + "Latitude: " + latitude +
+                    "Longitude: " + longitude + "Radius: " + radius + "LastTransition: "
+                    + lastTransition + "MonitorTransition: " + monitorTransitions +
+                    "NotificationResponsiveness: " + notificationResponsivenes +
+                    "UnKnown Timer: " + unknownTimer + "MonitoringType: " + monitoringType);
+
+        }
+        boolean result;
+        Message m = mGeofenceHandler.obtainMessage(ADD_GEOFENCE, callback);
+        m.arg1 = geofenceId;
+        mGeofenceHandler.sendMessage(m);
+
+        switch (monitoringType) {
+            case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
+                if (mGpsService == null) return false;
+                try {
+                    result = mGpsService.addCircularHardwareGeofence(geofenceId, latitude,
+                            longitude, radius, lastTransition, monitorTransitions,
+                            notificationResponsivenes, unknownTimer);
+                } catch (RemoteException e) {
+                    Log.e(TAG, "AddGeofence: Remote Exception calling LocationManagerService");
+                    result = false;
+                }
+                break;
+            default:
+                result = false;
+        }
+        if (!result) {
+            m = mGeofenceHandler.obtainMessage(REMOVE_GEOFENCE);
+            m.arg1 = geofenceId;
+            mGeofenceHandler.sendMessage(m);
+        }
+
+        if (DEBUG) Log.d(TAG, "addCircularFence: Result is: " + result);
+        return result;
+    }
+
+    public boolean removeGeofence(int geofenceId, int monitoringType) {
+        // This API is not thread safe. Operations on the same geofence need to be serialized
+        // by upper layers
+        if (DEBUG) Log.d(TAG, "Remove Geofence: GeofenceId: " + geofenceId);
+        boolean result = false;
+        switch (monitoringType) {
+            case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
+                if (mGpsService == null) return false;
+                try {
+                    result = mGpsService.removeHardwareGeofence(geofenceId);
+                } catch (RemoteException e) {
+                    Log.e(TAG, "RemoveGeofence: Remote Exception calling LocationManagerService");
+                    result = false;
+                }
+                break;
+            default:
+                result = false;
+        }
+        if (DEBUG) Log.d(TAG, "removeGeofence: Result is: " + result);
+        return result;
+    }
+
+    public boolean pauseGeofence(int geofenceId, int monitoringType) {
+        // This API is not thread safe. Operations on the same geofence need to be serialized
+        // by upper layers
+        if (DEBUG) Log.d(TAG, "Pause Geofence: GeofenceId: " + geofenceId);
+        boolean result;
+        switch (monitoringType) {
+            case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
+                if (mGpsService == null) return false;
+                try {
+                    result = mGpsService.pauseHardwareGeofence(geofenceId);
+                } catch (RemoteException e) {
+                    Log.e(TAG, "PauseGeofence: Remote Exception calling LocationManagerService");
+                    result = false;
+                }
+                break;
+            default:
+                result = false;
+        }
+        if (DEBUG) Log.d(TAG, "pauseGeofence: Result is: " + result);
+        return result;
+    }
+
+
+    public boolean resumeGeofence(int geofenceId, int monitorTransition, int monitoringType) {
+        // This API is not thread safe. Operations on the same geofence need to be serialized
+        // by upper layers
+        if (DEBUG) Log.d(TAG, "Resume Geofence: GeofenceId: " + geofenceId);
+        boolean result;
+        switch (monitoringType) {
+            case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
+                if (mGpsService == null) return false;
+                try {
+                    result = mGpsService.resumeHardwareGeofence(geofenceId, monitorTransition);
+                } catch (RemoteException e) {
+                    Log.e(TAG, "ResumeGeofence: Remote Exception calling LocationManagerService");
+                    result = false;
+                }
+                break;
+            default:
+                result = false;
+        }
+        if (DEBUG) Log.d(TAG, "resumeGeofence: Result is: " + result);
+        return result;
+    }
+
+    public boolean registerForMonitorStateChangeCallback(int monitoringType,
+            IGeofenceHardwareCallback callback) {
+        Message m = mCallbacksHandler.obtainMessage(CALLBACK_ADD, callback);
+        m.arg1 = monitoringType;
+        mCallbacksHandler.sendMessage(m);
+        return true;
+    }
+
+    public boolean unregisterForMonitorStateChangeCallback(int monitoringType,
+            IGeofenceHardwareCallback callback) {
+        Message m = mCallbacksHandler.obtainMessage(CALLBACK_REMOVE, callback);
+        m.arg1 = monitoringType;
+        mCallbacksHandler.sendMessage(m);
+        return true;
+    }
+
+    private Location getLocation(int flags, double latitude,
+            double longitude, double altitude, float speed, float bearing, float accuracy,
+            long timestamp) {
+        if (DEBUG) Log.d(TAG, "GetLocation: " + flags + ":" + latitude);
+        Location location = new Location(LocationManager.GPS_PROVIDER);
+        if ((flags & LOCATION_HAS_LAT_LONG) == LOCATION_HAS_LAT_LONG) {
+            location.setLatitude(latitude);
+            location.setLongitude(longitude);
+            location.setTime(timestamp);
+            // It would be nice to push the elapsed real-time timestamp
+            // further down the stack, but this is still useful
+            location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
+        }
+        if ((flags & LOCATION_HAS_ALTITUDE) == LOCATION_HAS_ALTITUDE) {
+            location.setAltitude(altitude);
+        } else {
+            location.removeAltitude();
+        }
+        if ((flags & LOCATION_HAS_SPEED) == LOCATION_HAS_SPEED) {
+            location.setSpeed(speed);
+        } else {
+            location.removeSpeed();
+        }
+        if ((flags & LOCATION_HAS_BEARING) == LOCATION_HAS_BEARING) {
+            location.setBearing(bearing);
+        } else {
+            location.removeBearing();
+        }
+        if ((flags & LOCATION_HAS_ACCURACY) == LOCATION_HAS_ACCURACY) {
+            location.setAccuracy(accuracy);
+        } else {
+            location.removeAccuracy();
+        }
+        return location;
+    }
+
+    /**
+     * called from GpsLocationProvider to report geofence transition
+     */
+    public void reportGpsGeofenceTransition(int geofenceId, int flags, double latitude,
+            double longitude, double altitude, float speed, float bearing, float accuracy,
+            long timestamp, int transition, long transitionTimestamp) {
+        if (DEBUG) Log.d(TAG, "GeofenceTransition: Flags: " + flags + " Lat: " + latitude +
+            " Long: " + longitude + " Altitude: " + altitude + " Speed: " + speed + " Bearing: " +
+            bearing + " Accuracy: " + accuracy + " Timestamp: " + timestamp + " Transition: " +
+            transition + " TransitionTimestamp: " + transitionTimestamp);
+        Location location = getLocation(flags, latitude, longitude, altitude, speed, bearing,
+                accuracy, timestamp);
+        GeofenceTransition t = new GeofenceTransition(geofenceId, transition, timestamp, location);
+        acquireWakeLock();
+        Message m = mGeofenceHandler.obtainMessage(GEOFENCE_TRANSITION_CALLBACK, t);
+        mGeofenceHandler.sendMessage(m);
+    }
+
+    /**
+     * called from GpsLocationProvider to report GPS status change.
+     */
+    public void reportGpsGeofenceStatus(int status, int flags, double latitude,
+            double longitude, double altitude, float speed, float bearing, float accuracy,
+            long timestamp) {
+        Location location = getLocation(flags, latitude, longitude, altitude, speed, bearing,
+                accuracy, timestamp);
+        boolean available = false;
+        if (status == GeofenceHardware.GPS_GEOFENCE_AVAILABLE) available = true;
+
+        int val = (available ? GeofenceHardware.MONITOR_CURRENTLY_UNAVAILABLE :
+                GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE);
+        setMonitorAvailability(GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE, val);
+
+        acquireWakeLock();
+        Message m = mCallbacksHandler.obtainMessage(GPS_GEOFENCE_STATUS, location);
+        m.arg1 = val;
+        mCallbacksHandler.sendMessage(m);
+    }
+
+    /**
+     * called from GpsLocationProvider add geofence callback.
+     */
+    public void reportGpsGeofenceAddStatus(int geofenceId, int status) {
+        if (DEBUG) Log.d(TAG, "Add Callback: GPS : Id: " + geofenceId + " Status: " + status);
+        acquireWakeLock();
+        Message m = mGeofenceHandler.obtainMessage(ADD_GEOFENCE_CALLBACK);
+        m.arg1 = geofenceId;
+        m.arg2 = getGeofenceStatus(status);
+        mGeofenceHandler.sendMessage(m);
+    }
+
+    /**
+     * called from GpsLocationProvider remove geofence callback.
+     */
+    public void reportGpsGeofenceRemoveStatus(int geofenceId, int status) {
+        if (DEBUG) Log.d(TAG, "Remove Callback: GPS : Id: " + geofenceId + " Status: " + status);
+        acquireWakeLock();
+        Message m = mGeofenceHandler.obtainMessage(REMOVE_GEOFENCE_CALLBACK);
+        m.arg1 = geofenceId;
+        m.arg2 = getGeofenceStatus(status);
+        mGeofenceHandler.sendMessage(m);
+    }
+
+    /**
+     * called from GpsLocationProvider pause geofence callback.
+     */
+    public void reportGpsGeofencePauseStatus(int geofenceId, int status) {
+        if (DEBUG) Log.d(TAG, "Pause Callback: GPS : Id: " + geofenceId + " Status: " + status);
+        acquireWakeLock();
+        Message m = mGeofenceHandler.obtainMessage(PAUSE_GEOFENCE_CALLBACK);
+        m.arg1 = geofenceId;
+        m.arg2 = getGeofenceStatus(status);
+        mGeofenceHandler.sendMessage(m);
+    }
+
+    /**
+     * called from GpsLocationProvider resume geofence callback.
+     */
+    public void reportGpsGeofenceResumeStatus(int geofenceId, int status) {
+        if (DEBUG) Log.d(TAG, "Resume Callback: GPS : Id: " + geofenceId + " Status: " + status);
+        acquireWakeLock();
+        Message m = mGeofenceHandler.obtainMessage(RESUME_GEOFENCE_CALLBACK);
+        m.arg1 = geofenceId;
+        m.arg2 = getGeofenceStatus(status);
+        mGeofenceHandler.sendMessage(m);
+    }
+
+    // All operations on mGeofences
+    private Handler mGeofenceHandler = new Handler() {
+        @Override
+        public void handleMessage(Message msg) {
+            int geofenceId;
+            int status;
+            IGeofenceHardwareCallback callback;
+            switch (msg.what) {
+                case ADD_GEOFENCE:
+                    geofenceId = msg.arg1;
+                    callback = (IGeofenceHardwareCallback) msg.obj;
+                    mGeofences.put(geofenceId, callback);
+                    break;
+                case REMOVE_GEOFENCE:
+                    geofenceId = msg.arg1;
+                    mGeofences.remove(geofenceId);
+                    break;
+                case ADD_GEOFENCE_CALLBACK:
+                    geofenceId = msg.arg1;
+                    callback = mGeofences.get(geofenceId);
+                    if (callback == null) return;
+
+                    try {
+                        callback.onGeofenceAdd(geofenceId, msg.arg2);
+                    } catch (RemoteException e) {Log.i(TAG, "Remote Exception:" + e);}
+                    releaseWakeLock();
+                    break;
+                case REMOVE_GEOFENCE_CALLBACK:
+                    geofenceId = msg.arg1;
+                    callback = mGeofences.get(geofenceId);
+                    if (callback == null) return;
+
+                    try {
+                        callback.onGeofenceRemove(geofenceId, msg.arg2);
+                    } catch (RemoteException e) {}
+                    mGeofences.remove(geofenceId);
+                    releaseWakeLock();
+                    break;
+
+                case PAUSE_GEOFENCE_CALLBACK:
+                    geofenceId = msg.arg1;
+                    callback = mGeofences.get(geofenceId);
+                    if (callback == null) return;
+
+                    try {
+                        callback.onGeofencePause(geofenceId, msg.arg2);
+                    } catch (RemoteException e) {}
+                    releaseWakeLock();
+                    break;
+
+                case RESUME_GEOFENCE_CALLBACK:
+                    geofenceId = msg.arg1;
+                    callback = mGeofences.get(geofenceId);
+                    if (callback == null) return;
+
+                    try {
+                        callback.onGeofenceResume(geofenceId, msg.arg2);
+                    } catch (RemoteException e) {}
+                    releaseWakeLock();
+                    break;
+
+                case GEOFENCE_TRANSITION_CALLBACK:
+                    GeofenceTransition geofenceTransition = (GeofenceTransition)(msg.obj);
+                    callback = mGeofences.get(geofenceTransition.mGeofenceId);
+
+                    if (DEBUG) Log.d(TAG, "GeofenceTransistionCallback: GPS : GeofenceId: " +
+                            geofenceTransition.mGeofenceId +
+                            "Transition: " + geofenceTransition.mTransition +
+                            "Location: " + geofenceTransition.mLocation + ":" + mGeofences);
+
+                    try {
+                        callback.onGeofenceChange(
+                                geofenceTransition.mGeofenceId, geofenceTransition.mTransition,
+                                geofenceTransition.mLocation, geofenceTransition.mTimestamp,
+                                GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE);
+                    } catch (RemoteException e) {}
+                    releaseWakeLock();
+                    break;
+            }
+        }
+    };
+
+    // All operations on mCallbacks
+    private Handler mCallbacksHandler = new Handler() {
+        @Override
+        public void handleMessage(Message msg) {
+            int monitoringType;
+            ArrayList<IGeofenceHardwareCallback> callbackList;
+            IGeofenceHardwareCallback callback;
+
+            switch (msg.what) {
+                case GPS_GEOFENCE_STATUS:
+                    Location location = (Location) msg.obj;
+                    int val = msg.arg1;
+                    boolean available;
+                    available = (val == GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE ?
+                            true : false);
+                    callbackList = mCallbacks[GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE];
+                    if (callbackList == null) return;
+
+                    if (DEBUG) Log.d(TAG, "MonitoringSystemChangeCallback: GPS : " + available);
+
+                    for (IGeofenceHardwareCallback c: callbackList) {
+                        try {
+                            c.onMonitoringSystemChange(
+                                    GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE, available,
+                                    location);
+                        } catch (RemoteException e) {}
+                    }
+                    releaseWakeLock();
+                    break;
+                case CALLBACK_ADD:
+                    monitoringType = msg.arg1;
+                    callback = (IGeofenceHardwareCallback) msg.obj;
+                    callbackList = mCallbacks[monitoringType];
+                    if (callbackList == null) {
+                        callbackList = new ArrayList<IGeofenceHardwareCallback>();
+                        mCallbacks[monitoringType] = callbackList;
+                    }
+                    if (!callbackList.contains(callback)) callbackList.add(callback);
+                    break;
+                case CALLBACK_REMOVE:
+                    monitoringType = msg.arg1;
+                    callback = (IGeofenceHardwareCallback) msg.obj;
+                    callbackList = mCallbacks[monitoringType];
+                    if (callbackList != null) {
+                        callbackList.remove(callback);
+                    }
+                    break;
+            }
+        }
+    };
+
+    private class GeofenceTransition {
+        private int mGeofenceId, mTransition;
+        private long mTimestamp;
+        private Location mLocation;
+
+        GeofenceTransition(int geofenceId, int transition, long timestamp, Location location) {
+            mGeofenceId = geofenceId;
+            mTransition = transition;
+            mTimestamp = timestamp;
+            mLocation = location;
+        }
+    }
+
+    private void setMonitorAvailability(int monitor, int val) {
+        synchronized (mSupportedMonitorTypes) {
+            mSupportedMonitorTypes[monitor] = val;
+        }
+    }
+
+
+    int getMonitoringResolutionLevel(int monitoringType) {
+        switch (monitoringType) {
+            case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
+                return RESOLUTION_LEVEL_FINE;
+        }
+        return RESOLUTION_LEVEL_NONE;
+    }
+
+    int getAllowedResolutionLevel(int pid, int uid) {
+        if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
+                pid, uid) == PackageManager.PERMISSION_GRANTED) {
+            return RESOLUTION_LEVEL_FINE;
+        } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
+                pid, uid) == PackageManager.PERMISSION_GRANTED) {
+            return RESOLUTION_LEVEL_COARSE;
+        } else {
+            return RESOLUTION_LEVEL_NONE;
+        }
+    }
+
+    private int getGeofenceStatus(int status) {
+        switch (status) {
+            case GPS_GEOFENCE_OPERATION_SUCCESS:
+                return GeofenceHardware.GEOFENCE_SUCCESS;
+            case GPS_GEOFENCE_ERROR_GENERIC:
+                return GeofenceHardware.GEOFENCE_FAILURE;
+            case GPS_GEOFENCE_ERROR_ID_EXISTS:
+                return GeofenceHardware.GEOFENCE_ERROR_ID_EXISTS;
+            case GPS_GEOFENCE_ERROR_INVALID_TRANSITION:
+                return GeofenceHardware.GEOFENCE_ERROR_INVALID_TRANSITION;
+            case GPS_GEOFENCE_ERROR_TOO_MANY_GEOFENCES:
+                return GeofenceHardware.GEOFENCE_ERROR_TOO_MANY_GEOFENCES;
+            case GPS_GEOFENCE_ERROR_ID_UNKNOWN:
+                return GeofenceHardware.GEOFENCE_ERROR_ID_UNKNOWN;
+        }
+        return -1;
+    }
+}
diff --git a/core/java/android/hardware/location/GeofenceHardwareService.java b/core/java/android/hardware/location/GeofenceHardwareService.java
new file mode 100644
index 0000000..0eccee6
--- /dev/null
+++ b/core/java/android/hardware/location/GeofenceHardwareService.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.location;
+
+import android.Manifest;
+import android.app.Service;
+import android.content.Context;
+import android.content.Intent;
+import android.location.IGpsGeofenceHardware;
+import android.os.Binder;
+import android.os.IBinder;
+
+/**
+ * Service that handles hardware geofencing.
+ *
+ * @hide
+ */
+public class GeofenceHardwareService extends Service {
+    private GeofenceHardwareImpl mGeofenceHardwareImpl;
+    private Context mContext;
+
+    @Override
+    public void onCreate() {
+        mContext = this;
+        mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
+    }
+
+    @Override
+    public IBinder onBind(Intent intent) {
+        return mBinder;
+    }
+
+    @Override
+    public boolean onUnbind(Intent intent) {
+        return false;
+    }
+
+    @Override
+    public void onDestroy() {
+        mGeofenceHardwareImpl = null;
+    }
+
+
+    private void checkPermission(int pid, int uid, int monitoringType) {
+        if (mGeofenceHardwareImpl.getAllowedResolutionLevel(pid, uid) <
+                mGeofenceHardwareImpl.getMonitoringResolutionLevel(monitoringType)) {
+            throw new SecurityException("Insufficient permissions to access hardware geofence for"
+                    + " type: " + monitoringType);
+        }
+    }
+
+    private IBinder mBinder = new IGeofenceHardware.Stub() {
+        public void setGpsGeofenceHardware(IGpsGeofenceHardware service) {
+            mGeofenceHardwareImpl.setGpsHardwareGeofence(service);
+        }
+
+        public int[] getMonitoringTypesAndStatus() {
+            mContext.enforceCallingPermission(Manifest.permission.LOCATION_HARDWARE,
+                    "Location Hardware permission not granted to access hardware geofence");
+
+            return mGeofenceHardwareImpl.getMonitoringTypesAndStatus();
+        }
+
+        public boolean addCircularFence(int id, double lat, double longitude, double radius,
+                int lastTransition, int monitorTransitions, int
+                notificationResponsiveness, int unknownTimer, int monitoringType,
+                IGeofenceHardwareCallback callback) {
+            mContext.enforceCallingPermission(Manifest.permission.LOCATION_HARDWARE,
+                    "Location Hardware permission not granted to access hardware geofence");
+            checkPermission(Binder.getCallingPid(), Binder.getCallingUid(), monitoringType);
+            return mGeofenceHardwareImpl.addCircularFence(id, lat, longitude, radius,
+                    lastTransition, monitorTransitions, notificationResponsiveness, unknownTimer,
+                    monitoringType, callback);
+        }
+
+        public boolean removeGeofence(int id, int monitoringType) {
+            mContext.enforceCallingPermission(Manifest.permission.LOCATION_HARDWARE,
+                    "Location Hardware permission not granted to access hardware geofence");
+
+            checkPermission(Binder.getCallingPid(), Binder.getCallingUid(), monitoringType);
+            return mGeofenceHardwareImpl.removeGeofence(id, monitoringType);
+        }
+
+        public boolean pauseGeofence(int id, int monitoringType) {
+            mContext.enforceCallingPermission(Manifest.permission.LOCATION_HARDWARE,
+                    "Location Hardware permission not granted to access hardware geofence");
+
+            checkPermission(Binder.getCallingPid(), Binder.getCallingUid(), monitoringType);
+            return mGeofenceHardwareImpl.pauseGeofence(id, monitoringType);
+        }
+
+        public boolean resumeGeofence(int id, int monitorTransitions, int monitoringType) {
+            mContext.enforceCallingPermission(Manifest.permission.LOCATION_HARDWARE,
+                    "Location Hardware permission not granted to access hardware geofence");
+
+            checkPermission(Binder.getCallingPid(), Binder.getCallingUid(), monitoringType);
+            return mGeofenceHardwareImpl.resumeGeofence(id, monitorTransitions, monitoringType);
+        }
+
+        public boolean registerForMonitorStateChangeCallback(int monitoringType,
+                IGeofenceHardwareCallback callback) {
+            mContext.enforceCallingPermission(Manifest.permission.LOCATION_HARDWARE,
+                    "Location Hardware permission not granted to access hardware geofence");
+
+            checkPermission(Binder.getCallingPid(), Binder.getCallingUid(), monitoringType);
+            return mGeofenceHardwareImpl.registerForMonitorStateChangeCallback(monitoringType,
+                    callback);
+        }
+
+        public boolean unregisterForMonitorStateChangeCallback(int monitoringType,
+                IGeofenceHardwareCallback callback) {
+            mContext.enforceCallingPermission(Manifest.permission.LOCATION_HARDWARE,
+                    "Location Hardware permission not granted to access hardware geofence");
+
+            checkPermission(Binder.getCallingPid(), Binder.getCallingUid(), monitoringType);
+            return mGeofenceHardwareImpl.unregisterForMonitorStateChangeCallback(monitoringType,
+                    callback);
+        }
+    };
+}
diff --git a/core/java/android/hardware/location/IGeofenceHardware.aidl b/core/java/android/hardware/location/IGeofenceHardware.aidl
new file mode 100644
index 0000000..4ba02b8
--- /dev/null
+++ b/core/java/android/hardware/location/IGeofenceHardware.aidl
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENS   E-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 android.hardware.location;
+
+import android.location.IGpsGeofenceHardware;
+import android.hardware.location.IGeofenceHardwareCallback;
+
+/** @hide */
+interface IGeofenceHardware {
+    void setGpsGeofenceHardware(in IGpsGeofenceHardware service);
+    int[] getMonitoringTypesAndStatus();
+    boolean addCircularFence(int id, double lat, double longitude, double radius,
+            int lastTransition, int monitorTransitions, int notificationResponsiveness,
+            int unknownTimer, int monitoringType, in IGeofenceHardwareCallback callback);
+    boolean removeGeofence(int id, int monitoringType);
+    boolean pauseGeofence(int id, int monitoringType);
+    boolean resumeGeofence(int id, int monitorTransitions, int monitoringType);
+    boolean registerForMonitorStateChangeCallback(int monitoringType,
+            IGeofenceHardwareCallback callback);
+    boolean unregisterForMonitorStateChangeCallback(int monitoringType,
+            IGeofenceHardwareCallback callback);
+}
diff --git a/core/java/android/hardware/location/IGeofenceHardwareCallback.aidl b/core/java/android/hardware/location/IGeofenceHardwareCallback.aidl
new file mode 100644
index 0000000..678fc49
--- /dev/null
+++ b/core/java/android/hardware/location/IGeofenceHardwareCallback.aidl
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.location;
+
+import android.location.Location;
+
+/** @hide */
+oneway interface IGeofenceHardwareCallback {
+   void onMonitoringSystemChange(int monitoringType, boolean available, in Location location);
+   void onGeofenceChange(int geofenceId, int transition, in Location location,
+            long timestamp, int monitoringType);
+   void onGeofenceAdd(int geofenceId, int status);
+   void onGeofenceRemove(int geofenceId, int status);
+   void onGeofencePause(int geofenceId, int status);
+   void onGeofenceResume(int geofenceId, int status);
+}
diff --git a/core/java/android/os/Trace.java b/core/java/android/os/Trace.java
index 310b12c..607def7 100644
--- a/core/java/android/os/Trace.java
+++ b/core/java/android/os/Trace.java
@@ -25,8 +25,6 @@
  * This tracing mechanism is independent of the method tracing mechanism
  * offered by {@link Debug#startMethodTracing}.  In particular, it enables
  * tracing of events that occur across multiple processes.
- *
- * @hide
  */
 public final class Trace {
     /*
@@ -198,7 +196,7 @@
 
     /**
      * Writes a trace message to indicate that a given section of code has begun. This call must
-     * be followed by a corresponding call to {@link #traceEnd()} on the same thread.
+     * be followed by a corresponding call to {@link #endSection()} on the same thread.
      *
      * <p class="note"> At this time the vertical bar character '|', newline character '\n', and
      * null character '\0' are used internally by the tracing mechanism.  If sectionName contains
@@ -206,10 +204,8 @@
      *
      * @param sectionName The name of the code section to appear in the trace.  This may be at
      * most 127 Unicode code units long.
-     *
-     * @hide
      */
-    public static void traceBegin(String sectionName) {
+    public static void beginSection(String sectionName) {
         if (isTagEnabled(TRACE_TAG_APP)) {
             if (sectionName.length() > MAX_SECTION_NAME_LEN) {
                 throw new IllegalArgumentException("sectionName is too long");
@@ -220,13 +216,12 @@
 
     /**
      * Writes a trace message to indicate that a given section of code has ended. This call must
-     * be preceeded by a corresponding call to {@link #traceBegin(String)}. Calling this method
+     * be preceeded by a corresponding call to {@link #beginSection(String)}. Calling this method
      * will mark the end of the most recently begun section of code, so care must be taken to
-     * ensure that traceBegin / traceEnd pairs are properly nested and called from the same thread.
-     *
-     * @hide
+     * ensure that beginSection / endSection pairs are properly nested and called from the same
+     * thread.
      */
-    public static void traceEnd() {
+    public static void endSection() {
         if (isTagEnabled(TRACE_TAG_APP)) {
             nativeTraceEnd(TRACE_TAG_APP);
         }
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 98b7877..c1db4c6 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -4284,7 +4284,7 @@
                     enqueueInputEvent(e);
                     Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e);
                     m.setAsynchronous(true);
-                    mHandler.sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
+                    sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout());
                 }
             }
 
diff --git a/core/jni/android_hardware_SensorManager.cpp b/core/jni/android_hardware_SensorManager.cpp
index 3083cb1..6374494 100644
--- a/core/jni/android_hardware_SensorManager.cpp
+++ b/core/jni/android_hardware_SensorManager.cpp
@@ -31,7 +31,7 @@
 static struct {
     jclass clazz;
     jmethodID dispatchSensorEvent;
-} gSensorEventQueueClassInfo;
+} gBaseEventQueueClassInfo;
 
 namespace android {
 
@@ -145,7 +145,7 @@
                 env->SetFloatArrayRegion(mScratch, 0, 16, buffer[i].data);
 
                 env->CallVoidMethod(mReceiverObject,
-                        gSensorEventQueueClassInfo.dispatchSensorEvent,
+                        gBaseEventQueueClassInfo.dispatchSensorEvent,
                         buffer[i].sensor,
                         mScratch,
                         buffer[i].vector.status,
@@ -209,9 +209,9 @@
             (void*)nativeGetNextSensor },
 };
 
-static JNINativeMethod gSensorEventQueueMethods[] = {
-    {"nativeInitSensorEventQueue",
-            "(Landroid/hardware/SystemSensorManager$SensorEventQueue;Landroid/os/MessageQueue;[F)I",
+static JNINativeMethod gBaseEventQueueMethods[] = {
+    {"nativeInitBaseEventQueue",
+            "(Landroid/hardware/SystemSensorManager$BaseEventQueue;Landroid/os/MessageQueue;[F)I",
             (void*)nativeInitSensorEventQueue },
 
     {"nativeEnableSensor",
@@ -245,13 +245,13 @@
     jniRegisterNativeMethods(env, "android/hardware/SystemSensorManager",
             gSystemSensorManagerMethods, NELEM(gSystemSensorManagerMethods));
 
-    jniRegisterNativeMethods(env, "android/hardware/SystemSensorManager$SensorEventQueue",
-            gSensorEventQueueMethods, NELEM(gSensorEventQueueMethods));
+    jniRegisterNativeMethods(env, "android/hardware/SystemSensorManager$BaseEventQueue",
+            gBaseEventQueueMethods, NELEM(gBaseEventQueueMethods));
 
-    FIND_CLASS(gSensorEventQueueClassInfo.clazz, "android/hardware/SystemSensorManager$SensorEventQueue");
+    FIND_CLASS(gBaseEventQueueClassInfo.clazz, "android/hardware/SystemSensorManager$BaseEventQueue");
 
-    GET_METHOD_ID(gSensorEventQueueClassInfo.dispatchSensorEvent,
-            gSensorEventQueueClassInfo.clazz,
+    GET_METHOD_ID(gBaseEventQueueClassInfo.dispatchSensorEvent,
+            gBaseEventQueueClassInfo.clazz,
             "dispatchSensorEvent", "(I[FIJ)V");
 
     return 0;
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 90e3b8d..6b4fe79 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -616,6 +616,14 @@
         android:label="@string/permlab_installLocationProvider"
         android:description="@string/permdesc_installLocationProvider" />
 
+    <!-- Allows an application to use location features in hardware,
+         such as the geofencing api
+         Protected by signature|system protection level -->
+    <permission android:name="android.permission.LOCATION_HARDWARE"
+        android:permissionGroup="android.permission-group.LOCATION"
+        android:protectionLevel="signature|system" />
+    <uses-permission android:name="android.permission.LOCATION_HARDWARE"/>
+
     <!-- ======================================= -->
     <!-- Permissions for accessing networks -->
     <!-- ======================================= -->
@@ -2264,6 +2272,14 @@
                 android:process=":ui">
         </activity>
 
+        <activity android:name="android.accounts.CantAddAccountActivity"
+                android:excludeFromRecents="true"
+                android:exported="true"
+                android:theme="@android:style/Theme.Holo.Dialog"
+                android:label="@string/error_message_title"
+                android:process=":ui">
+        </activity>
+
         <activity android:name="android.accounts.GrantCredentialsPermissionActivity"
                 android:excludeFromRecents="true"
                 android:exported="true"
@@ -2350,6 +2366,9 @@
             android:permission="android.permission.MASTER_CLEAR"
             android:exported="true" />
 
+        <service android:name="android.hardware.location.GeofenceHardwareService"
+            android:permission="android.permission.LOCATION_HARDWARE"
+            android:exported="false" />
     </application>
 
 </manifest>
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index 0afe4c1..7b70e21 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -996,8 +996,9 @@
               permission, and it must always be granted when it is installed.
               If you set this to false, then in some cases the application may
               be installed with it being granted the permission, and it will
-              need to request the permission later if it needs it. -->
+              need to request the permission later if it needs it.
         <attr name="required" format="boolean" />
+        -->
     </declare-styleable>
 
     <!-- The <code>uses-configuration</code> tag specifies
@@ -1040,7 +1041,7 @@
               don't support it.  If you set this to false, then this will
               not impose a restriction on where the application can be
               installed. -->
-        <attr name="required" />
+        <attr name="required" format="boolean" />
     </declare-styleable>
 
     <!-- The <code>uses-sdk</code> tag describes the SDK features that the
diff --git a/data/fonts/Roboto-Italic.ttf b/data/fonts/Roboto-Italic.ttf
index bd57775..4642d6f 100644
--- a/data/fonts/Roboto-Italic.ttf
+++ b/data/fonts/Roboto-Italic.ttf
Binary files differ
diff --git a/docs/html/guide/basics/appmodel.jd b/docs/html/guide/basics/appmodel.jd
deleted file mode 100644
index 323fc9b..0000000
--- a/docs/html/guide/basics/appmodel.jd
+++ /dev/null
@@ -1,261 +0,0 @@
-page.title=Application Model
-@jd:body
-<h1>Android Application Model: Applications, Tasks, Processes, and Threads</h1>
-
-<p>In most operating systems, there is a strong 1-to-1 correlation between
-the executable image (such as the .exe on Windows) that an application lives in,
-the process it runs in, and the icon and application the user interacts with.
-In Android these associations are much more fluid, and it is important to
-understand how the various pieces can be put together.</p>
-
-<p>Because of the flexible nature of Android applications, there is some
-basic terminology that needs to be understood when implementing the
-various pieces of an application:</p>
-
-<ul>
-<li><p>An <strong>android package</strong> (or <strong>.apk</strong> for short)
-is the file containing an application's code and its resources.  This is the
-file that an application is distributed in and downloaded by the user when
-installing that application on their device.</p></li>
-
-<li><p>A <strong>task</strong> is generally what the user perceives as
-an "application" that can be launched: usually a task has an icon in the
-home screen through which it is accessed, and it is available as a top-level
-item that can be brought to the foreground in front of other
-tasks.</p></li>
-
-<li><p>A <strong>process</strong> is a low-level kernel process in which
-an application's code is running.  Normally all of the code in a
-.apk is run in one, dedicated process for that .apk; however, the
-{@link android.R.styleable#AndroidManifestApplication_process process} tag
-can be used to modify where that code is run, either for
-{@link android.R.styleable#AndroidManifestApplication the entire .apk}
-or for individual
-{@link android.R.styleable#AndroidManifestActivity activity},
-{@link android.R.styleable#AndroidManifestReceiver receiver},
-{@link android.R.styleable#AndroidManifestService service}, or
-{@link android.R.styleable#AndroidManifestProvider provider}, components.</p></li>
-</ul>
-
-<h2 id="Tasks">Tasks</h2>
-
-<p>A key point here is: <em>when the user sees as an "application," what
-they are actually dealing with is a task</em>.  If you just create a .apk
-with a number of activities, one of which is a top-level entry point (via
-an {@link android.R.styleable#AndroidManifestIntentFilter intent-filter} for
-the action <code>android.intent.action.MAIN</code> and
-category <code>android.intent.category.LAUNCHER</code>), then there will indeed
-be one task created for your .apk, and any activities you start from there
-will also run as part of that task.</p>
-
-<p>A task, then, from the user's perspective your application; and from the
-application developer's perspective it is one or more activities the user
-has traversed through in that task and not yet closed, or an activity stack.
-A new task is created by
-starting an activity Intent with the {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK
-Intent.FLAG_ACTIVITY_NEW_TASK} flag; this Intent will be used as the root Intent of
-the task, defining what task it is.  Any activity started without this flag
-will run in the same task as the activity that is starting it (unless that
-activity has requested a special launch mode, as discussed later).  Tasks can
-be re-ordered: if you use FLAG_ACTIVITY_NEW_TASK but there is already a task
-running for that Intent, the current task's activity stack will be brought
-to the foreground instead of starting a new task.</p>
-
-<p>FLAG_ACTIVITY_NEW_TASK must only be used with care: using it says that,
-from the user's perspective, a new application starts at this point.  If this
-is not the behavior you desire, you should not be creating a new task.  In
-addition, you should only use the new task flag if it is possible for the user
-to navigate from home back to where they are and launch the same Intent as a
-new task.  Otherwise, if the user presses HOME instead of BACK from the task
-you have launched, your task and its activities will be ordered behind the
-home screen without a way to return to them.</p>
-
-<h3>Task Affinities</h3>
-
-<p>In some cases Android needs to know which task an activity belongs to even when
-it is not being launched in to a specific task.  This is accomplished through
-task affinities, which provide a unique static name for the task that one or more
-activities are intended to run in.  The default task affinity for an activity
-is the name of the .apk package name the activity is implemented in.  This
-provides the normally expected behavior, where all of the activities in a
-particular .apk are part of a single application to the user.</p>
-
-<p>When starting a new activity without the
-{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK
-Intent.FLAG_ACTIVITY_NEW_TASK} flag, task affinities have no impact on the
-task the new activity will run in: it will always run in the task of the
-activity that is starting it.  However, if the NEW_TASK flag is being used,
-then the affinity will be used to determine if a task already exists with
-the same affinity.  If so, that task will be brought to the front and the
-new activity launched at the top of that task.</p>
-
-<p>This behavior is most useful for situations where you must use the
-NEW_TASK flag, in particular launching activities from status bar notifications
-or home screen shortcuts.  The result is that, when the user launches your
-application this way, its current task state will be brought to the foreground,
-and the activity they now want to look at placed on top of it.</p>
-
-<p>You can assign your own task affinities in your manifest's
-{@link android.R.styleable#AndroidManifestApplication application} tag for
-all activities in the .apk, or the
-{@link android.R.styleable#AndroidManifestActivity activity} tag of
-individual activities.  Some examples of how this can be used are:</p>
-
-<ul>
-<li>If your .apk contains multiple top-level applications that the user can
-launch, then you will probably want to assign different affinities to each
-of the activities that the users sees for your .apk.  A good convention for
-coming up with distinct names is to append your .apk's package name with
-a colon separated string.  For example, the "com.android.contacts" .apk
-may have the affinities "com.android.contacts:Dialer" and
-"com.android.contacts:ContactsList".</ul>
-<li>If you are replacing a notification, shortcut, or other such "inner"
-activity of an application that can be launched from outside of it, you may
-need to explicitly set the taskAffinity of your replacement activity to be
-the same as the application you are replacing.  For example, if you are
-replacing the contacts details view (which the user can make and invoke
-shortcuts to), you would want to set the taskAffinity to
-"com.android.contacts".</li>
-</ul>
-
-<h3>Launch Modes and Launch Flags</h3>
-
-<p>The main way you control how activities interact with tasks is through
-the activity's
-{@link android.R.styleable#AndroidManifestActivity_launchMode launchMode}
-attribute and the {@link android.content.Intent#setFlags flags} associated
-with an Intent.  These two parameters can work together in various ways
-to control the outcome of the activity launch, as described in their
-associated documentation.  Here we will look at some common use cases and
-combinations of these parameters.</p>
-
-<p>The most common launch mode you will use (besides the default
-<code>standard</code> mode) is <code>singleTop</code>.  This does not have
-an impact on tasks; it just avoids starting the same activity multiple times
-on the top of a stack.
-
-<p>The <code>singleTask</code> launch mode has a major
-impact on tasks: it causes the activity to always be started in
-a new task (or its existing task to be brought to the foreground).  Using
-this mode requires a lot of care in how you interact with the rest of the
-system, as it impacts every path in to the activity.  It should only be used
-with activities that are front doors to the application (that is, which
-support the MAIN action and LAUNCHER category).</p>
-
-<p>The <code>singleInstance</code> launch mode is even more specialized, and
-should only be used in applications that are implemented entirely as one
-activity.</p>
-
-<p>A situation you will often run in to is when another entity (such as the
-{@link android.app.SearchManager} or {@link android.app.NotificationManager})
-starts one of your activities.  In this case, the
-{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK
-Intent.FLAG_ACTIVITY_NEW_TASK} flag must be used, because the activity is
-being started outside of a task (and the application/task may not even
-exist).  As described previously, the standard behavior in this situation
-is to bring to the foreground the current task matching the new activity's
-affinity and start the new activity at the top of it.  There are, however,
-other types of behavior that you can implement.</p>
-
-<p>One common approach is to also use the
-{@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP
-Intent.FLAG_ACTIVITY_CLEAR_TOP} flag in conjunction with NEW_TASK.  By doing so,
-if your task is already running, then it will be brought to the foreground,
-all of the activities on its stack cleared except the root activity, and the
-root activity's {@link android.app.Activity#onNewIntent} called with the
-Intent being started.  Note that the activity often also use the <code>singleTop</code>
-or <code>singleTask</code> launch mode when using this approach, so that
-the current instance is given the new intent instead of requiring that it
-be destroyed and a new instance started.</p>
-
-<p>Another approach you can take is to set the notification activity's
-<code>android:taskAffinity</code> to the empty string "" (indicating no affinity)
-and setting the
-<code>{@link android.R.styleable#AndroidManifestActivity_noHistory
-android:noHistory}</code> and
-<code>{@link android.R.styleable#AndroidManifestActivity_excludeFromRecents
-android:excludeFromRecents}</code> attributes.
-This approach is useful if you would like the notification
-to take the user to a separate activity describing it, rather than return
-to the application's task.  By specifying these attributes, the activity will
-be finished whether the user leaves it with BACK or HOME and it will not
-show up in the recent tasks list; if the <code>noHistory</code> attribute
-isn't specified, pressing HOME will result in the activity and its task
-remaining in the system, possibly with no way to return to it.</p>
-
-<p>Be sure to read the documentation on the
-{@link android.R.styleable#AndroidManifestActivity_launchMode launchMode attribute}
-and the {@link android.content.Intent#setFlags Intent flags} for the details
-on these options.</p>
-
-<h2 id="Processes">Processes</h2>
-
-<p>In Android, processes are entirely an implementation detail of applications
-and not something the user is normally aware of.  Their main uses are simply:</p>
-
-<ul>
-<li> Improving stability or security by putting untrusted or unstable code
-into another process.
-<li> Reducing overhead by running the code of multiple .apks in the same
-process.
-<li> Helping the system manage resources by putting heavy-weight code in
-a separate process that can be killed independently of other parts of the
-application.
-</ul>
-
-<p>As described previously, the
-{@link android.R.styleable#AndroidManifestApplication_process process} attribute
-is used to control the process that particular application components run in.
-Note that this attribute can not be used to violate security of the system: if
-two .apks that are not sharing the same user ID try to run in the same process,
-this will not be allowed and different distinct processes will be created for
-each of them.</p>
-
-<p>See the <a href="{@docRoot}devel/security.html">security</a> document for
-more information on these security restrictions.</p>
-
-<h2 id="Threads">Threads</h2>
-
-<p>Every process has one or more threads running in it.  In most situations, Android
-avoids creating additional threads in a process, keeping an application
-single-threaded unless it creates its own threads.  An important repercussion
-of this is that all calls to {@link android.app.Activity},
-{@link android.content.BroadcastReceiver}, and {@link android.app.Service}
-instances are made only from the main thread of the process they are running in.</p>
-
-<p>Note that a new thread is <strong>not</strong> created for each
-Activity, BroadcastReceiver, Service, or ContentProvider instance:
-these application components are instantiated in the desired process (all in the
-same process unless otherwise specified), in the main thread of that process.
-This means that none of these components (including services) should perform
-long or blocking operations (such as networking calls or computation loops)
-when called by the system, since this will block
-all other components in the process.  You can use the standard library
-{@link java.lang.Thread} class or Android's {@link android.os.HandlerThread}
-convenience class to perform long operations on another thread.</p>
-
-<p>There are a few important exceptions to this threading rule:</p>
-
-<ul>
-<li><p>Calls on to an {@link android.os.IBinder} or interface implemented on
-an IBinder are dispatched from the thread calling them or a thread pool in the
-local process if coming from another process, <em>not</em>
-from the main thread of their process.  In particular, calls on to the IBinder
-of a {@link android.app.Service} will be called this way.  (Though
-calls to methods on Service itself are done from the main thread.)
-This means that <em>implementations of IBinder interfaces must always be
-written in a thread-safe way, since they can be called from any number of
-arbitrary threads at the same time</em>.</p></li>
-
-<li><p>Calls to the main methods of {@link android.content.ContentProvider}
-are dispatched from the calling thread or main thread as with IBinder.  The
-specific methods are documented in the ContentProvider class.
-This means that <em>implementations of these methods must always be
-written in a thread-safe way, since they can be called from any number of
-arbitrary threads at the same time</em>.</p></li>
-
-<li><p>Calls on {@link android.view.View} and its subclasses are made from the
-thread that the view's window is running in.  Normally this will be the main
-thread of the process, however if you create a thread and show a window from
-there then the window's view hierarchy will be called from that thread.</p></li>
-</ul>
diff --git a/docs/html/guide/basics/building-blocks.jd b/docs/html/guide/basics/building-blocks.jd
deleted file mode 100644
index b8a609e..0000000
--- a/docs/html/guide/basics/building-blocks.jd
+++ /dev/null
@@ -1,76 +0,0 @@
-page.title=Building Blocks
-@jd:body
-<h1>Android Building Blocks</h1>
-
-<p>You can think of an Android application as a collection of components, of
-various kinds. These components are for the most part quite loosely coupled,
-to the degree where you can accurately describe them as a federation of
-components rather than a single cohesive application.</p>
-
-<p>Generally, these components all run in the same system process. It's
-possible (and quite common) to create multiple threads within that process,
-and it's also possible to create completely separate child processes if you
-need to. Such cases are pretty uncommon though, because Android tries very
-hard to make processes transparent to your code.</p>
-
-<p>These are the most important parts of the Android APIs:</p>
-
-<dl>
-    <dt><a href="{@docRoot}devel/bblocks-manifest.html">AndroidManifest.xml</a></dt>
-    <dd>The AndroidManifest.xml file is the control file that tells the system
-    what to do with all the top-level components (specifically activities,
-    services, intent receivers, and content providers described below)
-    you've created.  For instance, this is the
-    "glue" that actually specifies which Intents your Activities receive.</dd>
-    
-    <dt>{@link android.app.Activity Activities}</dt>
-    <dd>An Activity is, fundamentally, an object that has a life cycle. An
-    Activity is a chunk of code that does some work; if necessary, that work
-    can include displaying a UI to the user. It doesn't have to, though - some
-    Activities never display UIs. Typically, you'll designate one of your
-    application's Activities as the entry point to your application. </dd>
-  
-  
-    <dt>{@link android.view.View Views}</dt>
-    <dd>A View is an object that knows how to draw itself to the screen.
-    Android user interfaces are comprised of trees of Views. If you want to
-    perform some custom graphical technique (as you might if you're writing a
-    game, or building some unusual new user interface widget) then you'd
-    create a View.</dd>
-  
-  
-    <dt>{@link android.content.Intent Intents}</dt>
-    <dd>An Intent is a simple message object that represents an "intention" to
-    do something. For example, if your application wants to display a web
-    page, it expresses its "Intent" to view the URI by creating an Intent
-    instance and handing it off to the system. The system locates some other
-    piece of code (in this case, the Browser) that knows how to handle that
-    Intent, and runs it. Intents can also be used to broadcast interesting
-    events (such as a notification) system-wide.</dd>
-  
-  
-    <dt>{@link android.app.Service Services}</dt>
-    <dd>A Service is a body of code that runs in the background. It can run in
-    its own process, or in the context of another application's process,
-    depending on its needs. Other components "bind" to a Service and invoke
-    methods on it via remote procedure calls. An example of a Service is a
-    media player; even when the user quits the media-selection UI, she
-    probably still intends for her music to keep playing. A Service keeps the
-    music going even when the UI has completed.</dd>
-  
-  
-    <dt>{@link android.app.NotificationManager Notifications}</dt>
-    <dd>A Notification is a small icon that appears in the status bar. Users
-    can interact with this icon to receive information. The most well-known
-    notifications are SMS messages, call history, and voicemail, but
-    applications can create their own. Notifications are the
-    strongly-preferred mechanism for alerting the user of something that needs
-    their attention.</dd>
-    
-    <dt>{@link android.content.ContentProvider ContentProviders}</dt>
-    <dd>A ContentProvider is a data storehouse that provides access to data on
-    the device; the classic example is the ContentProvider that's used to
-    access the user's list of contacts. Your application can access data that
-    other applications have exposed via a ContentProvider, and you can also
-    define your own ContentProviders to expose data of your own.</dd>
-</dl>
diff --git a/docs/html/guide/basics/fixme-gs-core-packages.jd b/docs/html/guide/basics/fixme-gs-core-packages.jd
deleted file mode 100644
index 5281990..0000000
--- a/docs/html/guide/basics/fixme-gs-core-packages.jd
+++ /dev/null
@@ -1,92 +0,0 @@
-page.title=Getting Started
-@jd:body
-<h1>Getting Started with Android</h1>
- 
-<p>To get started with Android, please read the following sections first:</p>
-<dl>
-    <dt><a href="{@docRoot}intro/installing.html">Installing the SDK and
-    Plugin</a></dt>
-    <dd>How to install the Android SDK and Eclipse plugin.</dd>
-    <dt><a href="{@docRoot}intro/develop-and-debug.html">Developing and Debugging</a></dt>
-    <dd>An introduction to developing and debugging Android applications in Eclipse,
-    plus information on using other IDEs.</dd>
-    <dt><a href="{@docRoot}intro/hello-android.html">Hello Android</a></dt>
-    <dd>Writing your first Android Application, the ever popular Hello World,
-    Android style.</dd>
-    <dt><a href="{@docRoot}intro/anatomy.html">Anatomy of an App</a></dt>
-    <dd>A guide to the structure and architecture of an Android
-    Application. This guide will help you understand the pieces that make up
-    an Android app.</dd>
-    <dt><a href="{@docRoot}intro/tutorial.html">Notepad Tutorial</a></dt>
-    <dd>This tutorial document will lead you through
-    constructing a real Android Application: A notepad which can create, edit
-    and delete notes, and covers many of the basic concepts with practical
-    examples.</dd>
-    <dt><a href="{@docRoot}intro/tools.html">Development Tools</a></dt>
-    <dd>The
-    command line tools included with the SDK, what they do, and how to use
-    them.</dd>
-    <dt><a href="{@docRoot}intro/appmodel.html">Application Model</a></dt>
-    <dd>A guide to Applications, Tasks, Processes, and Threads.
-    These are the elements that define the way your application is run by the 
-    system and presented to the user.</dd>
-    <dt><a href="{@docRoot}intro/lifecycle.html">Application Life Cycle</a></dt>
-    <dd>The important life-cycle details for
-    Applications and the Activities running inside of them.</dd>
-
-</dl>
-
-<h2>Other Introductory Material</h2>
-<p>After reading the sections above, the following Getting Started information is also very useful:</p>
-
-
-<h3>Core Packages</h3>
-<p> These are the basic packages that make up the Android SDK for writing
-applications. The packages are organized as layers, listed here from
-lowest-level to highest.</p>
-
-<dl>
-    <dt>{@link android.util}</dt>
-    <dd>contains various low-level utility classes, such
-    as specialized container classes, XML utilities, etc.</dd>
-    <dt>{@link android.os}</dt>
-    <dd> provides basic operating system services, message
-    passing, and inter-process communication.</dd>
-    <dt>{@link android.graphics}</dt><dd>is the core rendering package.</dd>
-    <dt>{@link android.text}, {@link android.text.method}, {@link
-    android.text.style}, and {@link android.text.util} </dt>
-    <dd>supply a rich set of
-    text processing tools, supporting rich text, input methods, etc.</dd>
-    <dt>{@link android.database}</dt>
-    <dd>contains low-level APIs for working with
-    databases.</dd>
-    <dt>{@link android.content}</dt>
-    <dd>provides various services for accessing data
-    on the device: applications installed on the device and their associated
-    resources, and content providers for persistent dynamic data.</dd>
-    <dt>{@link android.view}</dt>
-    <dd>is the core user-interface framework.</dd>
-    <dt>{@link android.widget}</dt>
-    <dd>supplies standard user interface elements
-    (lists, buttons, layout managers, etc) built from the view package.</dd>
-    <dt>{@link android.app}</dt>
-    <dd>provides the high-level application model,
-    implemented using Activities.</dd>
-</dl>
-
-<h3>Other Notable Packages</h3>
-
-<p> These packages provide additional domain-specific features of the Android
-platform. They are not necessary for basic application development.</p>
-
-<dl>
-    <dt>{@link android.provider}</dt>
-    <dd>contains definitions for various standard
-    content providers included with the platform.</dd>
-    <dt>{@link android.telephony}</dt>
-    <dd>provides APIs for interacting with the
-    device's phone stack.</dd>
-    <dt>{@link android.webkit}</dt>
-    <dd>includes various APIs for working with
-    web-based content.</dd>
-</dl>
diff --git a/docs/html/guide/basics/index.html b/docs/html/guide/basics/index.html
deleted file mode 100644
index 4881acf..0000000
--- a/docs/html/guide/basics/index.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<html>
-<head>
-<meta http-equiv="refresh" content="0;url=../index.html">
-</head>
-<body>
-<a href="../index.html">click here</a> if you are not redirected.
-</body>
-</html>
\ No newline at end of file
diff --git a/docs/html/guide/topics/security/index.jd b/docs/html/guide/topics/security/index.jd
deleted file mode 100644
index 775fc03..0000000
--- a/docs/html/guide/topics/security/index.jd
+++ /dev/null
@@ -1,65 +0,0 @@
-page.title=Security and Permissions
-page.landing=true
-page.landing.intro=Android's security architecture gives the user full control over what resources are accessible to each app, protecting the system itself and all apps in it. Learn how to use system permissions to request access to the resources your app needs and design your app for optimal security. 
-page.landing.image=
-
-@jd:body
-
-<div style="width=100%;padding-left:1em;">
-
-  <div style="float:left;clear:both;padding-top:20px;">
-    <p style="text-transform:uppercase;"><b style="color:#666;font-size:14px;">Blog Articles</b></p>
-
-    <div class="" style="border-top:2px solid #DDD;margin:1em 0;background-color:#F7F7F7;width:336px">
-
-      <div style="float:left;padding:8px;padding-right:16px;">
-        <img src="/assets/images/resource-article.png">
-      </div>
-
-      <div class="caption">
-        <p style="margin:0;padding:0;font-weight:bold;"><a href="">Accessibility: Are You Serving All Your Users?</a></p>
-        <p style="margin:0;padding:0">In the upcoming weeks, some of the older Client Login authentication keys will expire. 
-        If you generated the token you’re currently using to authenticate with the C2DM servers before October 2011, it will stop working.</p>
-
-        <p style="margin:0;padding:0;font-weight:bold;"><a href="">Android C2DM — Client Login key expiration</a></p>
-        <p  style="margin:0;padding:0">Accessibility is about making sure that Android users who have limited vision or other physical impairments can use your application just as well</p>
-
-        <p style="margin:0;padding:0;font-weight:bold;"><a href="">A Faster Emulator with Better Hardware Support</a></p>
-        <p  style="margin:0;padding:0">The Android emulator is a key tool for Android developers in building and testing their apps.
-        As the power and diversity of Android devices has grown quickly, it’s been hard for the emulator keep pace. </p>
-
-        <a href="">More &raquo;</a>
-      </div>
-    </div>
-  </div>
-
-  <div style="float:right;padding-top:20px;">
-    <p style="text-transform:uppercase;"><b style="color:#666;font-size:14px;">Training</b></p>
-
-    <div class="" style="border-top:2px solid #DDD;bordddser-top:2px solid #FF8800;margin:1em 0;background-color:#F7F7F7;width:336px">
-
-      <div style="float:left;padding:8px;padding-right:16px;">
-        <img src="/assets/images/resource-tutorial.png">
-      </div>
-
-      <div class="caption">
-        <p style="margin:0;padding:0;font-weight:bold;"><a href="">Managing the Activity Lifecycle</a></p>
-        <p  style="margin:0;padding:0">This class explains important lifecycle callback methods that each Activity
-        instance receives and how you can use them so your activity does what the user expects and does not consume system
-        resources when your activity doesn't need them.</p>
-
-        <p style="margin:0;padding:0;font-weight:bold;"><a href="">Supporting Different Devices</a></p>
-        <p  style="margin:0;padding:0">This class teaches you how to use basic platform features that leverage alternative
-        resources and other features so your app can provide an optimized user experience on a variety of Android-compatible devices,
-        using a single application package (APK).</p>
-
-        <p style="margin:0;padding:0;font-weight:bold;"><a href="">Sharing Content</a></p>
-        <p  style="margin:0;padding:0">This class covers some common ways you can send and receive content between
-        applications using Intent APIs and the ActionProvider object.</p>
-
-        <a href="">More &raquo;</a>
-      </div>
-    </div>
-</div>
-
-</div>
\ No newline at end of file
diff --git a/docs/html/guide/topics/security/security.jd b/docs/html/guide/topics/security/security.jd
deleted file mode 100644
index 9cdccae..0000000
--- a/docs/html/guide/topics/security/security.jd
+++ /dev/null
@@ -1,767 +0,0 @@
-page.title=Designing for Security
-@jd:body
-
-<div id="qv-wrapper">
-<div id="qv">
-<h2>In this document</h2>
-<ol>
-<li><a href="#Dalvik">Using Davlik Code</a></li>
-<li><a href="#Native">Using Native Code</a></li>
-<li><a href="#Data">Storing Data</a></li>
-<li><a href="#IPC">Using IPC</a></li>
-<li><a href="#Permissions">Using Permissions</a></li>
-<li><a href="#Networking">Using Networking</a></li>
-<li><a href="#DynamicCode">Dynamically Loading Code</a></li>
-<li><a href="#Input">Performing Input Validation</a></li>
-<li><a href="#UserData">Handling User Data</a></li>
-<li><a href="#Crypto">Using Cryptography</a></li>
-</ol>
-<h2>See also</h2>
-<ol>
-<li><a href="http://source.android.com/tech/security/index.html">Android
-Security Overview</a></li>
-<li><a href="{@docRoot}guide/topics/security/security.html">Android Security
-And Permissions</a></li>
-</ol>
-</div></div>
-<p>Android was designed so that most developers will be able to build
-applications using the default settings and not be confronted with difficult
-decisions about security.  Android also has a number of security features built
-into the operating system that significantly reduce the frequency and impact of
-application security issues.</p>
-
-<p>Some of the security features that help developers build secure applications
-include:
-<ul>
-<li>The Android Application Sandbox that isolates data and code execution on a
-per-application basis.</li>
-<li>Android application framework with robust implementations of common
-security functionality such as cryptography, permissions, and secure IPC.</li>
-<li>Technologies like ASLR, NX, ProPolice, safe_iop, OpenBSD dlmalloc, OpenBSD
-calloc, and Linux mmap_min_addr to mitigate risks associated with common memory
-management errors</li>
-<li>An encrypted filesystem that can be enabled to protect data on lost or
-stolen devices.</li>
-</ul></p>
-
-<p>Nevertheless, it is important for developers to be familiar with Android
-security best practices to make sure they take advantage of these capabilities
-and to reduce the likelihood of inadvertently introducing security issues that
-can affect their applications.</p>
-
-<p>This document is organized around common APIs and development techniques
-that can have security implications for your application and its users. As
-these best practices are constantly evolving, we recommend you check back
-occasionally throughout your application development process.</p>
-
-<a name="Dalvik"></a>
-<h2>Using Dalvik Code</h2>
-<p>Writing secure code that runs in virtual machines is a well-studied topic
-and many of the issues are not specific to Android.  Rather than attempting to
-rehash these topics, we’d recommend that you familiarize yourself with the
-existing literature. Two of the more popular resources are:
-<ul>
-<li><a href="http://www.securingjava.com/toc.html">
-http://www.securingjava.com/toc.html</a></li>
-<li><a
-href="https://www.owasp.org/index.php/Java_Security_Resources">
-https://www.owasp.org/index.php/Java_Security_Resources</a></li>
-</ul></p>
-
-<p>This document is focused on the areas which are Android specific and/or
-different from other environments.  For developers experienced with VM
-programming in other environments, there are two broad issues that may be
-different about writing apps for Android:
-<ul>
-<li>Some virtual machines, such as the JVM or .net runtime, act as a security
-boundary, isolating code from the underlying operating system capabilities.  On
-Android, the Dalvik VM is not a security boundary -- the application sandbox is
-implemented at the OS level, so Dalvik can interoperate with native code in the
-same application without any security constraints.</li>
-<li>Given the limited storage on mobile devices, it’s common for developers
-to want to build modular applications and use dynamic class loading.  When
-doing this consider both the source where you retrieve your application logic
-and where you store it locally. Do not use dynamic class loading from sources
-that are not verified, such as unsecured network sources or external storage,
-since that code can be modified to include malicious behavior.</li>
-</ul></p>
-
-<a name="Native"></a>
-<h2>Using Native Code</h2>
-
-<p>In general, we encourage developers to use the Android SDK for most
-application development, rather than using native code.   Applications built
-with native code are more complex, less portable, and more like to include
-common memory corruption errors such as buffer overflows.</p>
-
-<p>Android is built using the Linux kernel and being familiar with Linux
-development security best practices is especially useful if you are going to
-use native code. This document is too short to discuss all of those best
-practices, but one of the most popular resources is  “Secure Programming for
-Linux and Unix HOWTO”, available at <a
-href="http://www.dwheeler.com/secure-programs">
-http://www.dwheeler.com/secure-programs</a>.</p>
-
-<p>An important difference between Android and most Linux environments is the
-Application Sandbox.  On Android, all applications run in the Application
-Sandbox, including those written with native code.  At the most basic level, a
-good way to think about it for developers familiar with Linux is to know that
-every application is given a unique UID with very limited permissions. This is
-discussed in more detail in the <a
-href="http://source.android.com/tech/security/index.html">Android Security
-Overview</a> and you should be familiar with application permissions even if
-you are using native code.</p>
-
-<a name="Data"></a>
-<h2>Storing Data</h2>
-
-<h3>Using internal files</h3>
-
-<p>By default, files created on <a
-href="{@docRoot}guide/topics/data/data-storage.html#filesInternal">internal
-storage</a> are only accessible to the application that created the file. This
-protection is implemented by Android and is sufficient for most
-applications.</p>
-
-<p>Use of <a
-href="{@docRoot}reference/android/content/Context.html#MODE_WORLD_WRITEABLE">
-world writable</a> or <a
-href="{@docRoot}reference/android/content/Context.html#MODE_WORLD_READABLE">world
-readable</a> files for IPC is discouraged because it does not provide
-the ability to limit data access to particular applications, nor does it
-provide any control on data format. As an alternative, you might consider using
-a ContentProvider which provides read and write permissions, and can make
-dynamic permission grants on a case-by-case basis.</p>
-
-<p>To provide additional protection for sensitive data, some applications
-choose to encrypt local files using a key that is not accessible to the
-application. (For example, a key can be placed in a {@link java.security.KeyStore} and
-protected with a user password that is not stored on the device).  While this
-does not protect data from a root compromise that can monitor the user
-inputting the password,  it can provide protection for a lost device without <a
-href="http://source.android.com/tech/encryption/index.html">file system
-encryption</a>.</p>
-
-<h3>Using external storage</h3>
-
-<p>Files created on <a
-href="{@docRoot}guide/topics/data/data-storage.html#filesExternal">external
-storage</a>, such as SD Cards, are globally readable and writable.  Since
-external storage can be removed by the user and also modified by any
-application,  applications should not store sensitive information using
-external storage.</p>
-
-<p>As with data from any untrusted source, applications should perform input
-validation when handling data from external storage (see Input Validation
-section).  We strongly recommend that applications not store executables or
-class files on external storage prior to dynamic loading.  If an application
-does retrieve executable files from external storage they should be signed and
-cryptographically verified prior to dynamic loading.</p>
-
-<h3>Using content providers</h3>
-
-<p>ContentProviders provide a structured storage mechanism that can be limited
-to your own application, or exported to allow access by other applications. By
-default, a <code>
-<a href="{@docRoot}reference/android/content/ContentProvider.html">
-ContentProvider</a></code> is
-<a href="{@docRoot}guide/topics/manifest/provider-element.html#exported">exported
-</a> for use by other applications.  If you do not intend to provide other
-applications with access to your<code>
-<a href="{@docRoot}reference/android/content/ContentProvider.html">
-ContentProvider</a></code>, mark them as <code><a
-href="{@docRoot}guide/topics/manifest/provider-element.html#exported">
-android:exported=false</a></code> in the application manifest.</p>
-
-<p>When creating a <code>
-<a href="{@docRoot}reference/android/content/ContentProvider.html">ContentProvider
-</a></code> that will be exported for use by other applications, you can specify
-a single
-<a href="{@docRoot}guide/topics/manifest/provider-element.html#prmsn">permission
-</a> for reading and writing, or distinct permissions for reading and writing
-within the manifest. We recommend that you limit your permissions to those
-required to accomplish the task at hand. Keep in mind that it’s usually
-easier to add permissions later to expose new functionality than it is to take
-them away and break existing users.</p>
-
-<p>If you are using a <code>
-<a href="{@docRoot}reference/android/content/ContentProvider.html">
-ContentProvider</a></code> for sharing data between applications built by the
-same developer, it is preferable to use
-<a href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">signature
-level permissions</a>.  Signature permissions do not require user confirmation,
-so they provide a better user experience and more controlled access to the
-<code>
-<a href="{@docRoot}reference/android/content/ContentProvider.html">
-ContentProvider</a></code>.</p>
-
-<p>ContentProviders can also provide more granular access by declaring the <a
-href="{@docRoot}guide/topics/manifest/provider-element.html#gprmsn">
-grantUriPermissions</a> element and using the <code><a
-href="{@docRoot}reference/android/content/Intent.html#FLAG_GRANT_READ_URI_PERMISSION">FLAG_GRANT_READ_URI_PERMISSION</a></code>
-and <code><a
-href="{@docRoot}reference/android/content/Intent.html#FLAG_GRANT_WRITE_URI_PERMISSION">FLAG_GRANT_WRITE_URI_PERMISSION</a></code>
-flags in the Intent object
-that activates the component.  The scope of these permissions can be further
-limited by the <code><a
-href="{@docRoot}guide/topics/manifest/grant-uri-permission-element.html">
-grant-uri-permission element</a></code>.</p>
-
-<p>When accessing a <code>
-<a href="{@docRoot}reference/android/content/ContentProvider.html">
-ContentProvider</a></code>, use parameterized query methods such as <code>
-<a href="{@docRoot}reference/android/content/ContentProvider.html#query(android.net.Uri,%20java.lang.String[],%20java.lang.String,%20java.lang.String[],%20java.lang.String)">query()</a></code>, <code><a
-href="{@docRoot}reference/android/content/ContentProvider.html#update(android.net.Uri,%20android.content.ContentValues,%20java.lang.String,%20java.lang.String[])">update()</a></code>, and <code><a
-href="{@docRoot}reference/android/content/ContentProvider.html#delete(android.net.Uri,%20java.lang.String,%20java.lang.String[])">delete()</a></code> to avoid
-potential <a href="http://en.wikipedia.org/wiki/SQL_injection">SQL
-Injection</a> from untrusted data. Note that using parameterized methods is not
-sufficient if the <code>selection</code> is built by concatenating user data
-prior to submitting it to the method.</p>
-
-<p>Do not have a false sense of security about the write permission.  Consider
-that the write permission allows SQL statements which make it possible for some
-data to be confirmed using creative <code>WHERE</code> clauses and parsing the
-results. For example, an attacker might probe for presence of a specific phone
-number in a call-log by modifying a row only if that phone number already
-exists. If the content provider data has predictable structure, the write
-permission may be equivalent to providing both reading and writing.</p>
-
-<a name="IPC"></a>
-<h2>Using Interprocess Communication (IPC)</h2>
-
-<p>Some Android applications attempt to implement IPC using traditional Linux
-techniques such as network sockets and shared files.  We strongly encourage the
-use of Android system functionality for IPC such as Intents, Binders, Services,
-and Receivers.  The Android IPC mechanisms allow you to verify the identity of
-the application connecting to your IPC and set security policy for each IPC
-mechanism.</p>
-
-<p>Many of the security elements are shared across IPC mechanisms. <a
-href="{@docRoot}reference/android/content/BroadcastReceiver.html">
-Broadcast Receivers</a>, <a
-href="{@docRoot}reference/android/R.styleable.html#AndroidManifestActivity">
-Activities</a>, and <a
-href="{@docRoot}reference/android/R.styleable.html#AndroidManifestService">
-Services</a> are all declared in the application manifest.  If your IPC mechanism is
-not intended for use by other applications, set the <a
-href="{@docRoot}guide/topics/manifest/service-element.html#exported">{@code android:exported}</a>
-property to false.  This is useful for applications that consist of multiple processes
-within the same UID, or if you decide late in development that you do not
-actually want to expose functionality as IPC but you don’t want to rewrite
-the code.</p>
-
-<p>If your IPC is intended to be accessible to other applications, you can
-apply a security policy by using the <a
-href="{@docRoot}reference/android/R.styleable.html#AndroidManifestPermission">
-Permission</a> tag. If IPC is between applications built by the same developer,
-it is preferable to use <a
-href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">signature
-level permissions</a>.  Signature permissions do not require user confirmation,
-so they provide a better user experience and more controlled access to the IPC
-mechanism.</p>
-
-<p>One area that can introduce confusion is the use of intent filters. Note
-that Intent filters should not be considered a security feature -- components
-can be invoked directly and may not have data that would conform to the intent
-filter. You should perform input validation within your intent receiver to
-confirm that it is properly formatted for the invoked receiver, service, or
-activity.</p>
-
-<h3>Using intents</h3>
-
-<p>Intents are the preferred mechanism for asynchronous IPC in Android.
-Depending on your application requirements, you might use <code><a
-href="{@docRoot}reference/android/content/Context.html#sendBroadcast(android.content.Intent)">sendBroadcast()</a></code>, 
-<code><a
-href="{@docRoot}reference/android/content/Context.html#sendOrderedBroadcast(android.content.Intent,%20java.lang.String)">sendOrderedBroadcast()</a></code>,
-or direct an intent to a specific application component.</p>
-
-<p>Note that ordered broadcasts can be “consumed” by a recipient, so they
-may not be delivered to all applications.  If you are sending an Intent where
-delivery to a specific receiver is required, the intent must be delivered
-directly to the receiver.</p>
-
-<p>Senders of an intent can verify that the recipient has a permission
-specifying a non-Null Permission upon sending.  Only applications with that
-Permission will receive the intent.  If data within a broadcast intent may be
-sensitive, you should consider applying a permission to make sure that
-malicious applications cannot register to receive those messages without
-appropriate permissions.  In those circumstances, you may also consider
-invoking the receiver directly, rather than raising a broadcast.</p>
-
-<h3>Using binder and AIDL interfaces</h3>
-
-<p><a href="{@docRoot}reference/android/os/Binder.html">Binders</a> are the
-preferred mechanism for RPC-style IPC in Android. They provide a well-defined
-interface that enables mutual authentication of the endpoints, if required.</p>
-
-<p>We strongly encourage designing interfaces in a manner that does not require
-interface specific permission checks. Binders are not declared within the
-application manifest, and therefore you cannot apply declarative permissions
-directly to a Binder.  Binders generally inherit permissions declared in the
-application manifest for the Service or Activity within which they are
-implemented.  If you are creating an interface that requires authentication
-and/or access controls on a specific binder interface, those controls must be
-explicitly added as code in the interface.</p>
-
-<p>If providing an interface that does require access controls, use <code><a
-href="{@docRoot}reference/android/content/Context.html#checkCallingPermission(java.lang.String)">checkCallingPermission()</a></code>
-to verify whether the
-caller of the Binder has a required permission. This is especially important
-before accessing a Service on behalf of the caller, as the identify of your
-application is passed to other interfaces.  If invoking an interface provided
-by a Service, the <code><a
-href="{@docRoot}reference/android/content/Context.html#bindService(android.content.Intent,%20android.content.ServiceConnection,%20int)">bindService()</a></code>
- invocation may fail if you do not have permission to access the given Service.
- If calling an interface provided locally by your own application, it may be
-useful to use the <code><a
-href="{@docRoot}reference/android/os/Binder.html#clearCallingIdentity()">
-clearCallingIdentity()</a></code> to satisfy internal security checks.</p>
-
-<h3>Using broadcast receivers</h3>
-
-<p>Broadcast receivers are used to handle asynchronous requests initiated via
-an intent.</p>
-
-<p>By default, receivers are exported and can be invoked by any other
-application. If your <code><a
-href="{@docRoot}reference/android/content/BroadcastReceiver.html">
-BroadcastReceivers</a></code> is intended for use by other applications, you
-may want to apply security permissions to receivers using the <code><a
-href="{@docRoot}guide/topics/manifest/receiver-element.html">
-&lt;receiver&gt;</a></code> element within the application manifest.  This will
-prevent applications without appropriate permissions from sending an intent to
-the <code><a
-href="{@docRoot}reference/android/content/BroadcastReceiver.html">
-BroadcastReceivers</a></code>.</p>
-
-<h3>Using Services</h3>
-
-<p>Services are often used to supply functionality for other applications to
-use. Each service class must have a corresponding <service> declaration in its
-package's AndroidManifest.xml.</p>
-
-<p>By default, Services are exported and can be invoked by any other
-application.  Services can be protected using the <a
-href="{@docRoot}guide/topics/manifest/service-element.html#prmsn">{@code android:permission}</a>
-attribute
-within the manifest’s <code><a
-href="{@docRoot}guide/topics/manifest/service-element.html">
-&lt;service&gt;</a></code> tag. By doing so, other applications will need to declare
-a corresponding <code><a
-href="{@docRoot}guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a>
-</code> element in their own manifest to be
-able to start, stop, or bind to the service.</p>
-
-<p>A Service can protect individual IPC calls into it with permissions, by
-calling <code><a
-href="{@docRoot}reference/android/content/Context.html#checkCallingPermission(java.lang.String)">checkCallingPermission()</a></code>
-before executing
-the implementation of that call.  We generally recommend using the
-declarative permissions in the manifest, since those are less prone to
-oversight.</p>
-
-<h3>Using Activities</h3>
-
-<p>Activities are most often used for providing the core user-facing
-functionality of an application. By default, Activities are exported and
-invokable by other applications only if they have an intent filter or binder
-declared.  In general, we recommend that you specifically declare a Receiver or
-Service to handle IPC, since this modular approach reduces the risk of exposing
-functionality that is not intended for use by other applications.</p>
-
-<p>If you do expose an Activity for purposes of IPC, the  <code><a
-href="{@docRoot}guide/topics/manifest/activity-element.html#prmsn">android:permission</a></code>
-attribute in the  <code><a
-href="{@docRoot}guide/topics/manifest/activity-element.html">
-&lt;activity&gt;</a></code> declaration in the application manifest can be used to
-restrict access to only those applications which have the stated
-permissions.</p>
-
-<a name="Permissions"></a>
-<h2>Using Permissions</h2>
-
-<h3>Requesting Permissions</h3>
-
-<p>We recommend minimizing the number of permissions requested by an
-application. Not having access to sensitive permissions reduces the risk of
-inadvertently misusing those permissions, can improve user adoption, and makes
-applications less attractive targets for attackers.</p>
-
-<p>If it is possible to design your application in a way that does not require
-a permission, that is preferable.  For example, rather than requesting access
-to device information to create an identifier, create a <a
-href="{@docRoot}reference/java/util/UUID.html">GUID</a> for your application.
-(This specific example is also discussed in Handling User Data) Or, rather than
-using external storage, store data in your application directory.</p>
-
-<p>If a permission is not required, do not request it.  This sounds simple, but
-there has been quite a bit of research into the frequency of over-requesting
-permissions. If you’re interested in the subject you might start with this
-research paper published by U.C. Berkeley: <a
-href="http://www.eecs.berkeley.edu/Pubs/TechRpts/2011/EECS-2011-48.pdf">
-http://www.eecs.berkeley.edu/Pubs/TechRpts/2011/EECS-2011-48.pdf</a></p>
-
-<p>In addition to requesting permissions, your application can use <a
-href="{@docRoot}guide/topics/manifest/permission-element.html">permissions</a>
-to protect IPC that is security sensitive and will be exposed to other
-applications -- such as a <code><a
-href="{@docRoot}reference/android/content/ContentProvider.html">
-ContentProvider</a></code>.  In general, we recommend using access controls
-other than user confirmed permissions where possible since permissions can
-be confusing for users. For example, consider using the <a
-href="{@docRoot}guide/topics/manifest/permission-element.html#plevel">signature
-protection level</a> on permissions for IPC communication between applications
-provided by a single developer.</p>
-
-<p>Do not cause permission re-delegation.  This occurs when an app exposes data
-over IPC that is only available because it has a specific permission, but does
-not require that permission of any clients of it’s IPC interface. More
-details on the potential impacts, and frequency of this type of problem is
-provided in this research paper published at USENIX: <a
-href="http://www.cs.berkeley.edu/~afelt/felt_usenixsec2011.pdf">http://www.cs.be
-rkeley.edu/~afelt/felt_usenixsec2011.pdf</a></p>
-
-<h3>Creating Permissions</h3>
-
-<p>Generally, you should strive to create as few permissions as possible while
-satisfying your security requirements.  Creating a new permission is relatively
-uncommon for most applications, since <a
-href="{@docRoot}reference/android/Manifest.permission.html">system-defined
-permissions</a> cover many situations.  Where appropriate,
-perform access checks using existing permissions.</p>
-
-<p>If you must create a new permission, consider whether you can accomplish
-your task with a Signature permission.  Signature permissions are transparent
-to the user and only allow access by applications signed by the same developer
-as application performing the permission check.  If you create a Dangerous
-permission, then the user needs to decide whether to install the application.
-This can be confusing for other developers, as well as for users.</p>
-
-<p>If you create a Dangerous permission, there are a number of complexities
-that you need to consider.
-<ul>
-<li>The permission must have a string that concisely expresses to a user the
-security decision they will be required to make.</li>
-<li>The permission string must be localized to many different languages.</li>
-<li>Uses may choose not to install an application because a permission is
-confusing or perceived as risky.</li>
-<li>Applications may request the permission when the creator of the permission
-has not been installed.</li>
-</ul></p>
-
-<p>Each of these poses a significant non-technical challenge for an application
-developer, which is why we discourage the use of Dangerous permission.</p>
-
-<a name="Networking"></a>
-<h2>Using Networking</h2>
-
-<h3>Using IP Networking</h3>
-
-<p>Networking on Android is not significantly different from Linux
-environments.  The key consideration is making sure that appropriate protocols
-are used for sensitive data, such as <a
-href="{@docRoot}reference/javax/net/ssl/HttpsURLConnection.html">HTTPS</a> for
-web traffic.   We prefer use of HTTPS over HTTP anywhere that HTTPS is
-supported on the server, since mobile devices frequently connect on networks
-that are not secured, such as public WiFi hotspots.</p>
-
-<p>Authenticated, encrypted socket-level communication can be easily
-implemented using the <code><a
-href="{@docRoot}reference/javax/net/ssl/SSLSocket.html">SSLSocket</a></code>
-class.  Given the frequency with which Android devices connect to unsecured
-wireless networks using WiFi, the use of secure networking is strongly
-encouraged for all applications.</p>
-
-<p>We have seen some applications use <a
-href="http://en.wikipedia.org/wiki/Localhost">localhost</a> network ports for
-handling sensitive IPC.  We discourage this approach since these interfaces are
-accessible by other applications on the device.  Instead, use an Android IPC
-mechanism where authentication is possible such as a Service and Binder.  (Even
-worse than using loopback is to bind to INADDR_ANY since then your application
-may receive requests from anywhere.  We’ve seen that, too.)</p>
-
-<p>Also, one common issue that warrants repeating is to make sure that you do
-not trust data downloaded from HTTP or other insecure protocols.  This includes
-validation of input in <code><a
-href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code> and
-any responses to intents issued against HTTP.</p>
-
-<h3>Using Telephony Networking</h3>
-
-<p>SMS is the telephony protocol most frequently used by Android developers.
-Developers should keep in mind that this protocol was primarily designed for
-user-to-user communication and is not well-suited for some application
-purposes. Due to the limitations of SMS, we strongly recommend the use of <a
-href="http://code.google.com/android/c2dm/">C2DM</a> and IP networking for
-sending data messages to devices.</p>
-
-<p>Many developers do not realize that SMS is not encrypted or strongly
-authenticated on the network or on the device.  In particular, any SMS receiver
-should expect that a malicious user may have sent the SMS to your application
--- do not rely on unauthenticated SMS data to perform sensitive commands.
-Also, you should be aware that SMS may be subject to spoofing and/or
-interception on the network.  On the Android-powered device itself, SMS
-messages are transmitted as Broadcast intents, so they may be read or captured
-by other applications that have the READ_SMS permission.</p>
-
-<a name="DynamicCode"></a>
-<h2>Dynamically Loading Code</h2>
-
-<p>We strongly discourage loading code from outside of the application APK.
-Doing so significantly increases the likelihood of application compromise due
-to code injection or code tampering.  It also adds complexity around version
-management and application testing.  Finally, it can make it impossible to
-verify the behavior of an application, so it may be prohibited in some
-environments.</p>
-
-<p>If your application does dynamically load code, the most important thing to
-keep in mind about dynamically loaded code is that it runs with the same
-security permissions as the application APK.  The user made a decision to
-install your application based on your identity, and they are expecting that
-you provide any code run within the application, including code that is
-dynamically loaded.</p>
-
-<p>The major security risk associated with dynamically loading code is that the
-code needs to come from a verifiable source. If the modules are included
-directly within your APK, then they cannot be modified by other applications.
-This is true whether the code is a native library or a class being loaded using
-<a href="{@docRoot}reference/dalvik/system/DexClassLoader.html">
-<code>DexClassLoader</code></a>.  We have seen many instances of applications
-attempting to load code from insecure locations, such as downloaded from the
-network over unencrypted protocols or from world writable locations such as
-external storage. These locations could allow someone on the network to modify
-the content in transit, or another application on a users device to modify the
-content, respectively.</p>
-
-
-<h3>Using WebView</h3>
-
-<p>Since WebView consumes web content that can include HTML and JavaScript,
-improper use can introduce common web security issues such as <a
-href="http://en.wikipedia.org/wiki/Cross_site_scripting">cross-site-scripting</a
-> (JavaScript injection).  Android includes a number of mechanisms to reduce
-the scope of these potential issues by limiting the capability of WebView to
-the minimum functionality required by your application.</p>
-
-<p>If your application does not directly use JavaScript within a <code><a
-href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code>, do
-not call
-<a href="{@docRoot}reference/android/webkit/WebSettings.html#setJavaScriptEnabled(boolean)">
-<code>setJavaScriptEnabled()</code></a>. We have seen this method invoked
-in sample code that might be repurposed in production application -- so
-remove it if necessary. By default, <code><a
-href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code> does
-not execute JavaScript so cross-site-scripting is not possible.</p>
-
-<p>Use <code><a
-href="{@docRoot}reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)">addJavaScriptInterface()</a></code> with
-particular care because it allows JavaScript to invoke operations that are
-normally reserved for Android applications.  Only expose <code><a
-href="{@docRoot}reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)">addJavaScriptInterface()</a></code> to
-sources from which all input is trustworthy.  If untrusted input is allowed,
-untrusted JavaScript may be able to invoke Android methods.  In general, we
-recommend only exposing <code><a
-href="{@docRoot}reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)">addJavaScriptInterface()</a></code> to
-JavaScript that is contained within your application APK.</p>
-
-<p>Do not trust information downloaded over HTTP, use HTTPS instead.  Even if
-you are connecting only to a single website that you trust or control, HTTP is
-subject to <a
-href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack">MiTM</a> attacks
-and interception of data.  Sensitive capabilities using <code><a
-href="{@docRoot}reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)">addJavaScriptInterface()</a></code> should
-not ever be exposed to unverified script downloaded over HTTP. Note that even
-with the use of HTTPS,
-<code><a
-href="{@docRoot}reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)">addJavaScriptInterface()</a></code>
-increases the attack surface of your application to include the server
-infrastructure and all CAs trusted by the Android-powered device.</p>
-
-<p>If your application accesses sensitive data with a <code><a
-href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code>, you
-may want to use the <code><a
-href="{@docRoot}reference/android/webkit/WebView.html#clearCache(boolean)">
-clearCache()</a></code> method to delete any files stored locally. Server side
-headers like no-cache can also be used to indicate that an application should
-not cache particular content.</p>
-
-<a name="Input"></a>
-<h2>Performing Input Validation</h2>
-
-<p>Insufficient input validation is one of the most common security problems
-affecting applications, regardless of what platform they run on. Android does
-have platform-level countermeasures that reduce the exposure of applications to
-input validation issues, you should use those features where possible. Also
-note that selection of type-safe languages tends to reduce the likelihood of
-input validation issues.  We strongly recommend building your applications with
-the Android SDK.</p>
-
-<p>If you are using native code, then any data read from files, received over
-the network, or received from an IPC has the potential to introduce a security
-issue.  The most common problems are <a
-href="http://en.wikipedia.org/wiki/Buffer_overflow">buffer overflows</a>, <a
-href="http://en.wikipedia.org/wiki/Double_free#Use_after_free">use after
-free</a>, and <a
-href="http://en.wikipedia.org/wiki/Off-by-one_error">off-by-one errors</a>.
-Android provides a number of technologies like ASLR and DEP that reduce the
-exploitability of these errors, but they do not solve the underlying problem.
-These can be prevented by careful handling of pointers and managing of
-buffers.</p>
-
-<p>Dynamic, string based languages such as JavaScript and SQL are also subject
-to input validation problems due to escape characters and <a
-href="http://en.wikipedia.org/wiki/Code_injection">script injection</a>.</p>
-
-<p>If you are using data within queries that are submitted to SQL Database or a
-Content Provider, SQL Injection may be an issue.  The best defense is to use
-parameterized queries, as is discussed in the ContentProviders section.
-Limiting permissions to read-only or write-only can also reduce the potential
-for harm related to SQL Injection.</p>
-
-<p>If you are using <code><a
-href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code>, then
-you must consider the possibility of XSS.  If your application does not
-directly use JavaScript within a <code><a
-href="{@docRoot}reference/android/webkit/WebView.html">WebView</a></code>, do
-not call setJavaScriptEnabled() and XSS is no longer possible. If you must
-enable JavaScript then the WebView section provides other security best
-practices.</p>
-
-<p>If you cannot use the security features above, we strongly recommend the use
-of well-structured data formats and verifying that the data conforms to the
-expected format. While blacklisting of characters or character-replacement can
-be an effective strategy, these techniques are error-prone in practice and
-should be avoided when possible.</p>
-
-<a name="UserData"></a>
-<h2>Handling User Data</h2>
-
-<p>In general, the best approach is to minimize use of APIs that access
-sensitive or personal user data. If you have access to data and can avoid
-storing or transmitting the information, do not store or transmit the data.
-Finally, consider if there is a way that your application logic can be
-implemented using a hash or non-reversible form of the data.  For example, your
-application might use the hash of an an email address as a primary key, to
-avoid transmitting or storing the email address.  This reduces the chances of
-inadvertently exposing data, and it also reduces the chance of attackers
-attempting to exploit your application.</p>
-
-<p>If your application accesses personal information such as passwords or
-usernames, keep in mind that some jurisdictions may require you to provide a
-privacy policy explaining your use and storage of that data.  So following the
-security best practice of minimizing access to user data may also simplify
-compliance.</p>
-
-<p>You should also consider whether your application might be inadvertently
-exposing personal information to other parties such as third-party components
-for advertising or third-party services used by your application. If you don't
-know why a component or service requires a personal information, don’t
-provide it.  In general, reducing the access to personal information by your
-application will reduce the potential for problems in this area.</p>
-
-<p>If access to sensitive data is required, evaluate whether that information
-must be transmitted to a server, or whether the operation can be performed on
-the client.  Consider running any code using sensitive data on the client to
-avoid transmitting user data.</p>
-
-<p>Also, make sure that you do not inadvertently expose user data to other
-application on the device through overly permissive IPC, world writable files,
-or network sockets. This is a special case of permission redelegation,
-discussed in the Requesting Permissions section.</p>
-
-<p>If a GUID is required, create a large, unique number and store it.  Do not
-use phone identifiers such as the phone number or IMEI which may be associated
-with personal information.  This topic is discussed in more detail in the <a
-href="http://android-developers.blogspot.com/2011/03/identifying-app-installations.html">Android Developer Blog</a>.</p>
-
-<p>Application developers should be careful writing to on-device logs.
-In Android, logs are a shared resource, and are available
-to an application with the
-<a href="{@docRoot}reference/android/Manifest.permission.html#READ_LOGS">
-<code>READ_LOGS</code></a> permission. Even though the phone log data
-is temporary and erased on reboot, inappropriate logging of user information
-could inadvertently leak user data to other applications.</p>
-
-
-<h3>Handling Credentials</h3>
-
-<p>In general, we recommend minimizing the frequency of asking for user
-credentials -- to make phishing attacks more conspicuous, and less likely to be
-successful.  Instead use an authorization token and refresh it.</p>
-
-<p>Where possible, username and password should not be stored on the device.
-Instead, perform initial authentication using the username and password
-supplied by the user, and then use a short-lived, service-specific
-authorization token.</p>
-
-<p>Services that will be accessible to multiple applications should be accessed
-using <code>
-<a href="{@docRoot}reference/android/accounts/AccountManager.html">
-AccountManager</a></code>. If possible, use the <code><a
-href="{@docRoot}reference/android/accounts/AccountManager.html">
-AccountManager</a></code> class to invoke a cloud-based service and do not store
-passwords on the device.</p>
-
-<p>After using <code><a
-href="{@docRoot}reference/android/accounts/AccountManager.html">
-AccountManager</a></code> to retrieve an Account, check the <code><a
-href="{@docRoot}reference/android/accounts/Account.html#CREATOR">CREATOR</a>
-</code> before passing in any credentials, so that you do not inadvertently pass
-credentials to the wrong application.</p>
-
-<p>If credentials are to be used only by applications that you create, then you
-can verify the application which accesses the <code><a
-href="{@docRoot}reference/android/accounts/AccountManager.html">
-AccountManager</a></code> using <code><a
-href="{@docRoot}reference/android/content/pm/PackageManager.html#checkSignatures(java.lang.String,%20java.lang.String)">checkSignature()</a></code>.
-Alternatively, if only one application will use the credential, you might use a
-{@link java.security.KeyStore} for
-storage.</p>
-
-<a name="Crypto"></a>
-<h2>Using Cryptography</h2>
-
-<p>In addition to providing data isolation, supporting full-filesystem
-encryption, and providing secure communications channels Android provides a
-wide array of algorithms for protecting data using cryptography.</p>
-
-<p>In general, try to use the highest level of pre-existing framework
-implementation that can  support your use case.  If you need to securely
-retrieve a file from a known location, a simple HTTPS URI may be adequate and
-require no knowledge of cryptography on your part.  If you need a secure
-tunnel, consider using
-<a href="{@docRoot}reference/javax/net/ssl/HttpsURLConnection.html">
-<code>HttpsURLConnection</code></a> or <code><a
-href="{@docRoot}reference/javax/net/ssl/SSLSocket.html">SSLSocket</a></code>,
-rather than writing your own protocol.</p>
-
-<p>If you do find yourself needing to implement your own protocol, we strongly
-recommend that you not implement your own cryptographic algorithms. Use
-existing cryptographic algorithms such as those in the implementation of AES or
-RSA provided in the <code><a
-href="{@docRoot}reference/javax/crypto/Cipher.html">Cipher</a></code> class.</p>
-
-<p>Use a secure random number generator (
-<a href="{@docRoot}reference/java/security/SecureRandom.html">
-<code>SecureRandom</code></a>) to initialize any cryptographic keys (<a
-href="{@docRoot}reference/javax/crypto/KeyGenerator.html">
-<code>KeyGenerator</code></a>). Use of a key that is not generated with a secure random
-number generator significantly weakens the strength of the algorithm, and may
-allow offline attacks.</p>
-
-<p>If you need to store a key for repeated use, use a mechanism like {@link java.security.KeyStore} that
-provides a mechanism for long term storage and retrieval of cryptographic
-keys.</p>
-
-<h2>Conclusion</h2>
-
-<p>Android provides developers with the ability to design applications with a
-broad range of security requirements.  These best practices will help you make
-sure that your application takes advantage of the security benefits provided by
-the platform.</p>
-
-<p>You can receive more information on these topics and discuss security best
-practices with other developers in the <a
-href="http://groups.google.com/group/android-security-discuss">Android Security
-Discuss</a> Google Group</p>
diff --git a/docs/html/guide/topics/ui/layout-objects.jd b/docs/html/guide/topics/ui/layout-objects.jd
deleted file mode 100644
index 1d15ad60..0000000
--- a/docs/html/guide/topics/ui/layout-objects.jd
+++ /dev/null
@@ -1,6 +0,0 @@
-page.title=Layouts
-parent.title=User Interface
-parent.link=index.html
-@jd:body
-
-<p>You should have been redirected to <a href="declaring-layout.html">Layouts</a>.</p>
\ No newline at end of file
diff --git a/docs/html/guide/topics/ui/notifiers/index.jd b/docs/html/guide/topics/ui/notifiers/index.jd
deleted file mode 100644
index caf0df7..0000000
--- a/docs/html/guide/topics/ui/notifiers/index.jd
+++ /dev/null
@@ -1,92 +0,0 @@
-page.title=Notifications
-parent.title=User Interface
-parent.link=../index.html
-@jd:body
-
-<p>Several types of situations may arise that require you to notify the user 
-about an event that occurs in your application. Some events require the user to respond
-and others do not. For example:</p>
-<ul>
-  <li>When an event such as saving a file is complete, a small message
-should appear to confirm that the save was successful.</li>
-  <li>If the application is running in the background and needs the user's attention, 
-the application should create a notification that allows the user to respond at 
-his or her convenience.</li>
-  <li>If the application is 
-performing work that the user must wait for (such as loading a file), 
-the application should show a hovering progress wheel or bar.</li>
-</ul>
-
-<p>Each of these notification tasks can be achieved using a different technique:</p>
-<ul>
-  <li>A <a href="#Toast">Toast Notification</a>, for brief messages that come 
-  from the background.</li>
-  <li>A <a href="#StatusBar">Status Notification</a>, for persistent reminders 
-  that come from the background and request the user's response.</li>
-  <li>A <a href="#Dialog">Dialog Notification</a>, for Activity-related notifications.</li>
-</ul>
-
-<p>This document summarizes each of these techniques for notifying the user and includes
-links to full documentation.</p>
-
-
-<h2 id="Toast">Toast Notification</h2>
-
-<img src="{@docRoot}images/toast.png" alt="" style="float:right" />
-
-<p>A toast notification is a message that pops up on the surface of the window.
-It only fills the amount of space required for the message and the user's current
-activity remains visible and interactive. The notification automatically fades in and 
-out, and does not accept interaction events. Because a toast can be created from a background 
-{@link android.app.Service}, it appears even if the application isn't visible.</p>
-
-<p>A toast is best for short text messages, such as "File saved,"
-when you're fairly certain the user is paying attention 
-to the screen. A toast can not accept user interaction events; if you'd like
-the user to respond and take action, consider using a 
-<a href="#StatusBar">Status Notification</a> instead.</p>
-
-<p>For more information, refer to <a href="toasts.html">Toast Notifications</a>.</p>
-
-
-<h2 id="StatusBar">Status Notification</h2>
-
-<img src="{@docRoot}images/notifications_window.png" alt="" style="float:right; clear:right;" />
-
-<p>A status notification adds an icon to the system's status bar 
-(with an optional ticker-text message) and an expanded message in the "Notifications" window.
-When the user selects the expanded message, Android fires an 
-{@link android.content.Intent} that is defined by the notification (usually to launch an 
-{@link android.app.Activity}).
-You can also configure the notification to alert the user with a sound, a vibration, and flashing
-lights on the device.</p>
-
-<p>This kind of notification is ideal when your application is working in
-a background {@link android.app.Service} and needs to 
-notify the user about an event. If you need to alert the user about an event that occurs 
-while your Activity is still in focus, consider using a 
-<a href="#Dialog">Dialog Notification</a> instead.</p>
-
-<p>For more information, refer to 
-<a href="notifications.html">Status Notifications</a>.</p>
-
-
-<h2 id="Dialog">Dialog Notification</h2>
-
-<img src="{@docRoot}images/dialog_progress_spinning.png" alt="" style="float:right" />
-
-<p>A dialog is usually a small window that appears in front of the current Activity.
-The underlying Activity loses focus and the dialog accepts all user interaction. 
-Dialogs are normally used
-for notifications and short activities that directly relate to the application in progress.</p>
-
-<p>You should use a dialog when you need to show a progress bar or a short
-message that requires confirmation from the user (such as an alert with "OK" and "Cancel" buttons). 
-You can use also use dialogs as integral components
-in your application's UI and for other purposes besides notifications.
-For a complete discussion on all the available types of dialogs, 
-including its uses for notifications, refer to 
-<a href="{@docRoot}guide/topics/ui/dialogs.html">Dialogs</a>.</p>
-
-
-
diff --git a/docs/html/sdk/installing/next.jd b/docs/html/sdk/installing/next.jd
deleted file mode 100644
index cb974a4..0000000
--- a/docs/html/sdk/installing/next.jd
+++ /dev/null
@@ -1,51 +0,0 @@
-page.title=Next Steps
-
-@jd:body
-
-
-<p>Now that you've installed the Android SDK, here are are a few ways to learn Android
-and start developing: </p>
-
-<h3>Start coding</h3>
-<ul>
-  <li>Follow the training class for <a
-href="{@docRoot}training/basics/firstapp/index.html">Building Your First App</a>.
-    <p>This class is an essential first step for new Android developers.</p>
-    <p>It gives you step by step instructions for building a simple app. You’ll learn how to
-create an Android project and run a debuggable version of the app. You'll also learn some
-fundamentals of Android app design, including how to build a simple user interface and handle user
-input.</p>
-</li>
-</ul>
-
-
-<h3>Learn how to design your app</h3>
-<ul>
-  <li>Learn the best practices for Android design and user experience by reading the Android <a
-href="{@docRoot}design/index.html">Design</a> guidelines.</li>
-</ul>
-
-
-<h3>Read up on the API framework</h3>
-<ul>
-  <li>Start reading about fundamental framework topics in the collection of <a
-href="{@docRoot}guide/components/index.html">API Guides</a>.</li>
-  <li>Browse the API specifications in the <a
-  href="{@docRoot}reference/packages.html">Reference</a>.</li>
-</ul>
-
-
-<h3>Explore the development tools</h3>
-<ul>
-  <li>Learn about developing an app with the Android Developer Tools plugin for Eclipse
-    and other tools from the <a
-  href="{@docRoot}tools/workflow/index.html">Workflow</a>.</li>
-</ul>
-
-
-<h3>Explore some code</h3>
-
-<ul>
-  <li>Browse the sample apps available from the Android SDK Manager. You'll find them in
-<code><em>&lt;sdk&gt;</em>/samples/<em>&lt;platform-version&gt;/</em></code>. </li>
-</ul>
diff --git a/docs/html/training/accessibility/index.jd b/docs/html/training/accessibility/index.jd
index 333f9f2..0af1d87 100644
--- a/docs/html/training/accessibility/index.jd
+++ b/docs/html/training/accessibility/index.jd
@@ -1,9 +1,8 @@
 page.title=Implementing Accessibility
+page.tags="navigation","input"
 
 trainingnavtop=true
 startpage=true
-next.title=Developing Accessible Applications
-next.link=accessible-app.html
 
 @jd:body
 
diff --git a/docs/html/training/articles/perf-anr.jd b/docs/html/training/articles/perf-anr.jd
index abef5456..d3b2318 100644
--- a/docs/html/training/articles/perf-anr.jd
+++ b/docs/html/training/articles/perf-anr.jd
@@ -1,4 +1,6 @@
 page.title=Keeping Your App Responsive
+page.tags="threads","asynctask"
+
 page.article=true
 @jd:body
 
diff --git a/docs/html/training/articles/perf-jni.jd b/docs/html/training/articles/perf-jni.jd
index 2abb000..0d1f04e 100644
--- a/docs/html/training/articles/perf-jni.jd
+++ b/docs/html/training/articles/perf-jni.jd
@@ -1,4 +1,6 @@
 page.title=JNI Tips
+page.tags="ndk","native"
+
 page.article=true
 @jd:body
 
diff --git a/docs/html/training/articles/security-ssl.jd b/docs/html/training/articles/security-ssl.jd
index 9a6320b..d3f68e2 100644
--- a/docs/html/training/articles/security-ssl.jd
+++ b/docs/html/training/articles/security-ssl.jd
@@ -1,4 +1,6 @@
 page.title=Security with HTTPS and SSL
+page.tags="network","certificates"
+
 page.article=true
 @jd:body
 
diff --git a/docs/html/training/articles/smp.jd b/docs/html/training/articles/smp.jd
index d46787d..0f667d7 100644
--- a/docs/html/training/articles/smp.jd
+++ b/docs/html/training/articles/smp.jd
@@ -1,4 +1,6 @@
 page.title=SMP Primer for Android
+page.tags="ndk","native"
+
 page.article=true
 @jd:body
 
diff --git a/docs/html/training/backward-compatible-ui/index.jd b/docs/html/training/backward-compatible-ui/index.jd
index f81b5a7..82087a6 100644
--- a/docs/html/training/backward-compatible-ui/index.jd
+++ b/docs/html/training/backward-compatible-ui/index.jd
@@ -1,9 +1,8 @@
 page.title=Creating Backward-Compatible UIs
+page.tags="widgets","support"
 
 trainingnavtop=true
 startpage=true
-next.title=Abstracting the New Implementation
-next.link=abstracting.html
 
 @jd:body
 
diff --git a/docs/html/training/basics/location/index.jd b/docs/html/training/basics/location/index.jd
index 48cfbc3..240bbb2 100644
--- a/docs/html/training/basics/location/index.jd
+++ b/docs/html/training/basics/location/index.jd
@@ -1,9 +1,8 @@
 page.title=Making Your App Location Aware
+page.tags="geolocation","maps"
 
 trainingnavtop=true
 startpage=true
-next.title=Using the Location Manager
-next.link=locationmanager.html
 
 @jd:body
 
diff --git a/docs/html/training/custom-views/index.jd b/docs/html/training/custom-views/index.jd
index cec75b4..1c09e66 100644
--- a/docs/html/training/custom-views/index.jd
+++ b/docs/html/training/custom-views/index.jd
@@ -1,9 +1,8 @@
 page.title=Creating Custom Views
+page.tags="widgets","ui","layout"
 
 trainingnavtop=true
 startpage=true
-next.title=Creating a View Class
-next.link=create-view.html
 
 @jd:body
 
diff --git a/docs/html/training/design-navigation/index.jd b/docs/html/training/design-navigation/index.jd
index af60717..f888c93a 100644
--- a/docs/html/training/design-navigation/index.jd
+++ b/docs/html/training/design-navigation/index.jd
@@ -2,8 +2,6 @@
 
 trainingnavtop=true
 startpage=true
-next.title=Planning Screens and Their Relationships
-next.link=screen-planning.html
 
 @jd:body
 
diff --git a/docs/html/training/enterprise/index.jd b/docs/html/training/enterprise/index.jd
index 0db9009..ac1b565 100644
--- a/docs/html/training/enterprise/index.jd
+++ b/docs/html/training/enterprise/index.jd
@@ -1,4 +1,5 @@
 page.title=Developing for Enterprise
+page.tags="policy","privacy"
 
 trainingnavtop=true
 startpage=true
diff --git a/docs/html/training/gestures/index.jd b/docs/html/training/gestures/index.jd
index 16ca7b0..9d21b08 100644
--- a/docs/html/training/gestures/index.jd
+++ b/docs/html/training/gestures/index.jd
@@ -1,8 +1,8 @@
 page.title=Using Touch Gestures
+page.tags="input","navigation","gesturedetector","scroller"
+
 trainingnavtop=true
 startpage=true
-next.title=Detect Built-in Gestures
-next.link=detector.html
 
 
 @jd:body
diff --git a/docs/html/training/id-auth/index.jd b/docs/html/training/id-auth/index.jd
index 140545c..2bae9c4 100644
--- a/docs/html/training/id-auth/index.jd
+++ b/docs/html/training/id-auth/index.jd
@@ -1,9 +1,8 @@
 page.title=Remembering Users
+page.tags="privacy","oauth","accounts"
 
 trainingnavtop=true
 startpage=true
-next.title=Remembering Your User
-next.link=identify.html
 
 @jd:body
 
diff --git a/docs/html/training/implementing-navigation/index.jd b/docs/html/training/implementing-navigation/index.jd
index ebb4995..990bcfe 100644
--- a/docs/html/training/implementing-navigation/index.jd
+++ b/docs/html/training/implementing-navigation/index.jd
@@ -1,9 +1,8 @@
 page.title=Implementing Effective Navigation
+page.tags="viewpager","tasks","back","up"
 
 trainingnavtop=true
 startpage=true
-next.title=Implementing Lateral Navigation
-next.link=lateral.html
 
 @jd:body
 
diff --git a/docs/html/training/improving-layouts/index.jd b/docs/html/training/improving-layouts/index.jd
index a0ac13e..af29d3f 100644
--- a/docs/html/training/improving-layouts/index.jd
+++ b/docs/html/training/improving-layouts/index.jd
@@ -1,4 +1,5 @@
 page.title=Improving Layout Performance
+page.tags="include","merge","viewstub","listview"
 
 trainingnavtop=true
 startpage=true
diff --git a/docs/html/training/in-app-billing/index.jd b/docs/html/training/in-app-billing/index.jd
index 3d07481..94708b8 100644
--- a/docs/html/training/in-app-billing/index.jd
+++ b/docs/html/training/in-app-billing/index.jd
@@ -1,4 +1,5 @@
 page.title=Selling In-app Products
+page.tags="billing"
 
 trainingnavtop=true
 startpage=true
diff --git a/docs/html/training/keyboard-input/index.jd b/docs/html/training/keyboard-input/index.jd
index ba4e598..7ac79e6 100644
--- a/docs/html/training/keyboard-input/index.jd
+++ b/docs/html/training/keyboard-input/index.jd
@@ -1,4 +1,5 @@
 page.title=Handling Keyboard Input
+page.tags="edittext","accessibility"
 
 trainingnavtop=true
 startpage=true
diff --git a/docs/html/training/load-data-background/index.jd b/docs/html/training/load-data-background/index.jd
index dc9d84a..221ae57 100644
--- a/docs/html/training/load-data-background/index.jd
+++ b/docs/html/training/load-data-background/index.jd
@@ -1,4 +1,6 @@
 page.title=Loading Data in the Background
+page.tags="cursorloader"
+
 trainingnavtop=true
 startpage=true
 
diff --git a/docs/html/training/monitoring-device-state/index.jd b/docs/html/training/monitoring-device-state/index.jd
index 585b669..c3d700a 100644
--- a/docs/html/training/monitoring-device-state/index.jd
+++ b/docs/html/training/monitoring-device-state/index.jd
@@ -1,9 +1,8 @@
 page.title=Optimizing Battery Life
+page.tags="network","internet"
 
 trainingnavtop=true
 startpage=true
-next.title=Monitoring the Battery Level and Charging State
-next.link=battery-monitoring.html
 
 @jd:body
 
diff --git a/docs/html/training/multiple-apks/index.jd b/docs/html/training/multiple-apks/index.jd
index 37286c3..5754da9 100644
--- a/docs/html/training/multiple-apks/index.jd
+++ b/docs/html/training/multiple-apks/index.jd
@@ -1,9 +1,8 @@
 page.title=Maintaining Multiple APKs
+page.tags="support"
 
 trainingnavtop=true
 startpage=true
-next.title=Creating Multiple APKs for Different API Levels
-next.link=api.html
 
 @jd:body
 
diff --git a/docs/html/training/multiple-threads/index.jd b/docs/html/training/multiple-threads/index.jd
index 3ea57c5..cbd42b4 100644
--- a/docs/html/training/multiple-threads/index.jd
+++ b/docs/html/training/multiple-threads/index.jd
@@ -1,4 +1,5 @@
 page.title=Sending Operations to Multiple Threads
+page.tags="threadpool","runnable"
 
 trainingnavtop=true
 startpage=true
diff --git a/docs/html/training/multiscreen/index.jd b/docs/html/training/multiscreen/index.jd
index 23f6564..d09540e 100644
--- a/docs/html/training/multiscreen/index.jd
+++ b/docs/html/training/multiscreen/index.jd
@@ -1,9 +1,8 @@
 page.title=Designing for Multiple Screens
+page.tags="tablet","tv","fragments","support"
 
 trainingnavtop=true
 startpage=true
-next.title=Supporting Different Screen Sizes
-next.link=screensizes.html
 
 @jd:body
 
diff --git a/docs/html/training/notify-user/index.jd b/docs/html/training/notify-user/index.jd
index 510f2c4..51f058f 100644
--- a/docs/html/training/notify-user/index.jd
+++ b/docs/html/training/notify-user/index.jd
@@ -1,8 +1,8 @@
 page.title=Notifying the User
+page.tags="notifications"
+
 trainingnavtop=true
 startpage=true
-next.title=Build a Notification
-next.link=build-notification.html
 
 
 @jd:body
diff --git a/docs/html/training/run-background-service/index.jd b/docs/html/training/run-background-service/index.jd
index 173b87a..3360df5 100644
--- a/docs/html/training/run-background-service/index.jd
+++ b/docs/html/training/run-background-service/index.jd
@@ -1,7 +1,11 @@
 page.title=Running in a Background Service
+page.tags="intentservice"
+
 trainingnavtop=true
 startpage=true
+
 @jd:body
+
 <div id="tb-wrapper">
 <div id="tb">
 <h2>Dependencies and prerequisites</h2>
diff --git a/docs/html/training/search/index.jd b/docs/html/training/search/index.jd
index bfd1618..4070372 100644
--- a/docs/html/training/search/index.jd
+++ b/docs/html/training/search/index.jd
@@ -1,8 +1,8 @@
 page.title=Adding Search Functionality
+page.tags="searchview","database"
+
 trainingnavtop=true
 startpage=true
-next.title=Setting Up the Search Interface
-next.link=setup.html
 
 @jd:body
 
diff --git a/docs/html/training/tv/index.jd b/docs/html/training/tv/index.jd
index ae13c4a..9d15f46 100644
--- a/docs/html/training/tv/index.jd
+++ b/docs/html/training/tv/index.jd
@@ -1,9 +1,8 @@
 page.title=Designing for TV
+page.tags="input","screens"
 
 trainingnavtop=true
 startpage=true
-next.title=Optimizing layouts for TV
-next.link=optimizing-layouts-tv.html
 
 @jd:body
 
diff --git a/graphics/java/android/renderscript/Allocation.java b/graphics/java/android/renderscript/Allocation.java
index 5751331..eb0c164 100644
--- a/graphics/java/android/renderscript/Allocation.java
+++ b/graphics/java/android/renderscript/Allocation.java
@@ -370,11 +370,20 @@
      */
     public void syncAll(int srcLocation) {
         switch (srcLocation) {
-        case USAGE_SCRIPT:
-        case USAGE_GRAPHICS_CONSTANTS:
         case USAGE_GRAPHICS_TEXTURE:
+        case USAGE_SCRIPT:
+            if ((mUsage & USAGE_SHARED) != 0) {
+                copyFrom(mBitmap);
+            }
+            break;
+        case USAGE_GRAPHICS_CONSTANTS:
         case USAGE_GRAPHICS_VERTEX:
             break;
+        case USAGE_SHARED:
+            if ((mUsage & USAGE_SHARED) != 0) {
+                copyTo(mBitmap);
+            }
+            break;
         default:
             throw new RSIllegalArgumentException("Source must be exactly one usage type.");
         }
@@ -1383,7 +1392,7 @@
         // enable optimized bitmap path only with no mipmap and script-only usage
         if (mips == MipmapControl.MIPMAP_NONE &&
             t.getElement().isCompatible(Element.RGBA_8888(rs)) &&
-            usage == (USAGE_SHARED | USAGE_SCRIPT)) {
+            usage == (USAGE_SHARED | USAGE_SCRIPT | USAGE_GRAPHICS_TEXTURE)) {
             int id = rs.nAllocationCreateBitmapBackedAllocation(t.getID(rs), mips.mID, b, usage);
             if (id == 0) {
                 throw new RSRuntimeException("Load failed.");
@@ -1454,7 +1463,7 @@
     static public Allocation createFromBitmap(RenderScript rs, Bitmap b) {
         if (rs.getApplicationContext().getApplicationInfo().targetSdkVersion >= 18) {
             return createFromBitmap(rs, b, MipmapControl.MIPMAP_NONE,
-                                    USAGE_SHARED | USAGE_SCRIPT);
+                                    USAGE_SHARED | USAGE_SCRIPT | USAGE_GRAPHICS_TEXTURE);
         }
         return createFromBitmap(rs, b, MipmapControl.MIPMAP_NONE,
                                 USAGE_GRAPHICS_TEXTURE);
@@ -1672,7 +1681,7 @@
         if (rs.getApplicationContext().getApplicationInfo().targetSdkVersion >= 18) {
             return createFromBitmapResource(rs, res, id,
                                             MipmapControl.MIPMAP_NONE,
-                                            USAGE_SHARED | USAGE_SCRIPT);
+                                            USAGE_SHARED | USAGE_SCRIPT | USAGE_GRAPHICS_TEXTURE);
         }
         return createFromBitmapResource(rs, res, id,
                                         MipmapControl.MIPMAP_NONE,
diff --git a/location/java/android/location/IGeofenceProvider.aidl b/location/java/android/location/IGeofenceProvider.aidl
new file mode 100644
index 0000000..5a5fdc6
--- /dev/null
+++ b/location/java/android/location/IGeofenceProvider.aidl
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.location;
+
+import android.hardware.location.IGeofenceHardware;
+
+/**
+ * An interface for location providers implementing the Geofencing service
+ *
+ * {@hide}
+ */
+interface IGeofenceProvider {
+    void setGeofenceHardware(in IGeofenceHardware proxy);
+}
diff --git a/location/java/android/location/IGpsGeofenceHardware.aidl b/location/java/android/location/IGpsGeofenceHardware.aidl
new file mode 100644
index 0000000..764bf8e
--- /dev/null
+++ b/location/java/android/location/IGpsGeofenceHardware.aidl
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2013, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.location;
+
+/**
+ * GPS hardware geofence
+ *
+ * @hide
+ */
+interface IGpsGeofenceHardware
+{
+    boolean isHardwareGeofenceSupported();
+    boolean addCircularHardwareGeofence(int geofenceId, double latitude, double
+            longitude, double radius, int lastTransition, int monitorTransition,
+            int notificationResponsiveness, int unknownTimer);
+    boolean removeHardwareGeofence(int geofenceId);
+    boolean pauseHardwareGeofence(int geofenceId);
+    boolean resumeHardwareGeofence(int geofenceId, int monitorTransition);
+}
diff --git a/location/lib/java/com/android/location/provider/GeofenceProvider.java b/location/lib/java/com/android/location/provider/GeofenceProvider.java
new file mode 100644
index 0000000..2618f34
--- /dev/null
+++ b/location/lib/java/com/android/location/provider/GeofenceProvider.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.location.provider;
+
+import android.hardware.location.GeofenceHardware;
+import android.hardware.location.IGeofenceHardware;
+import android.os.IBinder;
+
+import android.location.IGeofenceProvider;
+import android.util.Log;
+
+import java.lang.Long;
+
+/**
+ * Base class for geofence providers implemented as unbundled services.
+ *
+ * <p>Geofence providers can be implemented as services and return the result of
+ * {@link com.android.location.provider.GeofenceProvider#getBinder()} in its getBinder() method.
+ *
+ * <p>IMPORTANT: This class is effectively a public API for unbundled
+ * applications, and must remain API stable. See README.txt in the root
+ * of this package for more information.
+ */
+public abstract class GeofenceProvider {
+
+    private GeofenceHardware mGeofenceHardware;
+
+    private IGeofenceProvider.Stub mProvider = new IGeofenceProvider.Stub() {
+        public void setGeofenceHardware(IGeofenceHardware hardwareProxy) {
+            mGeofenceHardware = new GeofenceHardware(hardwareProxy);
+            onGeofenceHardwareChange(mGeofenceHardware);
+        }
+    };
+
+    /**
+     * Returns the Binder interface for the geofence provider.
+     * This is intended to be used for the onBind() method of
+     * a service that implements a geofence service.
+     *
+     * @return the IBinder instance for the provider
+     */
+    public IBinder getBinder() {
+        return mProvider;
+    }
+
+    /**
+     * Called when GeofenceHardware object becomes available.
+     *
+     * @param geofenceHardware Geofence Hardware object. This can be null
+     *        when for some reason the service connection gets disconnected.
+     */
+    public abstract void onGeofenceHardwareChange(GeofenceHardware geofenceHardware);
+}
diff --git a/media/java/android/media/MediaRouter.java b/media/java/android/media/MediaRouter.java
index 795c3c2..61c55a5 100644
--- a/media/java/android/media/MediaRouter.java
+++ b/media/java/android/media/MediaRouter.java
@@ -767,10 +767,19 @@
         boolean wantScan = false;
         boolean blockScan = false;
         WifiDisplay[] oldDisplays = oldStatus != null ?
-                oldStatus.getRememberedDisplays() : new WifiDisplay[0];
-        WifiDisplay[] newDisplays = newStatus.getRememberedDisplays();
-        WifiDisplay[] availableDisplays = newStatus.getAvailableDisplays();
-        WifiDisplay activeDisplay = newStatus.getActiveDisplay();
+                oldStatus.getRememberedDisplays() : WifiDisplay.EMPTY_ARRAY;
+        WifiDisplay[] newDisplays;
+        WifiDisplay[] availableDisplays;
+        WifiDisplay activeDisplay;
+
+        if (newStatus.getFeatureState() == WifiDisplayStatus.FEATURE_STATE_ON) {
+            newDisplays = newStatus.getRememberedDisplays();
+            availableDisplays = newStatus.getAvailableDisplays();
+            activeDisplay = newStatus.getActiveDisplay();
+        } else {
+            newDisplays = availableDisplays = WifiDisplay.EMPTY_ARRAY;
+            activeDisplay = null;
+        }
 
         for (int i = 0; i < newDisplays.length; i++) {
             final WifiDisplay d = newDisplays[i];
diff --git a/policy/src/com/android/internal/policy/impl/keyguard/KeyguardWidgetPager.java b/policy/src/com/android/internal/policy/impl/keyguard/KeyguardWidgetPager.java
index ad5e257..1bcee4e 100644
--- a/policy/src/com/android/internal/policy/impl/keyguard/KeyguardWidgetPager.java
+++ b/policy/src/com/android/internal/policy/impl/keyguard/KeyguardWidgetPager.java
@@ -594,13 +594,12 @@
         animateOutlinesAndSidePages(false);
     }
 
-    public void showInitialPageHints() {
-        mShowingInitialHints = true;
+    void updateChildrenContentAlpha(float sidePageAlpha) {
         int count = getChildCount();
         for (int i = 0; i < count; i++) {
             KeyguardWidgetFrame child = getWidgetPageAt(i);
             if (i != mCurrentPage) {
-                child.setBackgroundAlpha(KeyguardWidgetFrame.OUTLINE_ALPHA_MULTIPLIER);
+                child.setBackgroundAlpha(sidePageAlpha);
                 child.setContentAlpha(0f);
             } else {
                 child.setBackgroundAlpha(0f);
@@ -609,9 +608,15 @@
         }
     }
 
+    public void showInitialPageHints() {
+        mShowingInitialHints = true;
+        updateChildrenContentAlpha(KeyguardWidgetFrame.OUTLINE_ALPHA_MULTIPLIER);
+    }
+
     @Override
     void setCurrentPage(int currentPage) {
         super.setCurrentPage(currentPage);
+        updateChildrenContentAlpha(0.0f);
         updateWidgetFramesImportantForAccessibility();
     }
 
diff --git a/policy/src/com/android/internal/policy/impl/keyguard/PagedView.java b/policy/src/com/android/internal/policy/impl/keyguard/PagedView.java
index 539ec1a..186a013 100644
--- a/policy/src/com/android/internal/policy/impl/keyguard/PagedView.java
+++ b/policy/src/com/android/internal/policy/impl/keyguard/PagedView.java
@@ -756,6 +756,8 @@
     @Override
     public void onChildViewRemoved(View parent, View child) {
         mForceScreenScrolled = true;
+        invalidate();
+        invalidateCachedOffsets();
     }
 
     protected void invalidateCachedOffsets() {
diff --git a/services/java/com/android/server/LocationManagerService.java b/services/java/com/android/server/LocationManagerService.java
index bcb7cb7..1e1cf5a 100644
--- a/services/java/com/android/server/LocationManagerService.java
+++ b/services/java/com/android/server/LocationManagerService.java
@@ -54,19 +54,17 @@
 import android.os.PowerManager;
 import android.os.Process;
 import android.os.RemoteException;
-import android.os.ServiceManager;
 import android.os.SystemClock;
 import android.os.UserHandle;
 import android.os.WorkSource;
 import android.provider.Settings;
 import android.util.Log;
 import android.util.Slog;
-
-import com.android.internal.app.IAppOpsService;
 import com.android.internal.content.PackageMonitor;
 import com.android.internal.location.ProviderProperties;
 import com.android.internal.location.ProviderRequest;
 import com.android.server.location.GeocoderProxy;
+import com.android.server.location.GeofenceProxy;
 import com.android.server.location.GeofenceManager;
 import com.android.server.location.GpsLocationProvider;
 import com.android.server.location.LocationBlacklist;
@@ -338,11 +336,11 @@
         addProviderLocked(passiveProvider);
         mEnabledProviders.add(passiveProvider.getName());
         mPassiveProvider = passiveProvider;
+        // Create a gps location provider
+        GpsLocationProvider gpsProvider = new GpsLocationProvider(mContext, this,
+                mLocationHandler.getLooper());
 
         if (GpsLocationProvider.isSupported()) {
-            // Create a gps location provider
-            GpsLocationProvider gpsProvider = new GpsLocationProvider(mContext, this,
-                    mLocationHandler.getLooper());
             mGpsStatusProvider = gpsProvider.getGpsStatusProvider();
             mNetInitiatedListener = gpsProvider.getNetInitiatedListener();
             addProviderLocked(gpsProvider);
@@ -406,6 +404,14 @@
         if (mGeocodeProvider == null) {
             Slog.e(TAG,  "no geocoder provider found");
         }
+
+        // bind to geofence provider
+        GeofenceProxy provider = GeofenceProxy.createAndBind(mContext, providerPackageNames,
+                mLocationHandler, gpsProvider.getGpsGeofenceProxy());
+        if (provider == null) {
+            Slog.e(TAG,  "no geofence provider found");
+        }
+
     }
 
     /**
diff --git a/services/java/com/android/server/accounts/AccountManagerService.java b/services/java/com/android/server/accounts/AccountManagerService.java
index 14d808f..fd7cd78 100644
--- a/services/java/com/android/server/accounts/AccountManagerService.java
+++ b/services/java/com/android/server/accounts/AccountManagerService.java
@@ -22,6 +22,7 @@
 import android.accounts.AccountAuthenticatorResponse;
 import android.accounts.AccountManager;
 import android.accounts.AuthenticatorDescription;
+import android.accounts.CantAddAccountActivity;
 import android.accounts.GrantCredentialsPermissionActivity;
 import android.accounts.IAccountAuthenticator;
 import android.accounts.IAccountAuthenticatorResponse;
@@ -1456,6 +1457,14 @@
                         "User is not allowed to add an account!");
             } catch (RemoteException re) {
             }
+            Intent cantAddAccount = new Intent(mContext, CantAddAccountActivity.class);
+            cantAddAccount.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            long identityToken = clearCallingIdentity();
+            try {
+                mContext.startActivityAsUser(cantAddAccount, UserHandle.CURRENT);
+            } finally {
+                restoreCallingIdentity(identityToken);
+            }
             return;
         }
 
diff --git a/services/java/com/android/server/am/ActivityStack.java b/services/java/com/android/server/am/ActivityStack.java
index 3d2e912..0f1700d 100644
--- a/services/java/com/android/server/am/ActivityStack.java
+++ b/services/java/com/android/server/am/ActivityStack.java
@@ -47,6 +47,7 @@
 import android.content.res.Resources;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.Config;
+import android.net.Uri;
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.Handler;
@@ -4600,11 +4601,13 @@
 
     private final void logStartActivity(int tag, ActivityRecord r,
             TaskRecord task) {
+        final Uri data = r.intent.getData();
+        final String strData = data != null ? data.toSafeString() : null;
+
         EventLog.writeEvent(tag,
                 r.userId, System.identityHashCode(r), task.taskId,
                 r.shortComponentName, r.intent.getAction(),
-                r.intent.getType(), r.intent.getDataString(),
-                r.intent.getFlags());
+                r.intent.getType(), strData, r.intent.getFlags());
     }
 
     /**
diff --git a/services/java/com/android/server/content/ContentService.java b/services/java/com/android/server/content/ContentService.java
index 68cf5fc..f82cf01 100644
--- a/services/java/com/android/server/content/ContentService.java
+++ b/services/java/com/android/server/content/ContentService.java
@@ -459,7 +459,7 @@
         try {
             SyncManager syncManager = getSyncManager();
             if (syncManager != null) {
-                return syncManager.getSyncStorageEngine().getIsSyncable(
+                return syncManager.getIsSyncable(
                         account, userId, providerName);
             }
         } finally {
diff --git a/services/java/com/android/server/content/SyncManager.java b/services/java/com/android/server/content/SyncManager.java
index b3f9bf1..1c883ec 100644
--- a/services/java/com/android/server/content/SyncManager.java
+++ b/services/java/com/android/server/content/SyncManager.java
@@ -21,6 +21,7 @@
 import android.accounts.AccountManager;
 import android.app.ActivityManager;
 import android.app.AlarmManager;
+import android.app.AppGlobals;
 import android.app.Notification;
 import android.app.NotificationManager;
 import android.app.PendingIntent;
@@ -41,6 +42,7 @@
 import android.content.SyncResult;
 import android.content.SyncStatusInfo;
 import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ProviderInfo;
 import android.content.pm.RegisteredServicesCache;
@@ -491,6 +493,36 @@
         return mSyncStorageEngine;
     }
 
+    public int getIsSyncable(Account account, int userId, String providerName) {
+        int isSyncable = mSyncStorageEngine.getIsSyncable(account, userId, providerName);
+        UserInfo userInfo = UserManager.get(mContext).getUserInfo(userId);
+
+        // If it's not a restricted user, return isSyncable
+        if (userInfo == null || !userInfo.isRestricted()) return isSyncable;
+
+        // Else check if the sync adapter has opted-in or not
+        RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo =
+                mSyncAdapters.getServiceInfo(
+                SyncAdapterType.newKey(providerName, account.type), userId);
+        if (syncAdapterInfo == null) return isSyncable;
+
+        PackageInfo pInfo = null;
+        try {
+            pInfo = AppGlobals.getPackageManager().getPackageInfo(
+                syncAdapterInfo.componentName.getPackageName(), 0, userId);
+            if (pInfo == null) return isSyncable;
+        } catch (RemoteException re) {
+            // Shouldn't happen
+            return isSyncable;
+        }
+        if (pInfo.restrictedAccountType != null
+                && pInfo.restrictedAccountType.equals(account.type)) {
+            return isSyncable;
+        } else {
+            return 0;
+        }
+    }
+
     private void ensureAlarmService() {
         if (mAlarmService == null) {
             mAlarmService = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
@@ -608,7 +640,7 @@
             }
 
             for (String authority : syncableAuthorities) {
-                int isSyncable = mSyncStorageEngine.getIsSyncable(account.account, account.userId,
+                int isSyncable = getIsSyncable(account.account, account.userId,
                         authority);
                 if (isSyncable == 0) {
                     continue;
@@ -1930,7 +1962,7 @@
                     continue;
                 }
 
-                if (mSyncStorageEngine.getIsSyncable(info.account, info.userId, info.authority)
+                if (getIsSyncable(info.account, info.userId, info.authority)
                         == 0) {
                     continue;
                 }
@@ -2069,7 +2101,7 @@
                     }
 
                     // drop this sync request if it isn't syncable
-                    int syncableState = mSyncStorageEngine.getIsSyncable(
+                    int syncableState = getIsSyncable(
                             op.account, op.userId, op.authority);
                     if (syncableState == 0) {
                         operationIterator.remove();
diff --git a/services/java/com/android/server/location/GeofenceProxy.java b/services/java/com/android/server/location/GeofenceProxy.java
new file mode 100644
index 0000000..36e9fcc
--- /dev/null
+++ b/services/java/com/android/server/location/GeofenceProxy.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.server.location;
+
+import android.content.ComponentName;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.hardware.location.GeofenceHardwareService;
+import android.hardware.location.IGeofenceHardware;
+import android.location.IGeofenceProvider;
+import android.location.IGpsGeofenceHardware;
+import android.content.Context;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Message;
+import android.os.RemoteException;
+import android.os.UserHandle;
+import android.util.Log;
+import com.android.server.ServiceWatcher;
+
+import java.util.List;
+
+/**
+ * @hide
+ */
+public final class GeofenceProxy {
+    private static final String TAG = "GeofenceProxy";
+    private static final String SERVICE_ACTION =
+            "com.android.location.service.GeofenceProvider";
+    private ServiceWatcher mServiceWatcher;
+    private Context mContext;
+    private IGeofenceHardware mGeofenceHardware;
+    private IGpsGeofenceHardware mGpsGeofenceHardware;
+
+    private static final int GEOFENCE_PROVIDER_CONNECTED = 1;
+    private static final int GEOFENCE_HARDWARE_CONNECTED = 2;
+    private static final int GEOFENCE_HARDWARE_DISCONNECTED = 3;
+    private static final int GEOFENCE_GPS_HARDWARE_CONNECTED = 4;
+    private static final int GEOFENCE_GPS_HARDWARE_DISCONNECTED = 5;
+
+    private Runnable mRunnable = new Runnable() {
+        @Override
+        public void run() {
+            mHandler.sendEmptyMessage(GEOFENCE_PROVIDER_CONNECTED);
+        }
+    };
+
+    public static GeofenceProxy createAndBind(Context context,
+            List<String> initialPackageNames, Handler handler, IGpsGeofenceHardware gpsGeofence) {
+        GeofenceProxy proxy = new GeofenceProxy(context, initialPackageNames, handler, gpsGeofence);
+        if (proxy.bindGeofenceProvider()) {
+            return proxy;
+        } else {
+            return null;
+        }
+    }
+
+    private GeofenceProxy(Context context, List<String> initialPackageName, Handler handler,
+            IGpsGeofenceHardware gpsGeofence) {
+        mContext = context;
+        mServiceWatcher = new ServiceWatcher(context, TAG, SERVICE_ACTION, initialPackageName,
+                mRunnable, handler);
+        mGpsGeofenceHardware = gpsGeofence;
+        bindHardwareGeofence();
+    }
+
+    private boolean bindGeofenceProvider() {
+        return mServiceWatcher.start();
+    }
+
+    private IGeofenceProvider getGeofenceProviderService() {
+        return IGeofenceProvider.Stub.asInterface(mServiceWatcher.getBinder());
+    }
+
+    private void bindHardwareGeofence() {
+        mContext.bindServiceAsUser(new Intent(mContext, GeofenceHardwareService.class),
+                mServiceConnection, Context.BIND_AUTO_CREATE, UserHandle.OWNER);
+    }
+
+    private ServiceConnection mServiceConnection = new ServiceConnection() {
+        @Override
+        public void onServiceConnected(ComponentName name, IBinder service) {
+            mGeofenceHardware = IGeofenceHardware.Stub.asInterface(service);
+            mHandler.sendEmptyMessage(GEOFENCE_HARDWARE_CONNECTED);
+        }
+
+        @Override
+        public void onServiceDisconnected(ComponentName name) {
+            mGeofenceHardware = null;
+            mHandler.sendEmptyMessage(GEOFENCE_HARDWARE_DISCONNECTED);
+        }
+    };
+
+    private void setGeofenceHardwareInProvider() {
+        try {
+            getGeofenceProviderService().setGeofenceHardware(mGeofenceHardware);
+        } catch (RemoteException e) {
+            Log.e(TAG, "Remote Exception: setGeofenceHardwareInProvider: " + e);
+        }
+    }
+
+    private void setGpsGeofence() {
+        try {
+            mGeofenceHardware.setGpsGeofenceHardware(mGpsGeofenceHardware);
+        } catch (RemoteException e) {
+            Log.e(TAG, "Error while connecting to GeofenceHardwareService");
+        }
+    }
+
+
+    // This needs to be reworked, when more services get added,
+    // Might need a state machine or add a framework utility class,
+    private Handler mHandler = new Handler() {
+        private boolean mGeofenceHardwareConnected = false;
+        private boolean mGeofenceProviderConnected = false;
+
+
+        @Override
+        public void handleMessage(Message msg) {
+            switch (msg.what) {
+                case GEOFENCE_PROVIDER_CONNECTED:
+                    mGeofenceProviderConnected = true;
+                    if (mGeofenceHardwareConnected) {
+                        setGeofenceHardwareInProvider();
+                    }
+                    break;
+                case GEOFENCE_HARDWARE_CONNECTED:
+                    setGpsGeofence();
+                    mGeofenceHardwareConnected = true;
+                    if (mGeofenceProviderConnected) {
+                        setGeofenceHardwareInProvider();
+                    }
+                    break;
+                case GEOFENCE_HARDWARE_DISCONNECTED:
+                    mGeofenceHardwareConnected = false;
+                    setGeofenceHardwareInProvider();
+                    break;
+            }
+        }
+    };
+}
diff --git a/services/java/com/android/server/location/GpsLocationProvider.java b/services/java/com/android/server/location/GpsLocationProvider.java
index 3552b6a..1ebff67 100644
--- a/services/java/com/android/server/location/GpsLocationProvider.java
+++ b/services/java/com/android/server/location/GpsLocationProvider.java
@@ -24,7 +24,10 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.database.Cursor;
+import android.hardware.location.GeofenceHardwareImpl;
+import android.hardware.location.IGeofenceHardware;
 import android.location.Criteria;
+import android.location.IGpsGeofenceHardware;
 import android.location.IGpsStatusListener;
 import android.location.IGpsStatusProvider;
 import android.location.ILocationManager;
@@ -314,6 +317,8 @@
     // only modified on handler thread
     private WorkSource mClientSource = new WorkSource();
 
+    private GeofenceHardwareImpl mGeofenceHardwareImpl;
+
     private final IGpsStatusProvider mGpsStatusProvider = new IGpsStatusProvider.Stub() {
         @Override
         public void addGpsStatusListener(IGpsStatusListener listener) throws RemoteException {
@@ -367,6 +372,10 @@
         return mGpsStatusProvider;
     }
 
+    public IGpsGeofenceHardware getGpsGeofenceProxy() {
+        return mGpsGeofenceBinder;
+    }
+
     private final BroadcastReceiver mBroadcastReciever = new BroadcastReceiver() {
         @Override public void onReceive(Context context, Intent intent) {
             String action = intent.getAction();
@@ -918,6 +927,31 @@
         return result;
     }
 
+    private IGpsGeofenceHardware mGpsGeofenceBinder = new IGpsGeofenceHardware.Stub() {
+        public boolean isHardwareGeofenceSupported() {
+            return native_is_geofence_supported();
+        }
+
+        public boolean addCircularHardwareGeofence(int geofenceId, double latitude,
+                double longitude, double radius, int lastTransition, int monitorTransitions,
+                int notificationResponsiveness, int unknownTimer) {
+            return native_add_geofence(geofenceId, latitude, longitude, radius,
+                    lastTransition, monitorTransitions, notificationResponsiveness, unknownTimer);
+        }
+
+        public boolean removeHardwareGeofence(int geofenceId) {
+            return native_remove_geofence(geofenceId);
+        }
+
+        public boolean pauseHardwareGeofence(int geofenceId) {
+            return native_pause_geofence(geofenceId);
+        }
+
+        public boolean resumeHardwareGeofence(int geofenceId, int monitorTransition) {
+            return native_resume_geofence(geofenceId, monitorTransition);
+        }
+    };
+
     private boolean deleteAidingData(Bundle extras) {
         int flags;
 
@@ -1017,6 +1051,7 @@
         return ((mEngineCapabilities & capability) != 0);
     }
 
+
     /**
      * called from native code to update our position.
      */
@@ -1320,6 +1355,73 @@
         sendMessage(DOWNLOAD_XTRA_DATA, 0, null);
     }
 
+    /**
+     * Called from native to report GPS Geofence transition
+     * All geofence callbacks are called on the same thread
+     */
+    private void reportGeofenceTransition(int geofenceId, int flags, double latitude,
+            double longitude, double altitude, float speed, float bearing, float accuracy,
+            long timestamp, int transition, long transitionTimestamp) {
+        if (mGeofenceHardwareImpl == null) {
+            mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
+        }
+        mGeofenceHardwareImpl.reportGpsGeofenceTransition(geofenceId, flags, latitude, longitude,
+           altitude, speed, bearing, accuracy, timestamp, transition, transitionTimestamp);
+    }
+
+    /**
+     * called from native code to report GPS status change.
+     */
+    private void reportGeofenceStatus(int status, int flags, double latitude,
+            double longitude, double altitude, float speed, float bearing, float accuracy,
+            long timestamp) {
+        if (mGeofenceHardwareImpl == null) {
+            mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
+        }
+        mGeofenceHardwareImpl.reportGpsGeofenceStatus(status, flags, latitude, longitude, altitude,
+            speed, bearing, accuracy, timestamp);
+    }
+
+    /**
+     * called from native code - Geofence Add callback
+     */
+    private void reportGeofenceAddStatus(int geofenceId, int status) {
+        if (mGeofenceHardwareImpl == null) {
+            mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
+        }
+        mGeofenceHardwareImpl.reportGpsGeofenceAddStatus(geofenceId, status);
+    }
+
+    /**
+     * called from native code - Geofence Remove callback
+     */
+    private void reportGeofenceRemoveStatus(int geofenceId, int status) {
+        if (mGeofenceHardwareImpl == null) {
+            mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
+        }
+        mGeofenceHardwareImpl.reportGpsGeofenceRemoveStatus(geofenceId, status);
+    }
+
+    /**
+     * called from native code - Geofence Pause callback
+     */
+    private void reportGeofencePauseStatus(int geofenceId, int status) {
+        if (mGeofenceHardwareImpl == null) {
+            mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
+        }
+        mGeofenceHardwareImpl.reportGpsGeofencePauseStatus(geofenceId, status);
+    }
+
+    /**
+     * called from native code - Geofence Resume callback
+     */
+    private void reportGeofenceResumeStatus(int geofenceId, int status) {
+        if (mGeofenceHardwareImpl == null) {
+            mGeofenceHardwareImpl = GeofenceHardwareImpl.getInstance(mContext);
+        }
+        mGeofenceHardwareImpl.reportGpsGeofenceResumeStatus(geofenceId, status);
+    }
+
     //=============================================================
     // NI Client support
     //=============================================================
@@ -1650,4 +1752,13 @@
 
     private native void native_update_network_state(boolean connected, int type,
             boolean roaming, boolean available, String extraInfo, String defaultAPN);
+
+    // Hardware Geofence support.
+    private static native boolean native_is_geofence_supported();
+    private static native boolean native_add_geofence(int geofenceId, double latitude,
+            double longitude, double radius, int lastTransition,int monitorTransitions,
+            int notificationResponsivenes, int unknownTimer);
+    private static native boolean native_remove_geofence(int geofenceId);
+    private static native boolean native_resume_geofence(int geofenceId, int transitions);
+    private static native boolean native_pause_geofence(int geofenceId);
 }
diff --git a/services/java/com/android/server/pm/PackageManagerService.java b/services/java/com/android/server/pm/PackageManagerService.java
index cc9b785..154c4e8 100644
--- a/services/java/com/android/server/pm/PackageManagerService.java
+++ b/services/java/com/android/server/pm/PackageManagerService.java
@@ -8249,6 +8249,24 @@
             updatePermissionsLPw(newPackage.packageName, newPackage,
                     UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
                             ? UPDATE_PERMISSIONS_ALL : 0));
+            // For system-bundled packages, we assume that installing an upgraded version
+            // of the package implies that the user actually wants to run that new code,
+            // so we enable the package.
+            if (isSystemApp(newPackage)) {
+                // NB: implicit assumption that system package upgrades apply to all users
+                if (DEBUG_INSTALL) {
+                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
+                }
+                PackageSetting ps = mSettings.mPackages.get(pkgName);
+                if (ps != null) {
+                    if (res.origUsers != null) {
+                        for (int userHandle : res.origUsers) {
+                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
+                                    userHandle, installerPackageName);
+                        }
+                    }
+                }
+            }
             res.name = pkgName;
             res.uid = newPackage.applicationInfo.uid;
             res.pkg = newPackage;
diff --git a/services/java/com/android/server/pm/UserManagerService.java b/services/java/com/android/server/pm/UserManagerService.java
index aa1b2ff..3ef9370 100644
--- a/services/java/com/android/server/pm/UserManagerService.java
+++ b/services/java/com/android/server/pm/UserManagerService.java
@@ -963,7 +963,7 @@
     @Override
     public List<RestrictionEntry> getApplicationRestrictions(String packageName, int userId) {
         if (UserHandle.getCallingUserId() != userId
-                || Binder.getCallingUid() != getUidForPackage(packageName)) {
+                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
             checkManageUsersPermission("Only system can get restrictions for other users/apps");
         }
         synchronized (mPackagesLock) {
@@ -976,7 +976,7 @@
     public void setApplicationRestrictions(String packageName, List<RestrictionEntry> entries,
             int userId) {
         if (UserHandle.getCallingUserId() != userId
-                || Binder.getCallingUid() != getUidForPackage(packageName)) {
+                || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
             checkManageUsersPermission("Only system can set restrictions for other users/apps");
         }
         synchronized (mPackagesLock) {
@@ -986,11 +986,14 @@
     }
 
     private int getUidForPackage(String packageName) {
+        long ident = Binder.clearCallingIdentity();
         try {
             return mContext.getPackageManager().getApplicationInfo(packageName,
                     PackageManager.GET_UNINSTALLED_PACKAGES).uid;
         } catch (NameNotFoundException nnfe) {
             return -1;
+        } finally {
+            Binder.restoreCallingIdentity(ident);
         }
     }
 
diff --git a/services/java/com/android/server/power/PowerManagerService.java b/services/java/com/android/server/power/PowerManagerService.java
index 2652739..1203e02 100644
--- a/services/java/com/android/server/power/PowerManagerService.java
+++ b/services/java/com/android/server/power/PowerManagerService.java
@@ -432,7 +432,7 @@
             mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
             mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
 
-            SensorManager sensorManager = new SystemSensorManager(mHandler.getLooper());
+            SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
 
             // The notifier runs on the system server's main looper so as not to interfere
             // with the animations and other critical functions of the power manager.
diff --git a/services/java/com/android/server/wm/WindowStateAnimator.java b/services/java/com/android/server/wm/WindowStateAnimator.java
index 452f76d..c07174b 100644
--- a/services/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/java/com/android/server/wm/WindowStateAnimator.java
@@ -505,20 +505,20 @@
         public void setAlpha(float alpha) {
             super.setAlpha(alpha);
             if (alpha != mSurfaceTraceAlpha) {
+                mSurfaceTraceAlpha = alpha;
                 Slog.v(SURFACE_TAG, "setAlpha: " + this + ". Called by "
                         + Debug.getCallers(3));
             }
-            mSurfaceTraceAlpha = alpha;
         }
 
         @Override
         public void setLayer(int zorder) {
             super.setLayer(zorder);
             if (zorder != mLayer) {
+                mLayer = zorder;
                 Slog.v(SURFACE_TAG, "setLayer: " + this + ". Called by "
                         + Debug.getCallers(3));
             }
-            mLayer = zorder;
 
             sSurfaces.remove(this);
             int i;
@@ -535,20 +535,20 @@
         public void setPosition(float x, float y) {
             super.setPosition(x, y);
             if (x != mPosition.x || y != mPosition.y) {
+                mPosition.set(x, y);
                 Slog.v(SURFACE_TAG, "setPosition: " + this + ". Called by "
                         + Debug.getCallers(3));
             }
-            mPosition.set(x, y);
         }
 
         @Override
         public void setSize(int w, int h) {
             super.setSize(w, h);
             if (w != mSize.x || h != mSize.y) {
+                mSize.set(w, h);
                 Slog.v(SURFACE_TAG, "setSize: " + this + ". Called by "
                         + Debug.getCallers(3));
             }
-            mSize.set(w, h);
         }
 
         @Override
@@ -556,10 +556,10 @@
             super.setWindowCrop(crop);
             if (crop != null) {
                 if (!crop.equals(mWindowCrop)) {
+                    mWindowCrop.set(crop);
                     Slog.v(SURFACE_TAG, "setWindowCrop: " + this + ". Called by "
                             + Debug.getCallers(3));
                 }
-                mWindowCrop.set(crop);
             }
         }
 
@@ -567,28 +567,28 @@
         public void setLayerStack(int layerStack) {
             super.setLayerStack(layerStack);
             if (layerStack != mLayerStack) {
+                mLayerStack = layerStack;
                 Slog.v(SURFACE_TAG, "setLayerStack: " + this + ". Called by " + Debug.getCallers(3));
             }
-            mLayerStack = layerStack;
         }
 
         @Override
         public void hide() {
             super.hide();
             if (mShown) {
+                mShown = false;
                 Slog.v(SURFACE_TAG, "hide: " + this + ". Called by "
                         + Debug.getCallers(3));
             }
-            mShown = false;
         }
         @Override
         public void show() {
             super.show();
             if (!mShown) {
+                mShown = true;
                 Slog.v(SURFACE_TAG, "show: " + this + ". Called by "
                         + Debug.getCallers(3));
             }
-            mShown = true;
         }
 
         @Override
diff --git a/services/jni/com_android_server_location_GpsLocationProvider.cpp b/services/jni/com_android_server_location_GpsLocationProvider.cpp
index 036fc43..98de12a 100644
--- a/services/jni/com_android_server_location_GpsLocationProvider.cpp
+++ b/services/jni/com_android_server_location_GpsLocationProvider.cpp
@@ -43,6 +43,12 @@
 static jmethodID method_requestRefLocation;
 static jmethodID method_requestSetID;
 static jmethodID method_requestUtcTime;
+static jmethodID method_reportGeofenceTransition;
+static jmethodID method_reportGeofenceStatus;
+static jmethodID method_reportGeofenceAddStatus;
+static jmethodID method_reportGeofenceRemoveStatus;
+static jmethodID method_reportGeofencePauseStatus;
+static jmethodID method_reportGeofenceResumeStatus;
 
 static const GpsInterface* sGpsInterface = NULL;
 static const GpsXtraInterface* sGpsXtraInterface = NULL;
@@ -50,6 +56,7 @@
 static const GpsNiInterface* sGpsNiInterface = NULL;
 static const GpsDebugInterface* sGpsDebugInterface = NULL;
 static const AGpsRilInterface* sAGpsRilInterface = NULL;
+static const GpsGeofencingInterface* sGpsGeofencingInterface = NULL;
 
 // temporary storage for GPS callbacks
 static GpsSvStatus  sGpsSvStatus;
@@ -107,7 +114,7 @@
 
 static void set_capabilities_callback(uint32_t capabilities)
 {
-    ALOGD("set_capabilities_callback: %ld\n", capabilities);
+    ALOGD("set_capabilities_callback: %du\n", capabilities);
     JNIEnv* env = AndroidRuntime::getJNIEnv();
     env->CallVoidMethod(mCallbacksObj, method_setEngineCapabilities, capabilities);
     checkAndClearExceptionFromCallback(env, __FUNCTION__);
@@ -233,6 +240,97 @@
     create_thread_callback,
 };
 
+static void gps_geofence_transition_callback(int32_t geofence_id,  GpsLocation* location,
+        int32_t transition, GpsUtcTime timestamp)
+{
+    JNIEnv* env = AndroidRuntime::getJNIEnv();
+
+    env->CallVoidMethod(mCallbacksObj, method_reportGeofenceTransition, geofence_id,
+            location->flags, (jdouble)location->latitude, (jdouble)location->longitude,
+            (jdouble)location->altitude,
+            (jfloat)location->speed, (jfloat)location->bearing,
+            (jfloat)location->accuracy, (jlong)location->timestamp,
+            transition, timestamp);
+    checkAndClearExceptionFromCallback(env, __FUNCTION__);
+};
+
+static void gps_geofence_status_callback(int32_t status, GpsLocation* location)
+{
+    JNIEnv* env = AndroidRuntime::getJNIEnv();
+    jint flags = 0;
+    jdouble latitude = 0;
+    jdouble longitude = 0;
+    jdouble altitude = 0;
+    jfloat speed = 0;
+    jfloat bearing = 0;
+    jfloat accuracy = 0;
+    jlong timestamp = 0;
+    if (location != NULL) {
+        flags = location->flags;
+        latitude = location->latitude;
+        longitude = location->longitude;
+        altitude = location->altitude;
+        speed = location->speed;
+        bearing = location->bearing;
+        accuracy = location->accuracy;
+        timestamp = location->timestamp;
+    }
+
+    env->CallVoidMethod(mCallbacksObj, method_reportGeofenceStatus, status,
+            flags, latitude, longitude, altitude, speed, bearing, accuracy, timestamp);
+    checkAndClearExceptionFromCallback(env, __FUNCTION__);
+};
+
+static void gps_geofence_add_callback(int32_t geofence_id, int32_t status)
+{
+    JNIEnv* env = AndroidRuntime::getJNIEnv();
+    if (status != GPS_GEOFENCE_OPERATION_SUCCESS) {
+        ALOGE("Error in geofence_add_callback: %d\n", status);
+    }
+    env->CallVoidMethod(mCallbacksObj, method_reportGeofenceAddStatus, geofence_id, status);
+    checkAndClearExceptionFromCallback(env, __FUNCTION__);
+};
+
+static void gps_geofence_remove_callback(int32_t geofence_id, int32_t status)
+{
+    JNIEnv* env = AndroidRuntime::getJNIEnv();
+    if (status != GPS_GEOFENCE_OPERATION_SUCCESS) {
+        ALOGE("Error in geofence_remove_callback: %d\n", status);
+    }
+    env->CallVoidMethod(mCallbacksObj, method_reportGeofenceRemoveStatus, geofence_id, status);
+    checkAndClearExceptionFromCallback(env, __FUNCTION__);
+};
+
+static void gps_geofence_resume_callback(int32_t geofence_id, int32_t status)
+{
+    JNIEnv* env = AndroidRuntime::getJNIEnv();
+    if (status != GPS_GEOFENCE_OPERATION_SUCCESS) {
+        ALOGE("Error in geofence_resume_callback: %d\n", status);
+    }
+    env->CallVoidMethod(mCallbacksObj, method_reportGeofenceResumeStatus, geofence_id, status);
+    checkAndClearExceptionFromCallback(env, __FUNCTION__);
+};
+
+static void gps_geofence_pause_callback(int32_t geofence_id, int32_t status)
+{
+    JNIEnv* env = AndroidRuntime::getJNIEnv();
+    if (status != GPS_GEOFENCE_OPERATION_SUCCESS) {
+        ALOGE("Error in geofence_pause_callback: %d\n", status);
+    }
+    env->CallVoidMethod(mCallbacksObj, method_reportGeofencePauseStatus, geofence_id, status);
+    checkAndClearExceptionFromCallback(env, __FUNCTION__);
+};
+
+GpsGeofenceCallbacks sGpsGeofenceCallbacks = {
+    gps_geofence_transition_callback,
+    gps_geofence_status_callback,
+    gps_geofence_add_callback,
+    gps_geofence_remove_callback,
+    gps_geofence_pause_callback,
+    gps_geofence_resume_callback,
+    create_thread_callback,
+};
+
 static void android_location_GpsLocationProvider_class_init_native(JNIEnv* env, jclass clazz) {
     int err;
     hw_module_t* module;
@@ -249,6 +347,18 @@
     method_requestRefLocation = env->GetMethodID(clazz,"requestRefLocation","(I)V");
     method_requestSetID = env->GetMethodID(clazz,"requestSetID","(I)V");
     method_requestUtcTime = env->GetMethodID(clazz,"requestUtcTime","()V");
+    method_reportGeofenceTransition = env->GetMethodID(clazz,"reportGeofenceTransition",
+            "(IIDDDFFFJIJ)V");
+    method_reportGeofenceStatus = env->GetMethodID(clazz,"reportGeofenceStatus",
+            "(IIDDDFFFJ)V");
+    method_reportGeofenceAddStatus = env->GetMethodID(clazz,"reportGeofenceAddStatus",
+            "(II)V");
+    method_reportGeofenceRemoveStatus = env->GetMethodID(clazz,"reportGeofenceRemoveStatus",
+            "(II)V");
+    method_reportGeofenceResumeStatus = env->GetMethodID(clazz,"reportGeofenceResumeStatus",
+            "(II)V");
+    method_reportGeofencePauseStatus = env->GetMethodID(clazz,"reportGeofencePauseStatus",
+            "(II)V");
 
     err = hw_get_module(GPS_HARDWARE_MODULE_ID, (hw_module_t const**)&module);
     if (err == 0) {
@@ -270,6 +380,8 @@
             (const GpsDebugInterface*)sGpsInterface->get_extension(GPS_DEBUG_INTERFACE);
         sAGpsRilInterface =
             (const AGpsRilInterface*)sGpsInterface->get_extension(AGPS_RIL_INTERFACE);
+        sGpsGeofencingInterface =
+            (const GpsGeofencingInterface*)sGpsInterface->get_extension(GPS_GEOFENCING_INTERFACE);
     }
 }
 
@@ -287,7 +399,7 @@
     if (!sGpsInterface || sGpsInterface->init(&sGpsCallbacks) != 0)
         return false;
 
-    // if XTRA initialization fails we will disable it by sGpsXtraInterface to null,
+    // if XTRA initialization fails we will disable it by sGpsXtraInterface to NULL,
     // but continue to allow the rest of the GPS interface to work.
     if (sGpsXtraInterface && sGpsXtraInterface->init(&sGpsXtraCallbacks) != 0)
         sGpsXtraInterface = NULL;
@@ -297,6 +409,8 @@
         sGpsNiInterface->init(&sGpsNiCallbacks);
     if (sAGpsRilInterface)
         sAGpsRilInterface->init(&sAGpsRilCallbacks);
+    if (sGpsGeofencingInterface)
+        sGpsGeofencingInterface->init(&sGpsGeofenceCallbacks);
 
     return true;
 }
@@ -565,6 +679,62 @@
     }
 }
 
+static jboolean android_location_GpsLocationProvider_is_geofence_supported(JNIEnv* env,
+          jobject obj) {
+    if (sGpsGeofencingInterface != NULL) {
+        return JNI_TRUE;
+    }
+    return JNI_FALSE;
+}
+
+static jboolean android_location_GpsLocationProvider_add_geofence(JNIEnv* env, jobject obj,
+        jint geofence_id, jdouble latitude, jdouble longitude, jdouble radius,
+        jint last_transition, jint monitor_transition, jint notification_responsiveness,
+        jint unknown_timer) {
+    if (sGpsGeofencingInterface != NULL) {
+        sGpsGeofencingInterface->add_geofence_area(geofence_id, latitude, longitude,
+                radius, last_transition, monitor_transition, notification_responsiveness,
+                unknown_timer);
+        return JNI_TRUE;
+    } else {
+        ALOGE("Geofence interface not available");
+    }
+    return JNI_FALSE;
+}
+
+static jboolean android_location_GpsLocationProvider_remove_geofence(JNIEnv* env, jobject obj,
+        jint geofence_id) {
+    if (sGpsGeofencingInterface != NULL) {
+        sGpsGeofencingInterface->remove_geofence_area(geofence_id);
+        return JNI_TRUE;
+    } else {
+        ALOGE("Geofence interface not available");
+    }
+    return JNI_FALSE;
+}
+
+static jboolean android_location_GpsLocationProvider_pause_geofence(JNIEnv* env, jobject obj,
+        jint geofence_id) {
+    if (sGpsGeofencingInterface != NULL) {
+        sGpsGeofencingInterface->pause_geofence(geofence_id);
+        return JNI_TRUE;
+    } else {
+        ALOGE("Geofence interface not available");
+    }
+    return JNI_FALSE;
+}
+
+static jboolean android_location_GpsLocationProvider_resume_geofence(JNIEnv* env, jobject obj,
+        jint geofence_id, jint monitor_transition) {
+    if (sGpsGeofencingInterface != NULL) {
+        sGpsGeofencingInterface->resume_geofence(geofence_id, monitor_transition);
+        return JNI_TRUE;
+    } else {
+        ALOGE("Geofence interface not available");
+    }
+    return JNI_FALSE;
+}
+
 static JNINativeMethod sMethods[] = {
      /* name, signature, funcPtr */
     {"class_init_native", "()V", (void *)android_location_GpsLocationProvider_class_init_native},
@@ -591,6 +761,11 @@
     {"native_agps_ni_message", "([BI)V", (void *)android_location_GpsLocationProvider_agps_send_ni_message},
     {"native_get_internal_state", "()Ljava/lang/String;", (void*)android_location_GpsLocationProvider_get_internal_state},
     {"native_update_network_state", "(ZIZZLjava/lang/String;Ljava/lang/String;)V", (void*)android_location_GpsLocationProvider_update_network_state },
+    {"native_is_geofence_supported", "()Z", (void*) android_location_GpsLocationProvider_is_geofence_supported},
+    {"native_add_geofence", "(IDDDIIII)Z", (void *)android_location_GpsLocationProvider_add_geofence},
+    {"native_remove_geofence", "(I)Z", (void *)android_location_GpsLocationProvider_remove_geofence},
+    {"native_pause_geofence", "(I)Z", (void *)android_location_GpsLocationProvider_pause_geofence},
+    {"native_resume_geofence", "(II)Z", (void *)android_location_GpsLocationProvider_resume_geofence}
 };
 
 int register_android_server_location_GpsLocationProvider(JNIEnv* env)